update for beta universally
[framework/messaging/email-service.git] / email-core / em-core-utils.c
1 /*
2 *  email-service
3 *
4 * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
5 *
6 * Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
7
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 *
20 */
21
22
23 /******************************************************************************
24  * File: em-core-utils.c
25  * Desc: Mail Utils
26  *
27  * Auth:
28  *
29  * History:
30  *      2006.08.16 : created
31  *****************************************************************************/
32 #include <glib.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <ctype.h>
37 #include <errno.h>
38 #include <stdio.h>
39 #include <dlfcn.h>
40 #include <sys/time.h>
41 #include <unistd.h>
42 #include <sys/stat.h>
43 #include <sys/vfs.h>
44 #include <vconf.h>
45 #include <regex.h>
46 #include <malloc.h>
47
48 #include <contacts-svc.h>
49 #include <notification.h>
50
51 #include "emf-types.h"
52 #include "em-core-global.h"
53 #include "em-core-utils.h"
54 #include "emf-dbglog.h"
55 #include "em-core-mesg.h"
56 #include "em-core-event.h"
57 #include "em-core-mailbox.h"
58 #include "em-core-account.h" 
59 #include "em-core-mailbox-sync.h" 
60 #include "em-core-mime.h"
61 #include "em-core-sound.h" 
62 #include "Msg_Convert.h"
63
64 #define LED_TIMEOUT_SECS          12 
65 #define G_DISPLAY_LENGTH          256
66
67 #define DIR_SEPERATOR_CH          '/'
68 #define EMAIL_CH_QUOT             '"'
69 #define EMAIL_CH_BRACKET_S        '<'
70 #define EMAIL_CH_BRACKET_E        '>'
71 #define EMAIL_CH_COMMA            ','
72 #define EMAIL_CH_SEMICOLON        ';'
73 #define EMAIL_CH_ROUND_BRACKET_S  '('
74 #define EMAIL_CH_ROUND_BRACKET_E  ')'
75 #define EMAIL_CH_SQUARE_BRACKET_S '['
76 #define EMAIL_CH_SQUARE_BRACKET_E ']'
77 #define EMAIL_CH_SPACE            ' '
78
79 static char _g_display[G_DISPLAY_LENGTH];
80
81
82 typedef struct  _em_transaction_info_type_t {
83         int mail_id;
84         int     handle; 
85         struct _em_transaction_info_type_t *next;
86
87 } em_transaction_info_type_t;
88
89 em_transaction_info_type_t  *g_transaction_info_list;
90
91 static emf_option_t g_mail_option = 
92 {
93         0, /* priority                  */
94         1, /* keep_local_copy */
95         0, /* req_delivery_receipt */
96         0, /* req_read_receipt */
97         0, /* download_limit */
98         0, /* block_address */
99         0, /* block_subject */
100         NULL, /*  diplay name */
101 };
102
103 static emf_session_t g_session_list[SESSION_MAX] = { {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0},};
104
105
106 typedef struct em_core_account_list_t em_core_account_list_t;
107 struct em_core_account_list_t {
108         emf_account_t *account;
109         em_core_account_list_t *next;
110 };
111
112 static em_core_account_list_t **g_account_reference = NULL;
113
114 EXPORT_API 
115 char *em_core_convert_mutf7_to_utf8(char *mailbox_name)
116 {
117         EM_DEBUG_FUNC_BEGIN();
118         return (char *)(utf8_from_mutf7((unsigned char *)mailbox_name));
119 }
120
121 EXPORT_API int em_core_set_account_reference(em_core_account_list_t **account_list, int account_num, int *err_code)
122 {
123         g_account_reference = (em_core_account_list_t **)account_list;
124         return 1;
125 }
126
127 emf_option_t *em_core_get_option(int *err_code)
128 {
129         if (err_code != NULL)
130                 *err_code = EMF_ERROR_NONE;
131
132         return &g_mail_option;
133 }
134
135 EXPORT_API int em_core_set_option(emf_option_t *opt, int *err_code)
136 {
137         EM_DEBUG_FUNC_BEGIN("opt[%p], err_code[%p]", opt, err_code);
138         
139         int err = EMF_ERROR_NONE;
140         
141         if (!opt) {
142                 EM_DEBUG_EXCEPTION("opt[%p]", opt);
143                 
144                 if (err_code != NULL)
145                         *err_code = EMF_ERROR_INVALID_PARAM;
146                 return false;
147         }
148         
149         memset(_g_display, 0, G_DISPLAY_LENGTH);
150         memcpy(&g_mail_option, opt, sizeof(g_mail_option));
151
152         if (opt->display_name_from && opt->display_name_from[0] != '\0')  {
153                 strncpy(_g_display, opt->display_name_from, G_DISPLAY_LENGTH - 1);
154                 g_mail_option.display_name_from = _g_display;
155         }
156         else
157                 g_mail_option.display_name_from = NULL;
158         
159         if (err_code != NULL)
160                 *err_code = err;
161         
162         return true;
163 }
164
165         
166
167
168
169 /*  in smtp case, path argument must be ENCODED_PATH_SMTP */
170 int em_core_get_long_encoded_path_with_account_info(emf_account_t *account, char *path, int delimiter, char **long_enc_path, int *err_code)
171 {
172         EM_PROFILE_BEGIN(emCorelongEncodedpath);
173         EM_DEBUG_FUNC_BEGIN("account[%p], path[%s], delimiter[%d], long_enc_path[%p], err_code[%p]", account, path, delimiter, long_enc_path, err_code);
174         
175         int ret = false;
176         int error = EMF_ERROR_NONE;
177         char *p = NULL;
178         
179         size_t long_enc_path_len = 0;
180         
181         if (path == NULL || (path && strncmp(path, ENCODED_PATH_SMTP, strlen(ENCODED_PATH_SMTP)) != 0)) {               /*  imap or pop3 */
182                 EM_DEBUG_LOG("account->receiving_server_addr[%p]", account->receiving_server_addr);
183                 EM_DEBUG_LOG("account->receiving_server_addr[%s]", account->receiving_server_addr);
184                 
185                 if (!account->receiving_server_addr) {
186                         EM_DEBUG_EXCEPTION("account->receiving_server_addr is null");
187                         error = EMF_ERROR_INVALID_ACCOUNT;
188                         goto FINISH_OFF;
189                 }
190         
191                 long_enc_path_len = strlen(account->receiving_server_addr) + (path ? strlen(path) : 0) + 64;
192                 
193                 *long_enc_path = em_core_malloc(long_enc_path_len);
194                 if (!*long_enc_path)  {
195                         EM_DEBUG_EXCEPTION("malloc failed...");
196                         error = EMF_ERROR_OUT_OF_MEMORY;
197                         goto FINISH_OFF;
198                 }
199                 
200                 p = *long_enc_path;
201                 
202                 /*  ex:"{mai.test.com:143/imap} or {mai.test.com:143/imap/tls}my-mailbox" */
203
204                 SNPRINTF(p, long_enc_path_len, "{%s:%d/%s/user=%d",
205                         account->receiving_server_addr,
206                         account->port_num,
207                         account->receiving_server_type == EMF_SERVER_TYPE_POP3 ? "pop3" : "imap", account->account_id);
208                 
209                 if (account->use_security & 0x01)  {
210                         strncat(p, "/ssl", long_enc_path_len-(strlen(p)+1));
211                         /* strcat(p, "/tryssl"); */
212                 }
213
214                 /* Currently, receiving servers doesn't require tls. 
215                 if (account->use_security & 0x02)
216                         strncat(p, "/tls", long_enc_path_len-(strlen(p)+1));
217                 else
218                         strncat(p, "/notls", long_enc_path_len-(strlen(p)+1));
219                 */
220
221                 if (account->apop) {
222                         EM_DEBUG_LOG("em_core_get_long_encoded_path - apop - %d", account->apop);
223                         strncat(p, "/apop", long_enc_path_len-(strlen(p)+1));
224                         EM_DEBUG_LOG("long_enc_path - %s", p);
225                 }
226         }
227         else  {         /*  smtp */
228                 long_enc_path_len = strlen(account->sending_server_addr) + 64;
229                 
230                 *long_enc_path = em_core_malloc(strlen(account->sending_server_addr) + 64);
231                 if (!*long_enc_path) {
232                         EM_DEBUG_EXCEPTION("\t malloc failed...\n");
233                         
234                         error = EMF_ERROR_OUT_OF_MEMORY;
235                         goto FINISH_OFF;
236                 }
237                 
238                 p = *long_enc_path;
239                 
240                 /*  ex:"mail.test.com:25/smtp" */
241
242                 SNPRINTF(p, long_enc_path_len, "%s:%d/%s",
243                         account->sending_server_addr,
244                         account->sending_port_num,
245                         "smtp");
246                 
247                 if (account->sending_auth) {
248                         SNPRINTF(p + strlen(p), long_enc_path_len-(strlen(p)), "/user=%d", account->account_id);
249                 }
250                 
251                 if (account->sending_security & 0x01) {
252                         strncat(p, "/ssl", long_enc_path_len-(strlen(p)+1));
253                         /* strcat(p, "/tryssl"); */
254                 }
255                 if (account->sending_security & 0x02)
256                         strncat(p, "/tls", long_enc_path_len-(strlen(p)+1));
257                 else
258                         strncat(p, "/notls", long_enc_path_len-(strlen(p)+1));
259         }
260
261         if (path == NULL || (path && strncmp(path, ENCODED_PATH_SMTP, strlen(ENCODED_PATH_SMTP)) != 0)) {
262                 strncat(p, "}", long_enc_path_len-(strlen(p)+1));
263                 
264                 if (path != NULL) {
265                         char *enc_name = NULL;
266                         
267                         if (!em_core_get_encoded_mailbox_name(path, &enc_name, &error))  {
268                                 EM_DEBUG_EXCEPTION("em_core_get_encoded_mailbox_name failed - %d", error);
269                                 *long_enc_path = NULL;
270                                 goto FINISH_OFF;
271                         }
272                         
273                         if (enc_name)  {
274                                 strncat(p, enc_name, long_enc_path_len-(strlen(p)+1));
275                                 EM_SAFE_FREE(enc_name);
276                         }
277                 }
278         }
279         
280         ret = true;
281         
282 FINISH_OFF:
283         if (ret != true)
284                 EM_SAFE_FREE(p);
285         
286         if (err_code != NULL)
287                 *err_code = error;
288         EM_PROFILE_END(emCorelongEncodedpath);
289         return ret;
290 }
291
292 int em_core_get_long_encoded_path(int account_id, char *path, int delimiter, char **long_enc_path, int *err_code)
293 {
294         EM_PROFILE_BEGIN(emCorelongEncodedpath);
295         EM_DEBUG_FUNC_BEGIN("account_id[%d], delimiter[%d], long_enc_path[%p], err_code[%p]", account_id, delimiter, long_enc_path, err_code);
296         
297         int ret = false;
298         int error = EMF_ERROR_NONE;
299         
300         emf_account_t *ref_account = em_core_get_account_reference(account_id);
301         if (!ref_account)  {
302                 EM_DEBUG_EXCEPTION("em_core_get_account_reference failed [%d]", account_id);
303                 error = EMF_ERROR_INVALID_ACCOUNT;
304                 goto FINISH_OFF;
305         }
306
307         if (em_core_get_long_encoded_path_with_account_info(ref_account, path, delimiter, long_enc_path, &error) == false) {
308                 EM_DEBUG_EXCEPTION("em_core_get_long_encoded_path_with_account_info failed [%d]", error);
309                 goto FINISH_OFF;
310         }
311
312         ret = true;
313         
314 FINISH_OFF:
315         if (err_code != NULL)
316                 *err_code = error;
317         EM_PROFILE_END(emCorelongEncodedpath);
318         return ret;
319 }
320
321 int em_core_upper_path(char *path)
322 {
323         int i = 0, is_utf7 = 0, len = path ? (int)strlen(path) : -1;
324         for (; i < len; i++) {
325                 if (path[i] == '&' || path[i] == 5) {
326                         is_utf7 = 1;
327                 }
328                 else {
329                         if (is_utf7) {
330                                 if (path[i] == '-') is_utf7 = 0;
331                         }
332                         else {
333                                 path[i] = toupper(path[i]);
334                         }
335                 }
336         }
337
338         return 1;
339 }
340
341 int em_core_get_encoded_mailbox_name(char *name, char **enc_name, int *err_code)
342 {
343         EM_DEBUG_FUNC_BEGIN("name[%s], enc_name[%p], err_code[%p]", name, enc_name, err_code);
344         
345         if (!name || !enc_name)  {
346                 if (err_code != NULL)
347                         *err_code = EMF_ERROR_INVALID_PARAM;
348                 EM_DEBUG_FUNC_END();
349                 return false;
350         }
351         
352         /* encoding mailbox name (Charset->UTF8->UTF7) */
353
354         *enc_name = em_core_malloc(strlen(name)+1);
355         if (*enc_name == NULL) {
356                 EM_DEBUG_EXCEPTION("malloc failed...");
357                 if (err_code != NULL)
358                         *err_code = EMF_ERROR_OUT_OF_MEMORY;
359                 EM_DEBUG_FUNC_END();
360                 return false;
361         }
362         
363         strcpy(*enc_name, name);
364         
365         if (err_code != NULL)
366                 *err_code = EMF_ERROR_NONE;
367
368         EM_DEBUG_FUNC_END();
369         return true;
370 }
371
372 int em_core_upper_string(char *str)
373 {
374         int i = str ? (int)strlen(str) : -1;
375         for (; i >= 0; i--) 
376                 str[i] = toupper(str[i]);
377         return 1;
378 }
379
380 int em_core_get_temp_file_name(char **filename, int *err_code)
381 {
382         EM_DEBUG_FUNC_BEGIN("filename[%p], err_code[%p]", filename, err_code);
383         
384         int ret = false;
385         int error = EMF_ERROR_NONE;
386         
387         if (filename == NULL) {
388                 EM_DEBUG_EXCEPTION("\t filename[%p]\n", filename);
389                 error = EMF_ERROR_INVALID_PARAM;
390                 goto FINISH_OFF;
391         }
392         
393         char tempname[512] = {0x00, };
394         struct timeval tv;
395         
396
397         gettimeofday(&tv, NULL);
398         srand(tv.tv_usec);
399
400         /* Create Directory If deleted by user*/
401         em_storage_create_dir_if_delete();
402         
403         SNPRINTF(tempname, sizeof(tempname), "%s%c%s%c%d", MAILHOME, DIR_SEPERATOR_CH, MAILTEMP, DIR_SEPERATOR_CH, rand());
404         
405         char *p = EM_SAFE_STRDUP(tempname);
406         if (p == NULL) {
407                 EM_DEBUG_EXCEPTION("\t strdup failed...\n");
408                 error = EMF_ERROR_OUT_OF_MEMORY;
409                 goto FINISH_OFF;
410         }
411         
412         *filename = p;
413         
414         ret = true;
415
416 FINISH_OFF:
417         if (err_code != NULL)
418                 *err_code = error;
419         EM_DEBUG_FUNC_END();
420         return ret;
421 }
422
423 int em_core_get_file_name(char *path, char **filename, int *err_code)
424 {
425         EM_DEBUG_FUNC_BEGIN("path[%s], filename[%p], err_code[%p]", path, filename, err_code);
426         
427         int ret = false;
428         int error = EMF_ERROR_NONE;
429         
430         if (!path || !filename) {
431                 EM_DEBUG_EXCEPTION("path[%p], filename[%p]", path, filename);
432                 
433                 error = EMF_ERROR_INVALID_PARAM;
434                 goto FINISH_OFF;
435         }
436         
437         int i = (int)strlen(path);
438         
439         /*  get filename */
440         for (; i >= 0; i--)
441                 if (path[i] == DIR_SEPERATOR_CH)
442                         break;
443         
444         *filename = path + i + 1;
445         
446         ret = true;
447         
448 FINISH_OFF:
449                 if (err_code != NULL)
450                 *err_code = error;
451         EM_DEBUG_FUNC_END();
452         return ret;
453 }
454
455 int em_core_get_file_size(char *path, int *size, int *err_code)
456 {
457         EM_DEBUG_FUNC_BEGIN("path[%s], size[%p], err_code[%p]", path, size, err_code);
458         
459         int ret = false;
460         int error = EMF_ERROR_NONE;
461         
462         if ((path == NULL) || (size == NULL)) {
463                 EM_DEBUG_EXCEPTION("\t path[%p], size[%p]\n", path, size);
464                 
465                 error = EMF_ERROR_INVALID_PARAM;
466                 goto FINISH_OFF;
467         }
468         
469         struct stat st_buf;
470         
471         if (stat(path, &st_buf) < 0)  {
472                 EM_DEBUG_EXCEPTION("\t stat failed - %s\n", path);
473                 
474                 error = EMF_ERROR_SYSTEM_FAILURE;
475                 goto FINISH_OFF;
476         }
477         
478         *size = st_buf.st_size;
479         
480         ret = true;
481         
482 FINISH_OFF:
483         if (err_code != NULL)
484                 *err_code = error;
485         EM_DEBUG_FUNC_END();
486         return ret;
487 }
488
489 void* em_core_malloc(unsigned len)
490 {
491         /* EM_DEBUG_LOG("Memory allocation size[%d] bytes", len); */
492         void *p = NULL;
493
494         if (len <= 0) {
495                 EM_DEBUG_EXCEPTION("len should be positive.[%d]", len);
496                 return NULL;
497         }
498         
499         p = malloc(len);
500
501         if (p)
502                 memset(p, 0x00, len);
503         else
504                 EM_DEBUG_EXCEPTION("malloc failed");
505         return p;
506 }
507
508 EXPORT_API char* em_core_replace_string(char *source_string, char *old_string, char *new_string)
509 {
510         EM_DEBUG_FUNC_BEGIN();
511         char *result_buffer = NULL;
512         char *p = NULL;
513         int   buffer_length = 0;
514
515         EM_IF_NULL_RETURN_VALUE(source_string, NULL);
516         EM_IF_NULL_RETURN_VALUE(old_string, NULL);
517         EM_IF_NULL_RETURN_VALUE(new_string, NULL);
518
519         p = strstr(source_string, old_string);
520
521         if (p == NULL) {
522                 EM_DEBUG_EXCEPTION("old_string not found in source_string");
523                 EM_DEBUG_FUNC_END("return NULL");
524                 return NULL;
525         }
526         
527         EM_DEBUG_LOG("p[%s] ", p); /*  temp */
528         buffer_length   = strlen(source_string) + 1024;
529         EM_DEBUG_LOG("buffer_length[%d] ", buffer_length); /*  temp */
530         result_buffer  = (char *)em_core_malloc(buffer_length);
531
532         if (!result_buffer) {
533                 EM_DEBUG_EXCEPTION("em_core_malloc failed");
534                 return NULL;
535         }
536         
537         strncpy(result_buffer, source_string, p - source_string);
538         snprintf(result_buffer + strlen(result_buffer), buffer_length - strlen(result_buffer), "%s%s", new_string, p + strlen(old_string));
539
540         EM_DEBUG_FUNC_END("result_buffer[%s]", result_buffer);
541         return result_buffer;
542 }
543
544 static int _em_core_check_host(char *host)
545 {
546         if (!host)
547                 return 0;
548         return strncmp(host, ".SYNTAX-ERROR.", strlen(".SYNTAX-ERROR."));
549 }
550
551 void em_core_skip_whitespace(char *addr_str, char **pAddr)
552 {
553         EM_DEBUG_FUNC_BEGIN("addr_str[%p]", addr_str);
554         
555         if (!addr_str)
556                 return ;
557         char *str = addr_str;
558         char ptr[strlen(str)+1]  ;
559         int i, j = 0;
560         
561         str = addr_str ;
562         for (i = 0; str[i] != NULL_CHAR ; i++) {
563                 if (str[i] != SPACE && str[i] != TAB && str[i] != CR && str[i] != LF)
564                         ptr[j++] = str[i];
565         }
566         ptr[j] = NULL_CHAR;
567
568         *pAddr = EM_SAFE_STRDUP(ptr);
569         EM_DEBUG_FUNC_END("ptr[%s]", ptr);
570
571
572 EXPORT_API char* em_core_skip_whitespace_without_strdup(char *source_string)
573 {
574         EM_DEBUG_FUNC_BEGIN("source_string[%p]", source_string);
575         
576         if (!source_string)
577                 return NULL;
578         int i;
579         
580         for (i = 0; source_string[i] != NULL_CHAR ; i++) {
581                 if (source_string[i] != SPACE) /*  || source_string[i] != TAB || source_string[i] != CR || source_string[i] || LF) */
582                         break;  
583         }
584
585         EM_DEBUG_FUNC_END("i[%d]", i);
586         return source_string + i;
587
588
589 int em_core_get_address_count(char *addr_str, int *count, int *err_code)
590 {
591         EM_DEBUG_FUNC_BEGIN("addr_str[%s], count[%p], err_code[%p]", addr_str, count, err_code);
592         
593         int ret = false;
594         int error = EMF_ERROR_NONE;
595         
596         ADDRESS *addr = NULL;
597         ADDRESS *p_addr = NULL;
598         int i = 0, j;
599         char *p = NULL;
600
601
602         if (!count)  {
603                 EM_DEBUG_EXCEPTION("addr_str[%s], count[%p]", addr_str, count);
604                 error = EMF_ERROR_INVALID_PARAM;
605                 goto FINISH_OFF;
606         }
607         
608         if (addr_str != NULL)  {
609                 em_core_skip_whitespace(addr_str, &p);
610                 EM_DEBUG_LOG("em_core_skip_whitespace[p][%s]", p);
611
612
613                 for (i = 0, j = strlen(p); i < j; i++) 
614                         if (p[i] == ';') p[i] = ',';
615                 rfc822_parse_adrlist(&addr, p, NULL);
616                 EM_SAFE_FREE(p);
617
618         
619                 for (p_addr = addr, i = 0; p_addr; p_addr = p_addr->next, i++)  {
620                         if (p_addr->mailbox && p_addr->host) {  
621                                 if (!strncmp(p_addr->mailbox, "UNEXPECTED_DATA_AFTER_ADDRESS", strlen("UNEXPECTED_DATA_AFTER_ADDRESS")) || !strncmp(p_addr->mailbox, "INVALID_ADDRESS", strlen("INVALID_ADDRESS")) || !strncmp(p_addr->host, ".SYNTAX-ERROR.", strlen(".SYNTAX-ERROR."))) {
622                                         EM_DEBUG_LOG("Invalid address ");
623                                         continue;
624                                 }
625                         }                       
626                         if ((!p_addr->mailbox) || (_em_core_check_host(p_addr->host) == 0)) {
627                                 EM_DEBUG_EXCEPTION("\t invalid address : mailbox[%s], host[%s]\n", p_addr->mailbox, p_addr->host);
628                                 
629                                 error = EMF_ERROR_INVALID_ADDRESS;
630                                 /* goto FINISH_OFF; */
631                         }
632                 }
633         }
634
635         *count = i;
636         if (error != EMF_ERROR_INVALID_ADDRESS)
637         ret = true;
638         
639 FINISH_OFF:
640         if (addr) 
641                 mail_free_address(&addr);
642         
643         if (err_code != NULL)
644                 *err_code = error;
645         EM_DEBUG_FUNC_END();
646         return ret;
647 }
648
649 EXPORT_API int em_core_set_network_error(int err_code)
650 {
651         emf_session_t *session = NULL;
652
653         EM_DEBUG_FUNC_BEGIN();
654
655         em_core_get_current_session(&session);
656
657         if (!session)
658                 return false;
659
660         session->network = err_code;
661         EM_DEBUG_FUNC_END();
662         return true;
663 }
664
665 int em_core_get_empty_session(emf_session_t **session)
666 {
667         EM_DEBUG_FUNC_BEGIN("session[%p]", session);
668         
669         /*  lock()... */
670         
671         int i;
672         
673         for (i = 0; i < SESSION_MAX; i++)  {
674                 if (!g_session_list[i].status)  {
675                         memset(g_session_list+i, 0x00, sizeof(emf_session_t));
676                         g_session_list[i].tid = GPOINTER_TO_INT(THREAD_SELF());
677                         g_session_list[i].status = true;
678                         break;
679                 }
680         }
681         
682         /*  unlock()... */
683         
684         if (session != NULL)
685                 *session = (i != SESSION_MAX) ? &g_session_list[i] : NULL;
686         EM_DEBUG_FUNC_END();
687         return (i != SESSION_MAX) ? true : false;
688 }
689
690 int em_core_clear_session(emf_session_t *session)
691 {
692         EM_DEBUG_FUNC_BEGIN();
693         
694         if (session)
695                 memset(session, 0x00, sizeof(emf_session_t));
696         EM_DEBUG_FUNC_END();
697         return true;
698 }
699
700 int em_core_get_current_session(emf_session_t **session)
701 {
702         EM_DEBUG_FUNC_BEGIN("session[%p]", session);
703         
704         int i;
705         
706         for (i = 0; i < SESSION_MAX; i++)  {
707                 if (g_session_list[i].tid == GPOINTER_TO_INT(THREAD_SELF())) {
708                         if (session)
709                                 *session = g_session_list + i;
710                         
711                         break;
712                 }
713         }
714         
715         if (session)
716                 *session = (i != SESSION_MAX) ? g_session_list + i : NULL;
717         EM_DEBUG_FUNC_END();
718         return (i != SESSION_MAX) ? true : false;
719 }
720
721 int em_core_check_unread_mail()
722 {
723         EM_DEBUG_FUNC_BEGIN();
724         
725         int ret = false;
726         int err = EMF_ERROR_NONE;
727         int total_unread_count = 0;
728         int total_mail_count = 0;
729         emf_mailbox_t mailbox;
730         
731         memset(&mailbox, 0x00, sizeof(emf_mailbox_t));
732
733         /* ALL_ACCOUNT used, so not calling em_storage_get_mailboxname_by_mailbox_type to get mailbox name */
734         mailbox.account_id = ALL_ACCOUNT;
735         mailbox.name = NULL;
736         
737         if (!em_core_mailbox_get_mail_count(&mailbox, &total_mail_count, &total_unread_count, &err))  {
738                 EM_DEBUG_EXCEPTION("em_core_mailbox_get_mail_count failed [%d]", err);
739                 goto FINISH_OFF;
740         }
741         
742         EM_DEBUG_LOG("total_unread_count [%d]", total_unread_count);
743         
744         /*  set unread count to badge */
745         if ( vconf_set_int(VCONF_KEY_UNREAD_MAIL_COUNT, total_unread_count) != 0 ) {
746                 EM_DEBUG_EXCEPTION("vconf_set_int failed");
747                 err = EMF_ERROR_GCONF_FAILURE;
748                 goto FINISH_OFF;
749         }
750
751         EM_DEBUG_LOG("db/badge/com.samsung.email - set[%d]", total_unread_count);
752
753         ret = true;
754 FINISH_OFF:
755
756         return ret;
757 }
758
759 int em_core_add_notification(int account_id, int mail_id, char *title, char *content, time_t log_time)
760 {
761         EM_DEBUG_FUNC_BEGIN();
762         int ret = true;
763
764         EM_DEBUG_FUNC_END();
765         return ret;     
766 }
767
768 int em_core_show_popup(int id, emf_action_t action, int error)
769 {
770         EM_DEBUG_FUNC_BEGIN("id[%d], action[%d], error[%d]", id, action, error);
771
772         int ret = false;
773         time_t log_time = 0;
774         struct tm *log_time_tm;
775
776         time(&log_time);
777         log_time_tm = localtime(&log_time);
778         log_time = mktime(log_time_tm);
779
780         EM_DEBUG_LOG("sec[%d], min[%d], hour[%d], day[%d], month[%d], year[%d]" ,log_time_tm->tm_sec, log_time_tm->tm_min, log_time_tm->tm_hour, log_time_tm->tm_mday, log_time_tm->tm_mon, log_time_tm->tm_year);
781 #ifdef __FEATURE_PROGRESS_IN_OUTBOX__
782         if (action == EMF_ACTION_SEND_MAIL && error != EMF_ERROR_CANCELLED) {
783         /*  In case email is cancelled using cancel button in Outbox there is no need to show Cancel/Retry Pop up */
784 #else
785         if (action == EMF_ACTION_SEND_MAIL) {
786 #endif           
787                 emf_mail_tbl_t *mail_table_data = NULL;
788
789                 if (error == 0) /*  error 0 means 'this is not error' */
790                         return true;
791
792                 if (id <= 0) {
793                         EM_DEBUG_LOG("Invalid mail_id");
794                         return false;
795                 }
796                 
797                 if (!em_storage_get_mail_by_id(id, &mail_table_data, true, NULL)) {
798                         EM_DEBUG_LOG("Mail not found");
799                         return false;
800                 }
801
802                 if (!em_core_add_notification(mail_table_data->account_id + 1000, id, "Failed to send mail", mail_table_data->subject, log_time)) {
803                         EM_DEBUG_EXCEPTION("em_core_notification_set error");
804                         return false;
805                 }
806
807                 if (!em_storage_free_mail(&mail_table_data, 1, NULL))
808                         EM_DEBUG_EXCEPTION("em_storage_free_mail Failed");
809                 
810                 ret = true;
811         }
812         EM_DEBUG_FUNC_END();
813         return ret;
814 }
815         
816
817 /* storage space handling - 210709 */
818 int em_core_get_storage_status(void)
819 {
820         EM_DEBUG_FUNC_BEGIN();
821         int storage_status = 0, nError = 0;
822         
823         g_type_init();
824
825 #ifdef STORAGE_STATUS   
826         nError = vconf_get_int(PS_KEY_SYSTEM_STORAGE_MOVI_STATUS,
827                                                         &storage_status);       
828 #endif /*  STORAGE_STATUS */
829
830         if (nError == -1) {
831                 EM_DEBUG_EXCEPTION("vconf_get_int Failed");
832                 return false;
833         }
834         EM_DEBUG_FUNC_END();
835         return storage_status; 
836 }
837
838 int em_core_is_storage_full(int *err_code)
839 {
840         EM_DEBUG_FUNC_BEGIN();
841         
842         int ret = false;
843         int err = EMF_ERROR_NONE;
844         struct statfs buf = {0}; 
845         
846         if (statfs(DATA_PATH, &buf) == -1) {
847                 EM_DEBUG_EXCEPTION("statfs(\"%s\") failed - %d", DATA_PATH, errno);
848                 err = EMF_ERROR_SYSTEM_FAILURE;         /* lEMF_ERROR_UNKNOWN; */
849                 goto FINISH_OFF;
850         }
851         else  {
852                 long i_free = (buf.f_bfree * buf.f_bsize) / (1024 * 1024);
853                 EM_DEBUG_LOG("f_bfree[%d] f_bsize[%d]", buf.f_bfree, buf.f_bsize);
854                 EM_DEBUG_LOG("Free space of storage is[%ld] MB.", i_free);
855                 if (i_free < EM_STORAGE_LIMITATION_FREE_SPACE)
856                         err = EMF_ERROR_MAIL_MEMORY_FULL;
857         }
858         
859         if (err == EMF_ERROR_MAIL_MEMORY_FULL)
860                 ret = true;
861         
862 FINISH_OFF:
863         if (err_code != NULL)
864                 *err_code = err;
865         EM_DEBUG_FUNC_END("ret[%d]", ret);
866         return ret;
867 }
868
869 int em_core_get_mail_size(emf_mail_t *mail_src, int *error_code)
870 {
871         EM_DEBUG_FUNC_BEGIN("mail_src[%p], err_code[%p]", mail_src, error_code);
872         EM_PROFILE_BEGIN(profile_em_core_get_mail_size);
873
874         emf_attachment_info_t *atch = NULL;
875         struct stat st_buf;
876         int mail_size = 0;      /*  size of the plain text body and attachments */
877         int err = EMF_ERROR_NONE;
878         
879         if (!mail_src || !mail_src->body) {
880                 if (mail_src)  {
881                         if (mail_src->body)
882                                 EM_DEBUG_LOG("mail_src[%p], mail_src->body[%p], mail_src->body->plain[%p]", mail_src, mail_src->body, mail_src->body->plain);
883                         else
884                                 EM_DEBUG_LOG(" mail_src[%p], mail_src->body[%p]", mail_src, mail_src->body);
885                 }
886                 else
887                         EM_DEBUG_LOG("mail_src[%p]", mail_src);
888                 
889                 err = EMF_ERROR_INVALID_PARAM;
890                 goto FINISH_OFF;
891         }
892         
893         mail_size = 0;
894         if (mail_src->body->plain != NULL) {
895                 if (stat(mail_src->body->plain, &st_buf) < 0)  {
896                         EM_DEBUG_EXCEPTION("mail_src->body->plain stat(\"%s\") failed...", mail_src->body->plain);
897                         err = EMF_ERROR_INVALID_MAIL;
898                         goto FINISH_OFF;
899                 }
900                 
901                 mail_size += st_buf.st_size;
902
903         }
904
905         if (mail_src->body->html != NULL) {
906                 if (stat(mail_src->body->html, &st_buf) < 0) {
907                         EM_DEBUG_EXCEPTION("mail_src->body->html stat(\"%s\") failed...", mail_src->body->html);
908                         err = EMF_ERROR_INVALID_MAIL;
909                         goto FINISH_OFF;
910                 }
911                 
912                 mail_size += st_buf.st_size;
913         }
914
915         atch = mail_src->body->attachment;
916         
917         while (atch)  {
918                 if (stat(atch->savename, &st_buf) < 0)  {
919                         EM_DEBUG_EXCEPTION("stat(\"%s\") failed...", atch->savename);
920                         err = EMF_ERROR_INVALID_MAIL;           /* EMF_ERROR_INVALID_PATH; */
921                         goto FINISH_OFF;
922                 }
923                 
924                 mail_size += st_buf.st_size;
925                 atch = atch->next;
926         }
927
928         
929 FINISH_OFF:
930         if (error_code)
931                 *error_code = err;
932         EM_PROFILE_END(profile_em_core_get_mail_size);
933         EM_DEBUG_FUNC_END();
934         return (err == EMF_ERROR_NONE ? mail_size : 0);
935 }
936
937
938 int em_core_calc_mail_size(emf_mail_data_t *input_mail_data, emf_attachment_data_t *input_attachment_data_list, int input_attachment_count, int *output_size)
939 {
940         EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count[%d], output_size[%p]", input_mail_data, input_attachment_data_list, input_attachment_count, output_size);
941
942         struct stat            st_buf;
943         int                    mail_size = 0; /*  size of the plain text body and attachments */
944         int                    err       = EMF_ERROR_NONE;
945         int                    i         = 0;
946         
947         if (!input_mail_data || (input_attachment_count && !input_attachment_data_list) || (!input_attachment_count &&input_attachment_data_list) || !output_size)  {   
948                 EM_DEBUG_EXCEPTION("EMF_ERROR_INVALID_PARAM");
949                 err = EMF_ERROR_INVALID_PARAM;
950                 goto FINISH_OFF;
951         }
952         
953         if (input_mail_data->file_path_plain != NULL) {
954                 if (stat(input_mail_data->file_path_plain, &st_buf) < 0)  {
955                         EM_DEBUG_EXCEPTION("input_mail_data->file_path_plain : stat(\"%s\") failed...", input_mail_data->file_path_plain);
956                         err = EMF_ERROR_INVALID_MAIL;
957                         goto FINISH_OFF;
958                 }
959                 
960                 mail_size += st_buf.st_size;
961
962         }
963
964         if (input_mail_data->file_path_html != NULL) {
965                 if (stat(input_mail_data->file_path_html, &st_buf) < 0) {
966                         EM_DEBUG_EXCEPTION("input_mail_data->file_path_html : stat(\"%s\") failed...", input_mail_data->file_path_html);
967                         err = EMF_ERROR_INVALID_MAIL;
968                         goto FINISH_OFF;
969                 }
970                 
971                 mail_size += st_buf.st_size;
972         }
973         
974         for(i = 0; i < input_attachment_count; i++)  {
975                 if (stat(input_attachment_data_list[i].attachment_path, &st_buf) < 0)  {
976                         EM_DEBUG_EXCEPTION("stat(\"%s\") failed...", input_attachment_data_list[i].attachment_path);
977                         err = EMF_ERROR_INVALID_MAIL;
978                         goto FINISH_OFF;
979                 }
980                 mail_size += st_buf.st_size;
981         }
982
983         *output_size = mail_size;
984         
985 FINISH_OFF:
986         
987         EM_DEBUG_FUNC_END("mail_size [%d]", mail_size);
988         return err;
989 }
990
991
992 int em_storage_get_emf_error_from_em_storage_error(int error)
993 {
994         switch (error) {
995                 case EM_STORAGE_ERROR_NONE:
996                         return EMF_ERROR_NONE;
997
998                 case EM_STORAGE_ERROR_INVALID_PARAM:
999                         return EMF_ERROR_INVALID_PARAM;
1000
1001                 case EM_STORAGE_ERROR_ACCOUNT_NOT_FOUND:
1002                         return EMF_ERROR_ACCOUNT_NOT_FOUND;
1003
1004                 case EM_STORAGE_ERROR_MAIL_NOT_FOUND:
1005                         return EMF_ERROR_MAIL_NOT_FOUND;
1006
1007                 case EM_STORAGE_ERROR_MAILBOX_NOT_FOUND:
1008                         return EMF_ERROR_MAILBOX_NOT_FOUND;
1009
1010                 case EM_STORAGE_ERROR_ATTACHMENT_NOT_FOUND:
1011                         return EMF_ERROR_ATTACHMENT_NOT_FOUND;
1012
1013                 case EM_STORAGE_ERROR_CONTACT_NOT_FOUND:
1014                         return EMF_ERROR_CONTACT_NOT_FOUND;
1015
1016                 case EM_STORAGE_ERROR_FILE_NOT_FOUND:
1017                         return EMF_ERROR_FILE_NOT_FOUND;
1018
1019                 case EM_STORAGE_ERROR_DATA_NOT_FOUND:
1020                         return EMF_ERROR_DATA_NOT_FOUND;
1021
1022                 case EM_STORAGE_ERROR_NO_MORE_DATA:
1023                         return EMF_ERROR_NO_MORE_DATA;
1024
1025                 case EM_STORAGE_ERROR_DATA_TOO_LONG:
1026                         return EMF_ERROR_DATA_TOO_LONG;
1027
1028                 case EM_STORAGE_ERROR_DATA_TOO_SMALL:
1029                         return EMF_ERROR_DATA_TOO_SMALL;
1030
1031                 case EM_STORAGE_ERROR_OUT_OF_MEMORY:
1032                         return EMF_ERROR_OUT_OF_MEMORY;
1033
1034                 case EM_STORAGE_ERROR_CONNECTION_FAILURE:
1035                         return EMF_ERROR_CONNECTION_FAILURE;
1036
1037                 case EM_STORAGE_ERROR_SYSTEM_FAILURE:
1038                         return EMF_ERROR_SYSTEM_FAILURE;
1039
1040                 case EM_STORAGE_ERROR_RULE_NOT_FOUND:
1041                         return EMF_ERROR_FILTER_NOT_FOUND;
1042
1043                 case EM_STORAGE_ERROR_DB_IS_FULL:
1044                         return EMF_ERROR_MAIL_MEMORY_FULL;
1045
1046                 case EM_STORAGE_ERROR_DB_FAILURE:
1047                         return EMF_ERROR_DB_FAILURE;
1048
1049                 case EM_STORAGE_ERROR_MAIL_MAX_COUNT:
1050                         return EMF_ERROR_MAIL_MAX_COUNT;
1051
1052                 case EM_STORAGE_ERROR_MMC_NOT_FOUND:
1053                         return EMF_ERROR_NO_MMC_INSERTED;
1054
1055                 case EM_STORAGE_ERROR_ALREADY_EXISTS:
1056                         return EMF_ERROR_ALREADY_EXISTS;
1057
1058                 case EM_STORAGE_ERROR_UNKNOWN:
1059                 default:
1060                         return EMF_ERROR_UNKNOWN;
1061         }
1062                 
1063         return EMF_ERROR_UNKNOWN;
1064 }
1065
1066
1067 /* parse the Full mailbox Path and Get the Alias Name of the Mailbox */
1068 char *em_core_get_alias_of_mailbox(const char *mailbox_path)
1069 {
1070         EM_DEBUG_FUNC_BEGIN();
1071         EM_IF_NULL_RETURN_VALUE(mailbox_path, NULL);
1072
1073         guint index = 0;
1074         gchar **token_list = NULL;
1075         gchar *mailbox = NULL, *name = NULL;
1076         char *converted_name;
1077         
1078         
1079         mailbox = g_strdup(mailbox_path);
1080         token_list = g_strsplit_set(mailbox, "/", -1);
1081         
1082         if (mailbox)
1083                 g_free(mailbox);
1084
1085         while (token_list[index] != NULL)
1086                 index++;
1087
1088         name = g_strdup(token_list[index - 1]);
1089         g_strfreev(token_list);
1090
1091         converted_name = em_core_convert_mutf7_to_utf8(name);
1092         
1093         if (name)
1094                 g_free(name);
1095
1096         EM_DEBUG_FUNC_END();
1097         return converted_name;
1098 }
1099
1100 EXPORT_API int em_core_open_contact_db_library(void)
1101 {
1102         EM_DEBUG_FUNC_BEGIN();
1103         int  err;
1104         int ret = false;
1105
1106         if ((err = contacts_svc_connect()) == CTS_SUCCESS)
1107                 EM_DEBUG_LOG("Open Contact Service Success");   
1108         else    {               
1109                 EM_DEBUG_EXCEPTION("contact_db_service_connect failed - %d", err);              
1110                 return false;
1111         }
1112         ret = true;
1113
1114         EM_DEBUG_FUNC_END();
1115         return ret;
1116         
1117 }
1118
1119 EXPORT_API void em_core_close_contact_db_library()
1120 {
1121         EM_DEBUG_FUNC_BEGIN();
1122         int  err;
1123
1124         if ((err = contacts_svc_disconnect()) == CTS_SUCCESS)
1125                 EM_DEBUG_LOG("Close Contact Service Success");
1126         else
1127                 EM_DEBUG_EXCEPTION("Close Contact Service Fail[%d]", err);
1128         EM_DEBUG_FUNC_END();    
1129         return;
1130 }
1131
1132 #define EMAIL_ACCOUNT_RGEX                     "([a-z0-9!#$%&'*+/=?^_`{|}~-]+.)*[a-z0-9!#$%&'*+/=?^_`{|}~-]+"
1133 #define EMAIL_DOMAIN_RGEX                      "([a-z0-9!#$%&'*+/=?^_`{|}~-]+.)+[a-z0-9!#$%&'*+/=?^_`{|}~-]+"
1134
1135 #define EMAIL_ADDR_RGEX                        "[[:space:]]*<"EMAIL_ACCOUNT_RGEX"@"EMAIL_DOMAIN_RGEX">[[:space:]]*"
1136 #define EMAIL_ALIAS_RGEX                       "([[:space:]]*\"[^\"]*\")?"EMAIL_ADDR_RGEX
1137 #define EMAIL_ALIAS_LIST_RGEX                  "^("EMAIL_ALIAS_RGEX"[;,])*"EMAIL_ALIAS_RGEX"[;,]?[[:space:]]*$"
1138
1139 #define EMAIL_ADDR_WITHOUT_BRACKET_RGEX        "[[:space:]]*"EMAIL_ACCOUNT_RGEX"@"EMAIL_DOMAIN_RGEX"[[:space:]]*"
1140 #define EMAIL_ALIAS_WITHOUT_BRACKET_RGEX       "([[:space:]]*\"[^\"]*\")?"EMAIL_ADDR_WITHOUT_BRACKET_RGEX
1141 #define EMAIL_ALIAS_LIST_WITHOUT_BRACKET_RGEX  "("EMAIL_ALIAS_WITHOUT_BRACKET_RGEX"[;,])*"EMAIL_ADDR_WITHOUT_BRACKET_RGEX"[;,]?[[:space:]]*$"
1142
1143 EXPORT_API int em_core_verify_email_address(char *address, int without_bracket, int *err_code)
1144 {
1145         EM_DEBUG_FUNC_BEGIN("address[%s] without_bracket[%d]", address, without_bracket);
1146
1147         /*  this following code verfies the email alias string using reg. exp. */
1148         regex_t alias_list_regex = {0};
1149         int ret = false, error = EMF_ERROR_NONE;
1150         char *reg_rule = NULL;
1151
1152         if(!address || strlen(address) == 0) {
1153                 EM_DEBUG_EXCEPTION("EMF_ERROR_INVALID_PARAM");
1154                 if (err_code)
1155                         *err_code = EMF_ERROR_INVALID_PARAM;
1156                 return false;
1157         }
1158
1159         if(without_bracket)
1160                 reg_rule = EMAIL_ALIAS_LIST_WITHOUT_BRACKET_RGEX;
1161         else
1162                 reg_rule = EMAIL_ALIAS_LIST_RGEX;
1163
1164         if (regcomp(&alias_list_regex, reg_rule, REG_ICASE | REG_EXTENDED)) {
1165                 EM_DEBUG_EXCEPTION("email alias regex unrecognized");
1166                 if (err_code)
1167                         *err_code = EMF_ERROR_UNKNOWN;
1168                 return false;
1169         }
1170
1171         int alias_len = strlen(address) + 1;
1172         regmatch_t pmatch[alias_len];
1173         
1174         bzero(pmatch, alias_len);
1175
1176         if (regexec(&alias_list_regex, address, alias_len, pmatch, 0) == REG_NOMATCH)
1177                 EM_DEBUG_LOG("failed :[%s]", address);
1178         else {
1179                 EM_DEBUG_LOG("success :[%s]", address);
1180                 ret = true;
1181         }
1182
1183         regfree(&alias_list_regex);
1184
1185         if (err_code)
1186                 *err_code = error;
1187
1188         EM_DEBUG_FUNC_END("ret [%d]", ret);
1189         return ret;
1190 }
1191
1192 EXPORT_API int em_core_verify_email_address_of_mail_header(emf_mail_head_t *mail_header, int without_bracket, int *err_code)
1193 {
1194         EM_DEBUG_FUNC_BEGIN("mail_header[%p] without_bracket[%d]", mail_header, without_bracket);
1195         char *address_array[4] = { mail_header->to, mail_header->cc, mail_header->bcc, mail_header->from};
1196         int  ret = false, err = EMF_ERROR_NONE, i;
1197
1198         /* check for email_address validation */
1199         for (i = 0; i < 4; i++) {
1200                 if (address_array[i] && address_array[i][0] != 0) {
1201                         if (!em_core_verify_email_address(address_array[i] , without_bracket, &err)) {
1202                                 err = EMF_ERROR_INVALID_ADDRESS;
1203                                 EM_DEBUG_EXCEPTION("Invalid Email Address [%d][%s]", i, address_array[i]);
1204                                 goto FINISH_OFF;
1205                         }
1206                 }
1207         }
1208         ret = true;
1209 FINISH_OFF:     
1210         EM_DEBUG_FUNC_END("ret [%d]", ret);
1211         return ret;
1212 }
1213
1214 EXPORT_API int em_core_verify_email_address_of_mail_data(emf_mail_data_t *mail_data, int without_bracket, int *err_code)
1215 {
1216         EM_DEBUG_FUNC_BEGIN("mail_data[%p] without_bracket[%d]", mail_data, without_bracket);
1217         char *address_array[4] = { mail_data->full_address_from, mail_data->full_address_to, mail_data->full_address_cc, mail_data->full_address_bcc};
1218         int  ret = false, err = EMF_ERROR_NONE, i;
1219
1220         /* check for email_address validation */
1221         for (i = 0; i < 4; i++) {
1222                 if (address_array[i] && address_array[i][0] != 0) {
1223                         if (!em_core_verify_email_address(address_array[i] , without_bracket, &err)) {
1224                                 err = EMF_ERROR_INVALID_ADDRESS;
1225                                 EM_DEBUG_EXCEPTION("Invalid Email Address [%d][%s]", i, address_array[i]);
1226                                 goto FINISH_OFF;
1227                         }
1228                 }
1229         }
1230         ret = true;
1231 FINISH_OFF:     
1232         EM_DEBUG_FUNC_END("ret [%d]", ret);
1233         return ret;
1234 }
1235
1236 EXPORT_API int em_core_get_server_time(void *mail_stream, int account_id, char *uid, int msgno, time_t *log_time, int *err_code)
1237 {
1238         EM_DEBUG_FUNC_BEGIN();
1239
1240         int ret_code = false;
1241         int err = EMF_ERROR_NONE;
1242         emf_account_t *account =  NULL;
1243         emf_mailbox_t  mailbox = { 0 };
1244         MESSAGECACHE *elt = NULL;
1245         char datetime[DATETIME_LENGTH] = { 0, };
1246         emf_datetime_t date = { 0 };
1247         struct tm tm1 = { 0 };
1248         time_t t = time(NULL);
1249         
1250
1251         if (!mail_stream || (!uid && msgno < 1)) {
1252                 EM_DEBUG_EXCEPTION("Param is NULL");
1253                 err = EMF_ERROR_INVALID_PARAM;
1254                 goto FINISH_OFF;
1255         }
1256
1257         mailbox.account_id = account_id;
1258         mailbox.mail_stream = mail_stream;
1259
1260         if (!(account = em_core_get_account_reference(account_id))) {
1261                 EM_DEBUG_EXCEPTION("em_core_get_account_reference failed - %d", account_id);
1262                 err = EMF_ERROR_INVALID_ACCOUNT;        
1263                 goto FINISH_OFF;
1264         }
1265         if (msgno < 1) {        /*  get msgno  from server */
1266                 if (!em_core_mail_get_msgno_by_uid(account, &mailbox, uid, &msgno, &err)) {
1267                         EM_DEBUG_EXCEPTION("em_core_mail_get_msgno_by_uid failed message_no : %d ", err);
1268                         goto FINISH_OFF;
1269                 }
1270         }
1271         if (!(elt = mail_elt(mailbox.mail_stream, msgno))) {
1272                 EM_DEBUG_EXCEPTION("mail_elt failed...");
1273                 err = EMF_ERROR_UNKNOWN;
1274                 goto FINISH_OFF;
1275         }
1276         SNPRINTF(datetime, sizeof(datetime), "%04d%02d%02d%02d%02d%02d", 
1277                 BASEYEAR + elt->year, elt->month, elt->day, elt->hours, elt->minutes, elt->seconds);
1278
1279         EM_DEBUG_LOG("datetime[%s]", datetime);
1280         
1281         if (!em_convert_string_to_datetime(datetime, &date, &err)) 
1282                 EM_DEBUG_EXCEPTION("em_convert_string_to_datetime failed - %d", err);
1283
1284         tm1.tm_year = date.year - 1900;
1285         tm1.tm_mon = date.month - 1;
1286         tm1.tm_mday = date.day;
1287         tm1.tm_hour = date.hour;
1288         tm1.tm_min = date.minute;
1289         tm1.tm_sec = date.second;
1290         t = mktime(&tm1);
1291
1292         *log_time = t;
1293         ret_code = true;
1294         
1295 FINISH_OFF:
1296
1297         if (err_code)
1298                 *err_code = err;
1299
1300         EM_DEBUG_FUNC_END();
1301         return ret_code;
1302 }
1303
1304 static int em_core_get_first_address(const char *full_address, char **alias, char **address)
1305 {
1306         EM_DEBUG_FUNC_BEGIN();
1307
1308         if (full_address == NULL || alias == NULL || address == NULL){
1309                 EM_DEBUG_EXCEPTION("Invalid Param  :  full_address[%p], alias[%p], address[%p]", full_address, alias, address);
1310                 return false;
1311         }
1312
1313         char *s = NULL;
1314         char *alias_start = NULL;
1315         char *alias_end = NULL;
1316         char *alias_cursor = NULL;
1317         char *address_start = NULL;
1318         char *address_end = NULL;
1319         char *first_address = NULL;
1320         
1321         if (full_address){
1322                 s = (char *)strchr((char *)full_address, ';');
1323                 if (s == NULL)
1324                         first_address = strdup(full_address);   /*  only one  address */
1325                 else
1326                         first_address = strndup(full_address, s - full_address);        /*  over two addresses */
1327
1328                 /*  get alias */
1329                 *alias = NULL;
1330                 if ((alias_start = (char *)strchr((char *)first_address, '\"'))){       
1331                         alias_start++;
1332                         alias_cursor = alias_start;
1333                         while ((alias_cursor = (char *)strchr((char *)(alias_cursor), '\"'))){
1334                                 alias_end = alias_cursor;
1335                                 alias_cursor++;
1336                                 if (*alias_cursor == 0)
1337                                         break;
1338                         }
1339                         if (alias_end)  {       /*  there is "alias" */
1340                                 *alias = strndup(alias_start, alias_end - alias_start); 
1341                                 EM_DEBUG_LOG("alias [%s]", *alias);
1342                         }
1343                 }
1344
1345                 /*  get address */
1346                 *address = NULL;
1347                 if (alias_end == NULL)
1348                         s = first_address;
1349                 else
1350                         s = alias_end+1;
1351                 if ((address_start = (char *)strchr((char  *)s, '<'))){ 
1352                         address_start++;
1353                         if ((address_end = (char *)strchr((char  *)address_start, '>')))
1354                                 *address = strndup(address_start, address_end - address_start); /*  (alias) <(addr)>  ... */
1355                         else
1356                                 *address = strdup(s);
1357                 }
1358                 else
1359                *address = strdup(s);    /*  (addr) ; ...                 :  no alias */
1360         }
1361
1362         EM_SAFE_FREE(first_address);
1363         EM_DEBUG_FUNC_END();    
1364         return true;
1365 }               
1366
1367 EXPORT_API void em_core_fill_address_information_of_mail_tbl(emf_mail_tbl_t *mail_data)
1368 {
1369         EM_DEBUG_FUNC_BEGIN("mail_data [%p]", mail_data);
1370
1371         char *first_alias   = NULL;
1372         char *first_address = NULL;
1373         char *recipient     = NULL;
1374
1375         /*  sender alias & address */
1376         if (em_core_get_first_address(mail_data->full_address_from, &first_alias, &first_address) == true) {
1377                 if (first_alias == NULL) {
1378                         mail_data->alias_sender = EM_SAFE_STRDUP(first_address);
1379                 }
1380                 else {
1381                         mail_data->alias_sender = first_alias;
1382                         first_alias = NULL;
1383                 }
1384                 mail_data->email_address_sender = first_address;
1385                 first_address = NULL;
1386         }
1387
1388         /*  recipient alias & address */
1389         if (mail_data->full_address_to != NULL)
1390                 recipient = mail_data->full_address_to;
1391         else if (mail_data->full_address_cc != NULL)
1392                 recipient = mail_data->full_address_cc;
1393         else if (mail_data->full_address_bcc != NULL)
1394                 recipient = mail_data->full_address_bcc;
1395         
1396         if (em_core_get_first_address(recipient, &first_alias, &first_address) == true) {
1397                 if (first_alias == NULL)
1398                         mail_data->alias_recipient = EM_SAFE_STRDUP(first_address);
1399                 else
1400                         mail_data->alias_recipient = first_alias;
1401
1402                 mail_data->email_address_recipient = first_address;
1403         }
1404         EM_DEBUG_FUNC_END();    
1405 }
1406
1407
1408 EXPORT_API int em_core_get_preview_text_from_file(const char *input_plain_path, const char *input_html_path, int input_preview_buffer_length, char **output_preview_buffer)
1409 {
1410         EM_DEBUG_FUNC_BEGIN("input_plain_path[%p], input_html_path[%p], input_preview_buffer_length [%d], output_preview_buffer[%p]", input_plain_path, input_html_path, input_preview_buffer_length, output_preview_buffer);
1411         
1412         int          err = EMF_ERROR_NONE;
1413         unsigned int byte_read = 0;
1414         unsigned int byte_written = 0;
1415         int          result_strlen = 0;
1416         int          local_preview_buffer_length = 0;
1417         char        *local_preview_text = NULL;
1418         char        *encoding_type = NULL;
1419         char        *utf8_encoded_string = NULL;
1420         FILE        *fp = NULL;
1421         GError      *glib_error = NULL;
1422         struct stat  st_buf;
1423
1424         if (!output_preview_buffer) {
1425                 EM_DEBUG_EXCEPTION("EMF_ERROR_INVALID_PARAM");
1426                 err = EMF_ERROR_INVALID_PARAM;
1427                 goto FINISH_OFF;
1428         }
1429
1430         local_preview_buffer_length = input_preview_buffer_length * 2;
1431
1432         if (input_html_path != NULL) {  
1433                         /*      get preview text from html file */
1434                         if( (err = em_core_get_encoding_type_from_file_path(input_html_path, &encoding_type)) != EMF_ERROR_NONE) {
1435                                 EM_DEBUG_EXCEPTION("em_core_get_encoding_type_from_file_path failed [%s]", err);
1436                                 goto FINISH_OFF;
1437                         }
1438                         
1439                         if (stat(input_html_path, &st_buf) < 0)  {
1440                                 EM_DEBUG_EXCEPTION("stat(\"%s\") failed...", input_html_path);
1441                                 err = EMF_ERROR_INVALID_MAIL;
1442                                 goto FINISH_OFF;
1443                         }
1444                         
1445                         if (!(fp = fopen(input_html_path, "r")))        {
1446                                 EM_DEBUG_EXCEPTION("fopen failed [%s]", input_html_path);
1447                                 err = EMF_ERROR_SYSTEM_FAILURE;
1448                                 goto FINISH_OFF;
1449                         }
1450         
1451                         if (!(local_preview_text = (char*)em_core_malloc(sizeof(char) * (st_buf.st_size + 1)))) {
1452                                 EM_DEBUG_EXCEPTION("em_core_malloc failed");
1453                                 err = EMF_ERROR_OUT_OF_MEMORY;
1454                                 goto FINISH_OFF;
1455                         }
1456                         
1457                         byte_read = fread(local_preview_text, sizeof(char), st_buf.st_size, fp);
1458                         
1459                         if (ferror(fp)) {
1460                                 EM_DEBUG_EXCEPTION("fread failed [%s]", input_plain_path);
1461                                 err = EMF_ERROR_SYSTEM_FAILURE;
1462                                 goto FINISH_OFF;
1463                         }
1464         
1465                         if ( (err = em_core_strip_HTML(local_preview_text)) != EMF_ERROR_NONE) {
1466                                 EM_DEBUG_EXCEPTION("em_core_strip_HTML failed");
1467                                 goto FINISH_OFF;
1468                         }
1469         
1470                         result_strlen = EM_SAFE_STRLEN(local_preview_text);
1471                 }
1472
1473         if (local_preview_text == NULL && input_plain_path != NULL) {   
1474                 /*  get preview text from plain text file */
1475                 if( (err = em_core_get_encoding_type_from_file_path(input_plain_path, &encoding_type)) != EMF_ERROR_NONE) {
1476                         EM_DEBUG_EXCEPTION("em_core_get_encoding_type_from_file_path failed [%s]", err);
1477                         goto FINISH_OFF;
1478                 }
1479                 
1480                 if (!(fp = fopen(input_plain_path, "r")))  {
1481                         EM_DEBUG_EXCEPTION("fopen failed [%s]", input_plain_path);
1482                         err = EMF_ERROR_SYSTEM_FAILURE;
1483                         goto FINISH_OFF;
1484                 }
1485
1486                 if (!(local_preview_text = (char*)em_core_malloc(sizeof(char) * local_preview_buffer_length))) {
1487                         EM_DEBUG_EXCEPTION("em_core_malloc failed");
1488                         goto FINISH_OFF;
1489                 }
1490                 
1491                 byte_read = fread(local_preview_text, sizeof(char), local_preview_buffer_length - 1, fp);
1492                 
1493                 if (ferror(fp)) {
1494                         EM_DEBUG_EXCEPTION("fread failed [%s]", input_plain_path);
1495                         err = EMF_ERROR_SYSTEM_FAILURE;
1496                         goto FINISH_OFF;
1497                 }
1498                 result_strlen = byte_read;
1499         }       
1500         
1501
1502         if(local_preview_text) {
1503                 if(encoding_type && strcasecmp(encoding_type, "UTF-8") != 0) {
1504                         EM_DEBUG_LOG("encoding_type [%s]", encoding_type);
1505                         utf8_encoded_string = (char*)g_convert (local_preview_text, -1, "UTF-8", encoding_type, &byte_read, &byte_written, &glib_error);
1506
1507                         if(utf8_encoded_string) {
1508                                 EM_SAFE_FREE(local_preview_text);
1509                                 local_preview_text = utf8_encoded_string;
1510                         }
1511                         else 
1512                                 EM_DEBUG_EXCEPTION("g_convert failed");
1513                 }
1514                 
1515                 if (!(*output_preview_buffer = (char*)em_core_malloc(sizeof(char) * (result_strlen + 1)))) {
1516                         EM_DEBUG_EXCEPTION("em_core_malloc failed");
1517                         err = EMF_ERROR_OUT_OF_MEMORY;
1518                         goto FINISH_OFF;
1519                 }
1520
1521                 EM_SAFE_STRNCPY(*output_preview_buffer, local_preview_text, result_strlen);
1522                 /* EM_DEBUG_LOG("local_preview_text[%s], byte_read[%d], result_strlen[%d]", local_preview_text, byte_read, result_strlen); */
1523         }
1524
1525 FINISH_OFF:
1526
1527         EM_SAFE_FREE(local_preview_text);
1528         EM_SAFE_FREE(encoding_type);
1529         
1530         if (fp != NULL)
1531                 fclose(fp);
1532
1533         EM_DEBUG_FUNC_END("err [%d]", err);
1534         return err;
1535 }
1536
1537 EXPORT_API int em_core_add_transaction_info(int mail_id, int handle , int *err_code)
1538 {
1539         EM_DEBUG_FUNC_BEGIN("mail_id[%d], handle[%d]", mail_id, handle);
1540
1541         int ret = false;
1542         int err = EMF_ERROR_NONE ;
1543         em_transaction_info_type_t  *pTransinfo = NULL ;
1544         em_transaction_info_type_t      *pTemp = NULL;
1545
1546         EM_DEBUG_LOG("g_transaction_info_list[%p]", g_transaction_info_list);
1547         pTransinfo = g_transaction_info_list ;
1548         
1549         if (!(pTemp = em_core_malloc(sizeof(em_transaction_info_type_t))))  {
1550                 EM_DEBUG_EXCEPTION("malloc failed...");
1551                 err = EMF_ERROR_OUT_OF_MEMORY;
1552                 goto FINISH_OFF;
1553         }
1554         pTemp->mail_id = mail_id ;
1555         pTemp->handle = handle;
1556                 
1557         if (!pTransinfo) {
1558                 pTransinfo = pTemp ;
1559                 g_transaction_info_list = pTransinfo ;
1560         }
1561         else {
1562                 while (pTransinfo->next)
1563                         pTransinfo = pTransinfo->next;
1564                 pTransinfo->next = pTemp;
1565         }
1566         ret = true ;
1567         
1568 FINISH_OFF:
1569
1570         if (err_code)
1571                 *err_code = err;
1572         EM_DEBUG_FUNC_END("g_transaction_info_list[%p]", g_transaction_info_list);
1573         return ret;     
1574 }
1575
1576 EXPORT_API int em_core_get_handle_by_mailId_from_transaction_info(int mail_id, int *pHandle)
1577 {
1578         EM_DEBUG_FUNC_BEGIN("mail_id[%d], handle[%p]", mail_id, pHandle);
1579
1580         int ret = false;
1581         em_transaction_info_type_t  *pTransinfo = NULL ;
1582         
1583         if (g_transaction_info_list == NULL) {
1584                 EM_DEBUG_EXCEPTION("g_transaction_info_list NULL");
1585                 return false;
1586         }
1587         pTransinfo = g_transaction_info_list;
1588
1589         do {
1590                 EM_DEBUG_LOG("pTransinfo->mail_id[%d]", pTransinfo->mail_id);
1591                 if (pTransinfo->mail_id == mail_id) {
1592                         *pHandle = pTransinfo->handle;
1593                         ret = true;
1594                         EM_DEBUG_LOG("*pHandle[%d]", *pHandle);
1595                         break;
1596                 }
1597                 else
1598                         pTransinfo = pTransinfo->next ;
1599         }while (pTransinfo);
1600         EM_DEBUG_FUNC_END();
1601         return ret;
1602 }
1603
1604 EXPORT_API int em_core_delete_transaction_info_by_mailId(int mail_id )
1605 {
1606         EM_DEBUG_FUNC_BEGIN("mail_id[%d]", mail_id);
1607
1608         em_transaction_info_type_t  *pTransinfo ;
1609         em_transaction_info_type_t *pTemp = NULL;
1610
1611         if (g_transaction_info_list == NULL) {
1612                 EM_DEBUG_EXCEPTION("g_transaction_info_list NULL");
1613                 return false;
1614         }
1615         pTransinfo = g_transaction_info_list;
1616
1617         EM_DEBUG_LOG("pTransinfo[%p]", pTransinfo);
1618
1619         do {
1620                 EM_DEBUG_LOG("pTransinfo->mail_id[%d]", pTransinfo->mail_id);
1621                 if (pTransinfo->mail_id == mail_id) {
1622                         pTemp = pTransinfo->next ;
1623                         if (!pTemp) {
1624                                 EM_SAFE_FREE(pTransinfo) ;
1625                                 g_transaction_info_list = NULL;
1626                         }
1627                         else {
1628                                 pTransinfo->mail_id = pTransinfo->next->mail_id;
1629                                 pTransinfo->handle = pTransinfo->next->handle ;
1630                                 pTransinfo->next = pTransinfo->next->next;
1631
1632                                 EM_SAFE_FREE(pTemp);
1633                         }
1634                         break;
1635                 }
1636                 else {
1637                         pTransinfo = pTransinfo->next ;
1638                 }       
1639
1640         }while (pTransinfo);
1641         EM_DEBUG_FUNC_END();
1642         return true;
1643 }
1644
1645
1646 #include <regex.h>
1647
1648 int reg_replace (char *input_source_text, char *input_old_pattern_string, char *input_new_string)
1649 {
1650         EM_DEBUG_FUNC_BEGIN("input_source_text [%p], input_old_pattern_string [%p], input_new_string [%p]", input_source_text, input_old_pattern_string, input_new_string);
1651         int         error_code = EMF_ERROR_NONE; 
1652         char       *pos = NULL;
1653         int         so, n, nmatch, source_text_length, n_count = 1;
1654         regmatch_t *pmatch = NULL; 
1655         regex_t     reg_pattern;
1656
1657         if(!input_source_text || !input_old_pattern_string || !input_new_string) {
1658                 EM_DEBUG_EXCEPTION("EMF_ERROR_INVALID_PARAM");
1659                 error_code = EMF_ERROR_INVALID_PARAM;
1660                 goto FINISH_OFF;                
1661         }
1662
1663         source_text_length = strlen(input_source_text);
1664
1665         regcomp(&reg_pattern, input_old_pattern_string, REG_ICASE);
1666
1667         nmatch = reg_pattern.re_nsub + 1;
1668
1669         EM_DEBUG_LOG("nmatch [%d]", nmatch);
1670
1671         if(nmatch < 1) {
1672                 EM_DEBUG_EXCEPTION("EMF_ERROR_INVALID_DATA");
1673                 error_code = EMF_ERROR_INVALID_DATA;
1674                 goto FINISH_OFF;                
1675         }
1676         
1677         pmatch = (regmatch_t*)em_core_malloc(sizeof(regmatch_t) * nmatch);
1678
1679         if(pmatch == NULL) {
1680                 EM_DEBUG_EXCEPTION("EMF_ERROR_OUT_OF_MEMORY");
1681                 error_code = EMF_ERROR_OUT_OF_MEMORY;
1682                 goto FINISH_OFF;                
1683         }
1684         
1685         for (pos = input_new_string; *pos ; pos++) {
1686                 if (*pos == '\\' && *(pos + 1) > '0' && *(pos + 1) <= '9') {
1687                 
1688                         so = pmatch[*(pos + 1) - 48].rm_so;
1689                         n  = pmatch[*(pos + 1) - 48].rm_eo - so;
1690
1691                         EM_DEBUG_LOG("so [%d], n [%d]", so, n);
1692                         
1693                         if (so < 0 || strlen (input_new_string) + n - 1 > source_text_length) 
1694                                 break;
1695
1696                         memmove (pos + n, pos + 2, strlen (pos) - 1);
1697                         memmove (pos, input_source_text + so, n);
1698                         pos = pos + n - 2;
1699                 }
1700         }
1701         
1702         for (pos = input_source_text; !regexec (&reg_pattern, pos, 1, pmatch, 0);) {
1703                 n = pmatch[0].rm_eo - pmatch[0].rm_so;
1704                 pos += pmatch[0].rm_so;
1705
1706                 memmove (pos + strlen (input_new_string), pos + n, strlen (pos) - n + 1);
1707                 memmove (pos, input_new_string, strlen (input_new_string));
1708                 pos += strlen (input_new_string);
1709                 n_count++;
1710         }
1711         
1712 FINISH_OFF:
1713
1714         EM_SAFE_FREE(pmatch);
1715         regfree (&reg_pattern);
1716         
1717         EM_DEBUG_FUNC_END("error_code [%d]", error_code);
1718         return error_code;
1719 }
1720
1721
1722 EXPORT_API int em_core_strip_HTML(char *source_string)
1723 {
1724         EM_DEBUG_FUNC_BEGIN("source_string [%p]", source_string);
1725
1726         int result = EMF_ERROR_NONE;
1727         
1728         reg_replace(source_string, CR_STRING, "");
1729         reg_replace(source_string, LF_STRING, "");
1730         reg_replace(source_string, TAB_STRING, "");
1731         reg_replace(source_string, "<head[^>]*>", "<head>"); /*  "<()*head([^>])*>", "<head>" */
1732         reg_replace(source_string, "<*/head>", "</head>");  /*  "(<()*(/)()*head()*>)", "</head>" */
1733         reg_replace(source_string, "<head>.*</head>", ""); /*  "(<head>).*(</head>)", "" */
1734
1735         reg_replace(source_string, "<*/p>", LF_STRING);
1736
1737         /*   "<[^>]*>", " */
1738         reg_replace(source_string, "<[^>]*>", "");
1739
1740
1741         /*   "&bull;", " *  */
1742         /* reg_replace(source_string, "&bull;", " * "); */
1743
1744         /*   "&lsaquo;", "< */
1745         /* reg_replace(source_string, "&lsaquo;", "<"); */
1746
1747         /*   "&rsaquo;", "> */
1748         /* reg_replace(source_string, "&rsaquo;", ">"); */
1749
1750         /*   "&trade;", "(tm) */
1751         /* reg_replace(source_string, "&trade;", "(tm)"); */
1752
1753         /*   "&frasl;", "/ */
1754         /* reg_replace(source_string, "&frasl;", "/"); */
1755
1756         /*  "&lt;", "< */
1757         reg_replace(source_string, "&lt;", "<");
1758
1759         /*  "&gt;", "> */
1760         reg_replace(source_string, "&gt;", ">");
1761
1762         /*  "&copy;", "(c) */
1763         /* reg_replace(source_string, "&copy;", "(c)"); */
1764
1765         /* "&quot;", "\' */
1766         reg_replace(source_string, "&quot;", "\'");
1767
1768         /*  "&nbsp;", " */
1769         reg_replace(source_string, "&nbsp;", " ");
1770
1771         reg_replace(source_string, "\n\n", "");
1772         reg_replace(source_string, "  ", "");
1773
1774         EM_DEBUG_FUNC_END();
1775
1776         return result;
1777 }
1778
1779 #define MAX_NOTI_STRING_LENGTH          8096
1780
1781 EXPORT_API int em_core_convert_structure_to_string(void *struct_var, char **encoded_string, emf_convert_struct_type_e type)
1782 {
1783         EM_DEBUG_FUNC_BEGIN("Struct type[%d]", type);
1784         
1785         char *buf = NULL;
1786         char delimiter[] = {0x01, 0x00};
1787         int error_code = EMF_ERROR_NONE;
1788
1789         buf = (char *) malloc(MAX_NOTI_STRING_LENGTH * sizeof(char));
1790         if (NULL == buf) {
1791                 error_code = EMF_ERROR_OUT_OF_MEMORY;
1792                 goto FINISH_OFF;                
1793         }
1794         switch (type) {
1795                 case EMF_CONVERT_STRUCT_TYPE_MAIL_LIST_ITEM: {
1796                         emf_mail_list_item_t *item = (emf_mail_list_item_t *)struct_var;
1797                         SNPRINTF(buf, MAX_NOTI_STRING_LENGTH, 
1798                                 "%d%c"  /*      int  mail_id                                                            ; */
1799                                 "%d%c"  /*      int  account_id                                                                 ; */
1800                                 "%s%c"  /*      char mailbox_name[STRING_LENGTH_FOR_DISPLAY]    ; */
1801                                 "%s%c"  /*      char from[STRING_LENGTH_FOR_DISPLAY]                    ; */
1802                                 "%s%c"  /*      char from_email_address[MAX_EMAIL_ADDRESS_LENGTH]; */
1803                                 "%s%c"  /*      char recipients[STRING_LENGTH_FOR_DISPLAY]      ; */
1804                                 "%s%c"  /*      char subject[STRING_LENGTH_FOR_DISPLAY]                 ; */
1805                                 "%d%c"  /*      int  is_text_downloaded                                                 ; */
1806                                 "%s%c"  /*      char datetime[MAX_DATETIME_STRING_LENGTH]               ; */
1807                                 "%d%c"  /*      int  flags_seen_field                                                                   ; */
1808                                 "%d%c"  /*      int  priority                                                                   ; */
1809                                 "%d%c"  /*      int  save_status                                                                                ; */
1810                                 "%d%c"  /*      int  is_locked                                                                  ; */
1811                                 "%d%c"  /*      int  is_report_mail                                                             ; */
1812                                 "%d%c"  /*      int  recipients_count                                                   ; */
1813                                 "%d%c"  /*      int  has_attachment                                                     ; */
1814                                 "%d%c"  /*      int  has_drm_attachment                                                 ; */
1815                                 "%s%c"  /*      char previewBodyText[MAX_PREVIEW_TEXT_LENGTH]   ; */
1816                                 "%d%c"  /*      int  thread_id                                                                  ; */
1817                                 "%d%c", /*      int  thread_item_count                                                  ; */
1818
1819                                 item->mail_id,                  delimiter[0],
1820                                 item->account_id,                       delimiter[0],
1821                                 item->mailbox_name,             delimiter[0],
1822                                 item->from,                             delimiter[0],
1823                                 item->from_email_address,       delimiter[0],
1824                                 item->recipients,                       delimiter[0],
1825                                 item->subject,                  delimiter[0],
1826                                 item->is_text_downloaded,       delimiter[0],
1827                                 item->datetime,                         delimiter[0],
1828                                 item->flags_seen_field,                         delimiter[0],
1829                                 item->priority,                         delimiter[0],
1830                                 item->save_status,                              delimiter[0],
1831                                 item->is_locked,                        delimiter[0],
1832                                 item->is_report_mail,           delimiter[0],
1833                                 item->recipients_count,         delimiter[0],
1834                                 item->has_attachment,   delimiter[0],
1835                                 item->has_drm_attachment,       delimiter[0],
1836                                 item->previewBodyText,  delimiter[0],
1837                                 item->thread_id,                        delimiter[0],
1838                                 item->thread_item_count,        delimiter[0]
1839                         );
1840                 }               
1841                         break;
1842         }
1843
1844 FINISH_OFF:
1845         if (encoded_string)
1846                 *encoded_string = buf;
1847         EM_DEBUG_FUNC_END("Struct -> String:[%s]\n", buf);
1848         return error_code;
1849 }
1850
1851 EXPORT_API int em_core_convert_string_to_structure(const char *encoded_string, void **struct_var, emf_convert_struct_type_e type)
1852 {
1853         EM_DEBUG_FUNC_BEGIN();
1854         
1855         int ret = false;
1856         void *temp_struct = NULL;
1857         char *buff = NULL;
1858         char *current_pos = NULL;
1859         char *found_pos = NULL;
1860         char delimiter[] = {0x01, 0x00};
1861         int error_code = EMF_ERROR_NONE;
1862
1863         EM_DEBUG_LOG("Struct Type[%d], String:[%s]", type, encoded_string);
1864
1865         buff = (char *)EM_SAFE_STRDUP(encoded_string);
1866         if (NULL == buff) {
1867                 error_code = EMF_ERROR_OUT_OF_MEMORY;
1868                 goto FINISH_OFF;                
1869         }
1870         
1871         switch (type) {
1872                 case EMF_CONVERT_STRUCT_TYPE_MAIL_LIST_ITEM: {
1873                         emf_mail_list_item_t *item = (emf_mail_list_item_t *)malloc(sizeof(emf_mail_list_item_t));
1874                         if (NULL == item) {
1875                                 error_code = EMF_ERROR_OUT_OF_MEMORY;
1876                                 goto FINISH_OFF;                
1877                         }
1878                         temp_struct = (void *)item;
1879
1880                         current_pos = buff;
1881
1882                         /*  mail_id */
1883                         found_pos = strstr(current_pos, delimiter);
1884                         if (NULL == found_pos) {
1885                                 error_code = EMF_ERROR_INVALID_DATA;
1886                                 goto FINISH_OFF;                
1887                         }
1888                         *found_pos = NULL_CHAR;
1889                         item->mail_id = atoi(current_pos);
1890                         EM_DEBUG_LOG("mail_id[%d]", item->mail_id);
1891                         current_pos = found_pos + 1;
1892
1893                         /*  account_id */
1894                         found_pos = strstr(current_pos, delimiter);
1895                         if (NULL == found_pos) {
1896                                 error_code = EMF_ERROR_INVALID_DATA;
1897                                 goto FINISH_OFF;                
1898                         }
1899                         *found_pos = NULL_CHAR;
1900                         item->account_id = atoi(current_pos);
1901                         EM_DEBUG_LOG("account_id[%d]", item->account_id);
1902                         current_pos = found_pos + 1;
1903
1904                         /*  mailbox_name */
1905                         found_pos = strstr(current_pos, delimiter);
1906                         if (NULL == found_pos) {
1907                                 error_code = EMF_ERROR_INVALID_DATA;
1908                                 goto FINISH_OFF;                
1909                         }
1910                         *found_pos = NULL_CHAR;
1911                         strncpy(item->mailbox_name, current_pos, STRING_LENGTH_FOR_DISPLAY-1);
1912                         EM_DEBUG_LOG("mailbox_name[%s]", item->mailbox_name);
1913                         current_pos = found_pos + 1;
1914
1915                         /*  from */
1916                         found_pos = strstr(current_pos, delimiter);
1917                         if (NULL == found_pos) {
1918                                 error_code = EMF_ERROR_INVALID_DATA;
1919                                 goto FINISH_OFF;                
1920                         }
1921                         *found_pos = NULL_CHAR;
1922                         strncpy(item->from, current_pos, STRING_LENGTH_FOR_DISPLAY-1);
1923                         EM_DEBUG_LOG("from[%s]", item->from);
1924                         current_pos = found_pos + 1;
1925
1926                         /*  from_email_address */
1927                         found_pos = strstr(current_pos, delimiter);
1928                         if (NULL == found_pos) {
1929                                 error_code = EMF_ERROR_INVALID_DATA;
1930                                 goto FINISH_OFF;                
1931                         }
1932                         *found_pos = NULL_CHAR;
1933                         strncpy(item->from_email_address, current_pos, STRING_LENGTH_FOR_DISPLAY-1);
1934                         EM_DEBUG_LOG("from_email_address[%s]", item->from_email_address);
1935                         current_pos = found_pos + 1;
1936
1937                         /*  recipients */
1938                         found_pos = strstr(current_pos, delimiter);
1939                         if (NULL == found_pos) {
1940                                 error_code = EMF_ERROR_INVALID_DATA;
1941                                 goto FINISH_OFF;                
1942                         }
1943                         *found_pos = NULL_CHAR;
1944                         strncpy(item->recipients, current_pos, STRING_LENGTH_FOR_DISPLAY-1);
1945                         EM_DEBUG_LOG("recipients[%s]", item->recipients);
1946                         current_pos = found_pos + 1;                    
1947
1948                         /*  subject */
1949                         found_pos = strstr(current_pos, delimiter);
1950                         if (NULL == found_pos) {
1951                                 error_code = EMF_ERROR_INVALID_DATA;
1952                                 goto FINISH_OFF;                
1953                         }
1954                         *found_pos = NULL_CHAR;
1955                         strncpy(item->subject, current_pos, STRING_LENGTH_FOR_DISPLAY-1);
1956                         EM_DEBUG_LOG("subject[%s]", item->subject);
1957                         current_pos = found_pos + 1;                    
1958
1959                         /*  is_text_downloaded */
1960                         found_pos = strstr(current_pos, delimiter);
1961                         if (NULL == found_pos) {
1962                                 error_code = EMF_ERROR_INVALID_DATA;
1963                                 goto FINISH_OFF;                
1964                         }
1965                         *found_pos = NULL_CHAR;
1966                         item->is_text_downloaded = atoi(current_pos);
1967                         EM_DEBUG_LOG("is_text_downloaded[%d]", item->is_text_downloaded);
1968                         current_pos = found_pos + 1;
1969
1970                         /*  datatime */
1971                         found_pos = strstr(current_pos, delimiter);
1972                         if (NULL == found_pos) {
1973                                 error_code = EMF_ERROR_INVALID_DATA;
1974                                 goto FINISH_OFF;                
1975                         }
1976                         *found_pos = NULL_CHAR;
1977                         strncpy(item->datetime, current_pos, MAX_DATETIME_STRING_LENGTH-1);
1978                         EM_DEBUG_LOG("datetime[%s]", item->datetime);
1979                         current_pos = found_pos + 1;    
1980
1981                         /*  flags_seen_field */
1982                         found_pos = strstr(current_pos, delimiter);
1983                         if (NULL == found_pos) {
1984                                 error_code = EMF_ERROR_INVALID_DATA;
1985                                 goto FINISH_OFF;                
1986                         }
1987                         *found_pos = NULL_CHAR;
1988                         item->flags_seen_field = atoi(current_pos);
1989                         EM_DEBUG_LOG("flags_seen_field[%d]", item->flags_seen_field);
1990                         current_pos = found_pos + 1;
1991
1992                         /*  priority */
1993                         found_pos = strstr(current_pos, delimiter);
1994                         if (NULL == found_pos) {
1995                                 error_code = EMF_ERROR_INVALID_DATA;
1996                                 goto FINISH_OFF;                
1997                         }
1998                         *found_pos = NULL_CHAR;
1999                         item->priority = atoi(current_pos);
2000                         EM_DEBUG_LOG("priority[%d]", item->priority);
2001                         current_pos = found_pos + 1;                    
2002
2003                         /*  save_status */
2004                         found_pos = strstr(current_pos, delimiter);
2005                         if (NULL == found_pos) {
2006                                 error_code = EMF_ERROR_INVALID_DATA;
2007                                 goto FINISH_OFF;                
2008                         }
2009                         *found_pos = NULL_CHAR;
2010                         item->save_status = atoi(current_pos);
2011                         EM_DEBUG_LOG("save_status[%d]", item->save_status);
2012                         current_pos = found_pos + 1;    
2013
2014                         /*  is_locked */
2015                         found_pos = strstr(current_pos, delimiter);
2016                         if (NULL == found_pos) {
2017                                 error_code = EMF_ERROR_INVALID_DATA;
2018                                 goto FINISH_OFF;                
2019                         }
2020                         *found_pos = NULL_CHAR;
2021                         item->is_locked = atoi(current_pos);
2022                         EM_DEBUG_LOG("is_locked[%d]", item->is_locked);
2023                         current_pos = found_pos + 1;    
2024
2025                         /*  is_report_mail */
2026                         found_pos = strstr(current_pos, delimiter);
2027                         if (NULL == found_pos) {
2028                                 error_code = EMF_ERROR_INVALID_DATA;
2029                                 goto FINISH_OFF;                
2030                         }
2031                         *found_pos = NULL_CHAR;
2032                         item->is_report_mail = atoi(current_pos);
2033                         EM_DEBUG_LOG("is_report_mail[%d]", item->is_report_mail);
2034                         current_pos = found_pos + 1;    
2035
2036                         /*  recipients_count */
2037                         found_pos = strstr(current_pos, delimiter);
2038                         if (NULL == found_pos) {
2039                                 error_code = EMF_ERROR_INVALID_DATA;
2040                                 goto FINISH_OFF;                
2041                         }
2042                         *found_pos = NULL_CHAR;
2043                         item->recipients_count = atoi(current_pos);
2044                         EM_DEBUG_LOG("is_report_mail[%d]", item->recipients_count);
2045                         current_pos = found_pos + 1;                            
2046
2047                         /*  has_attachment */
2048                         found_pos = strstr(current_pos, delimiter);
2049                         if (NULL == found_pos) {
2050                                 error_code = EMF_ERROR_INVALID_DATA;
2051                                 goto FINISH_OFF;                
2052                         }
2053                         *found_pos = NULL_CHAR;
2054                         item->has_attachment = atoi(current_pos);
2055                         EM_DEBUG_LOG("has_attachment[%d]", item->has_attachment);
2056                         current_pos = found_pos + 1;                            
2057
2058                         /*  has_drm_attachment */
2059                         found_pos = strstr(current_pos, delimiter);
2060                         if (NULL == found_pos) {
2061                                 error_code = EMF_ERROR_INVALID_DATA;
2062                                 goto FINISH_OFF;                
2063                         }
2064                         *found_pos = NULL_CHAR;
2065                         item->has_drm_attachment = atoi(current_pos);
2066                         EM_DEBUG_LOG("has_drm_attachment[%d]", item->has_drm_attachment);
2067                         current_pos = found_pos + 1;                            
2068
2069                         /*  previewBodyText */
2070                         found_pos = strstr(current_pos, delimiter);
2071                         if (NULL == found_pos) {
2072                                 error_code = EMF_ERROR_INVALID_DATA;
2073                                 goto FINISH_OFF;                
2074                         }
2075                         *found_pos = NULL_CHAR;
2076                         strncpy(item->previewBodyText, current_pos, MAX_PREVIEW_TEXT_LENGTH-1);
2077                         EM_DEBUG_LOG("previewBodyText[%s]", item->previewBodyText);
2078                         current_pos = found_pos + 1;    
2079
2080                         /*  thread_id */
2081                         found_pos = strstr(current_pos, delimiter);
2082                         if (NULL == found_pos) {
2083                                 error_code = EMF_ERROR_INVALID_DATA;
2084                                 goto FINISH_OFF;                
2085                         }
2086                         *found_pos = NULL_CHAR;
2087                         item->thread_id = atoi(current_pos);
2088                         EM_DEBUG_LOG("thread_id[%d]", item->thread_id);
2089                         current_pos = found_pos + 1;    
2090
2091                         /*  thread_item_count - the last item */
2092                         item->thread_item_count = atoi(current_pos);
2093                         EM_DEBUG_LOG("thread_item_count[%d]", item->thread_item_count);
2094                         
2095                 }
2096                         break;
2097                         
2098                 default:
2099                         EM_DEBUG_EXCEPTION("Unknown structure type");
2100                         break;
2101         }
2102
2103         ret = true;
2104         
2105 FINISH_OFF:
2106         EM_SAFE_FREE(buff);
2107         if (ret == true) {
2108                 if (struct_var)
2109                         *struct_var = temp_struct;
2110         }
2111         else {
2112                 switch (type) {
2113                         case EMF_CONVERT_STRUCT_TYPE_MAIL_LIST_ITEM:
2114                                 EM_SAFE_FREE(temp_struct);
2115                                 break;
2116                         default:
2117                                 break;
2118                 }
2119         }
2120         EM_DEBUG_FUNC_END();
2121         return error_code;
2122 }
2123
2124
2125 /*  em_core_send_noti_for_new_mail is not used currently because DBUS could not send very long message.*/
2126 /*  But I think it can be used to notify incomming new mail for replacing NOTI_MAIL_ADD with some modification(uid should be replaced with mail_id).  */
2127 /*  This notification is including addtional information comparing NOTI_MAIL_ADD. */
2128 /*  By this change, email application will be able to add email item without additional DB query.  */
2129 /*  It might improve performance of sync email.  */
2130 /*  kyuho.jo 2010-09-07 */
2131
2132 EXPORT_API int em_core_send_noti_for_new_mail(int account_id, char *mailbox_name, char *subject, char *from, char *uid, char *datetime)
2133 {
2134         EM_DEBUG_FUNC_BEGIN("mailbox_name(%s) subject(%s), from(%s), uid(%s), datetime(%s)", mailbox_name, subject, from, uid, datetime);
2135         int error_code = EMF_ERROR_NONE;
2136         char *param_string = NULL;
2137
2138         if (mailbox_name == NULL || subject == NULL || from == NULL || uid == NULL || datetime == NULL) {
2139                 error_code = EMF_ERROR_INVALID_PARAM;
2140                 EM_DEBUG_EXCEPTION("Invalid parameter, mailbox_name(%p), subject(%p), from(%p), uid(%p), datetime(%p)", mailbox_name, subject, from, uid, datetime);
2141                 goto FINISH_OFF;
2142         }
2143
2144         param_string = malloc(strlen(mailbox_name) + strlen(subject) + strlen(from) + strlen(uid) + strlen(datetime) + 5);
2145
2146         if (param_string == NULL) {
2147                 error_code = EMF_ERROR_OUT_OF_MEMORY;
2148                 EM_DEBUG_EXCEPTION("Memory allocation for 'param_string' is failed");
2149                 goto FINISH_OFF;
2150         }
2151
2152         memset(param_string, 0x00, sizeof(param_string));
2153         /* TODO: account_name, thread_id */
2154         /*  uid -> mail_id */
2155         SNPRINTF(param_string, sizeof(param_string), "%s%c%s%c%s%c%s%c%s", mailbox_name, 0x01, subject, 0x01, from, 0x01, uid, 0x01, datetime);
2156
2157         if (em_storage_notify_network_event(NOTI_DOWNLOAD_NEW_MAIL, account_id, param_string, 0, 0) == 0) {     /*  failed */
2158                 error_code = EMF_ERROR_UNKNOWN;
2159                 EM_DEBUG_EXCEPTION("em_storage_notify_network_event is failed");
2160                 goto FINISH_OFF;
2161         }
2162
2163 FINISH_OFF:
2164         if (param_string)
2165                 free(param_string);     
2166         EM_DEBUG_FUNC_END();
2167         return error_code;
2168 }
2169
2170
2171 EXPORT_API 
2172 int em_core_find_tag_for_thread_view(char *subject, int *result)
2173 {
2174         EM_DEBUG_FUNC_BEGIN();
2175         int error_code = EMF_ERROR_NONE;
2176         char *copy_of_subject = NULL;
2177
2178         EM_IF_NULL_RETURN_VALUE(subject, EMF_ERROR_INVALID_PARAM);
2179         EM_IF_NULL_RETURN_VALUE(result, EMF_ERROR_INVALID_PARAM);
2180         
2181         *result = FALSE;
2182
2183         copy_of_subject = EM_SAFE_STRDUP(subject);
2184         
2185         if (copy_of_subject == NULL) {
2186                 EM_DEBUG_EXCEPTION("strdup is failed \n");
2187                 goto FINISH_OFF;
2188         }
2189         
2190         em_core_upper_string(copy_of_subject);
2191         EM_DEBUG_LOG("em_core_upper_string result : %s\n", copy_of_subject);
2192
2193         if (strstr(copy_of_subject, "RE:") == NULL) {
2194                 if (strstr(copy_of_subject, "FWD:") == NULL) {
2195                         if (strstr(copy_of_subject, "FW:") != NULL)
2196                                 *result = TRUE;         
2197                 }
2198                 else
2199                         *result = TRUE; 
2200         }
2201         else
2202                 *result = TRUE; 
2203
2204 FINISH_OFF:
2205         EM_SAFE_FREE(copy_of_subject);  
2206
2207         EM_DEBUG_FUNC_END("result : %d", *result);
2208    
2209         return error_code;
2210 }
2211
2212
2213 EXPORT_API 
2214 int em_core_find_pos_stripped_subject_for_thread_view(char *subject, char *stripped_subject)
2215 {
2216         EM_DEBUG_FUNC_BEGIN();
2217         int error_code = EMF_ERROR_NONE;
2218         int gap;
2219         char *copy_of_subject = NULL, *curpos = NULL, *result;
2220
2221         EM_IF_NULL_RETURN_VALUE(subject, EMF_ERROR_INVALID_PARAM);
2222         EM_IF_NULL_RETURN_VALUE(stripped_subject, EMF_ERROR_INVALID_PARAM);
2223         
2224         copy_of_subject = EM_SAFE_STRDUP(subject);
2225         
2226         if (copy_of_subject == NULL) {
2227                 EM_DEBUG_EXCEPTION("strdup is failed");
2228                 goto FINISH_OFF;
2229         }
2230         
2231         em_core_upper_string(copy_of_subject);
2232         curpos = copy_of_subject;
2233
2234         EM_DEBUG_LOG("em_core_upper_string result : %s", copy_of_subject);
2235
2236         while ((result = strstr(curpos, "RE:")) != NULL) {
2237                 curpos = result + 3;
2238                 EM_DEBUG_LOG("RE result : %s", curpos);
2239         }
2240
2241         while ((result = strstr(curpos, "FWD:")) != NULL) {
2242                 curpos = result + 4;    
2243                 EM_DEBUG_LOG("FWD result : %s", curpos);
2244         }
2245
2246         while ((result = strstr(curpos, "FW:")) != NULL) {
2247                 curpos = result + 3;
2248                 EM_DEBUG_LOG("FW result : %s", curpos);
2249         }
2250
2251         while (curpos != NULL && *curpos == ' ') {
2252                 curpos++;
2253         }
2254
2255         gap = curpos - copy_of_subject;
2256
2257         strcpy(stripped_subject, subject + gap);
2258
2259 FINISH_OFF:
2260         EM_SAFE_FREE(copy_of_subject);  
2261
2262         if (error_code == EMF_ERROR_NONE && stripped_subject)
2263                 EM_DEBUG_LOG("result[%s]", stripped_subject);
2264
2265         EM_DEBUG_FUNC_END("error_code[%d]", error_code);
2266         return error_code;
2267 }
2268
2269 #define MAX_TITLE_LENGTH 1024
2270 EXPORT_API int em_core_update_notification_for_unread_mail(int account_id)
2271 {
2272         EM_DEBUG_FUNC_BEGIN("account_id[%d]", account_id); 
2273         int error_code = EMF_ERROR_NONE;
2274         notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
2275
2276         if((noti_err = notification_update(NULL)) != NOTIFICATION_ERROR_NONE) {
2277                 EM_DEBUG_EXCEPTION("notification_update failed");
2278                 goto FINISH_OFF;
2279         }
2280
2281 FINISH_OFF:
2282
2283         EM_DEBUG_FUNC_END("return [%d]", error_code);
2284         return error_code;
2285 }
2286
2287 EXPORT_API int em_core_finalize_sync(int account_id, int *error)
2288 {
2289         EM_DEBUG_FUNC_BEGIN("account_id [%d], error [%p]", account_id, error);
2290         int err = EMF_ERROR_NONE, ret = true, result_sync_status = SYNC_STATUS_FINISHED;
2291         emf_mail_account_tbl_t *account_tbl = NULL;
2292
2293         if (!em_storage_update_sync_status_of_account(account_id, SET_TYPE_MINUS, SYNC_STATUS_SYNCING, true, &err)) 
2294                 EM_DEBUG_EXCEPTION("em_storage_update_sync_status_of_account failed [%d]", err);
2295
2296         if (!em_storage_get_sync_status_of_account(ALL_ACCOUNT, &result_sync_status, &err))
2297                 EM_DEBUG_EXCEPTION("em_storage_get_sync_status_of_account failed [%d]", err);
2298
2299         if ( result_sync_status == SYNC_STATUS_HAVE_NEW_MAILS) {
2300                 if (!em_core_update_notification_for_unread_mail(ALL_ACCOUNT))
2301                                 EM_DEBUG_EXCEPTION("em_core_update_notification_for_unread_mail failed");       
2302                         em_core_check_unread_mail();
2303                         /* Temp.. exception for EAS */
2304                         if(account_id >= FIRST_ACCOUNT_ID)
2305                                 em_storage_get_account_by_id(account_id, EMF_ACC_GET_OPT_DEFAULT, &account_tbl, true, &err);
2306                         if(account_tbl && account_tbl->receiving_server_type != EMF_SERVER_TYPE_ACTIVE_SYNC)
2307                                 start_alert();
2308         }
2309
2310         EM_DEBUG_FUNC_END();
2311         return ret;
2312 }
2313
2314 EXPORT_API int em_core_clear_all_notifications()
2315 {
2316         int account_count = 0, i;
2317         emf_mail_account_tbl_t *account_list;
2318         int error_code = EMF_ERROR_NONE;
2319         
2320         if(!em_storage_get_account_list(&account_count, &account_list, true, false, &error_code)) {
2321                 EM_DEBUG_EXCEPTION("em_storage_get_account_list failed");
2322                 goto FINISH_OFF;
2323         }
2324
2325         for(i = 0; i < account_count; i++) {
2326                 em_core_delete_notification_by_account(account_list[i].account_id);
2327         }
2328
2329 FINISH_OFF:
2330         if(account_count) {
2331                 em_storage_free_account(&account_list, account_count, NULL);
2332         }
2333
2334         EM_DEBUG_FUNC_END("return[%d]", error_code);
2335         return error_code;
2336 }
2337
2338 EXPORT_API int em_core_add_notification_for_unread_mail_by_mail_header(int account_id, int mail_id, emf_mail_head_t *mail_header)
2339 {
2340         EM_DEBUG_FUNC_BEGIN("mail_id[%d], mail_header[%p]", mail_id, mail_header);
2341         EM_PROFILE_BEGIN(profile_em_core_add_notification_for_unread_mail);
2342
2343         int error_code = EMF_ERROR_NONE;
2344         struct tm log_time_tm;
2345         time_t log_time = 0;
2346
2347         if (mail_header == NULL) {
2348                 EM_DEBUG_EXCEPTION("mail_header is NULL");
2349                 error_code = EMF_ERROR_INVALID_PARAM;
2350                 goto FINISH_OFF;
2351         }
2352
2353         memset(&log_time_tm, 0, sizeof(struct tm));
2354
2355         log_time_tm.tm_sec  = mail_header->datetime.second;
2356         log_time_tm.tm_min  = mail_header->datetime.minute;
2357         log_time_tm.tm_hour = mail_header->datetime.hour;
2358         log_time_tm.tm_mday = mail_header->datetime.day;
2359         log_time_tm.tm_mon  = mail_header->datetime.month;
2360         log_time_tm.tm_year = mail_header->datetime.year + 70;
2361
2362         EM_DEBUG_LOG("sec[%d], min[%d], hour[%d], day[%d], month[%d], year[%d]"
2363                                 , log_time_tm.tm_sec, log_time_tm.tm_min, log_time_tm.tm_hour, log_time_tm.tm_mday, log_time_tm.tm_mon, log_time_tm.tm_year);
2364
2365         log_time = mktime(&log_time_tm);
2366                 
2367         EM_DEBUG_LOG("log_time[%d]", log_time);
2368
2369         if (!em_core_add_notification(account_id, mail_id, mail_header->from, mail_header->subject, log_time)) {
2370                 EM_DEBUG_EXCEPTION("Failed the em_core_fill_notification_set");
2371                 goto FINISH_OFF;
2372         }
2373 FINISH_OFF:
2374
2375         EM_PROFILE_END(profile_em_core_add_notification_for_unread_mail);
2376         EM_DEBUG_FUNC_END("return[%d]", error_code);
2377         return error_code;
2378 }
2379
2380 EXPORT_API int em_core_add_notification_for_unread_mail(emf_mail_data_t *input_mail_data)
2381 {
2382         EM_DEBUG_FUNC_BEGIN("input_mail_data[%p]", input_mail_data);
2383
2384         int error_code = EMF_ERROR_NONE;
2385         struct tm log_time_tm = { 0 };
2386         time_t log_time = 0;
2387         emf_datetime_t datetime_data = { 0 };
2388
2389         if (input_mail_data == NULL) {
2390                 EM_DEBUG_EXCEPTION("input_mail_data is NULL");
2391                 error_code = EMF_ERROR_INVALID_PARAM;
2392                 goto FINISH_OFF;
2393         }
2394
2395         if(!em_convert_string_to_datetime(input_mail_data->datetime, &datetime_data, &error_code)) {
2396                 EM_DEBUG_EXCEPTION("em_convert_string_to_datetime failed");
2397                 goto FINISH_OFF;
2398         }
2399
2400         log_time_tm.tm_sec  = datetime_data.second;
2401         log_time_tm.tm_min  = datetime_data.minute;
2402         log_time_tm.tm_hour = datetime_data.hour;
2403         log_time_tm.tm_mday = datetime_data.day;
2404         log_time_tm.tm_mon  = datetime_data.month;
2405         log_time_tm.tm_year = datetime_data.year + 70;
2406
2407         EM_DEBUG_LOG("sec[%d], min[%d], hour[%d], day[%d], month[%d], year[%d]"
2408                                 , log_time_tm.tm_sec, log_time_tm.tm_min, log_time_tm.tm_hour, log_time_tm.tm_mday, log_time_tm.tm_mon, log_time_tm.tm_year);
2409
2410         log_time = mktime(&log_time_tm);
2411                 
2412         EM_DEBUG_LOG("log_time[%d]", log_time);
2413
2414         if (!em_core_add_notification(input_mail_data->account_id, input_mail_data->mail_id, input_mail_data->full_address_from, input_mail_data->subject, log_time)) {
2415                 EM_DEBUG_EXCEPTION("em_core_add_notification failed");
2416                 goto FINISH_OFF;
2417         }
2418 FINISH_OFF:
2419
2420         EM_DEBUG_FUNC_END("return[%d]", error_code);
2421         return error_code;
2422 }
2423
2424
2425 EXPORT_API int em_core_delete_notification_for_read_mail(int mail_id)
2426 {
2427         EM_DEBUG_FUNC_BEGIN();
2428         int error_code = EMF_ERROR_NONE;
2429         EM_DEBUG_FUNC_END();
2430         return error_code;
2431 }
2432
2433 #define EAS_EXECUTABLE_PATH "/usr/bin/eas-engine"
2434
2435 EXPORT_API int em_core_delete_notification_by_account(int account_id)
2436 {
2437         EM_DEBUG_FUNC_BEGIN("account_id [%d]", account_id);
2438         int error_code = EMF_ERROR_NONE;
2439         EM_DEBUG_FUNC_END();
2440         return error_code;
2441 }
2442
2443 #ifdef __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
2444
2445 /**
2446  * @fn em_core_convert_to_uid_range_set(emf_id_set_t* id_set, int id_set_count, emf_uid_range_set **uid_range_set, int range_len, int *err_code)
2447  * Prepare a linked list of uid ranges with each node having a uid_range and lowest and highest uid in it.
2448  *
2449  *@author                                       h.gahlaut@samsung.com
2450  * @param[in] id_set                    Specifies the array of mail_id and corresponding server_mail_id sorted by server_mail_ids in ascending order
2451  * @param[in] id_set_count              Specifies the no. of cells in id_set array i.e. no. of sets of mail_ids and server_mail_ids
2452  * @param[in] range_len         Specifies the maximum length of string of range allowed. 
2453  * @param[out] uid_range_set    Returns the uid_ranges formed in the form of a linked list with head stored in uid_range_set pointer
2454  * @param[out] err_code         Returns the error code.
2455  * @remarks                                     An example of a uid_range formed is 2:6,8,10,14:15,89, 
2456  *                                                      While using it the caller should remove the ending, (comma)
2457  * @return This function returns true on success or false on failure.
2458  */
2459  
2460 EXPORT_API int em_core_convert_to_uid_range_set(emf_id_set_t *id_set, int id_set_count, emf_uid_range_set **uid_range_set, int range_len, int *err_code)
2461 {
2462         EM_DEBUG_FUNC_BEGIN();
2463
2464         int ret = false;
2465         int error = EM_STORAGE_ERROR_NONE;
2466
2467         if (NULL == id_set || id_set_count  <= 0 || NULL == uid_range_set) {
2468                 EM_DEBUG_EXCEPTION(" Invalid Parameter id_set[%p] id_set_count[%d] uid_range_set[%p]", id_set, id_set_count, uid_range_set);
2469                 error = EM_STORAGE_ERROR_INVALID_PARAM;
2470                 goto FINISH_OFF;
2471         }
2472
2473         int i = 0;
2474         unsigned long current_uid = 0;
2475         unsigned long first_uid = 0;
2476         unsigned long last_uid = 0;
2477         const int max_subset_string_size = MAX_SUBSET_STRING_SIZE;                      
2478         char subset_string[MAX_SUBSET_STRING_SIZE] = {0,};      
2479         emf_uid_range_set *current_node = NULL; /* current_node denotes the current node under processing in the linked list of uid_range_set that is to be formed*/
2480
2481         if (range_len < (max_subset_string_size + 1))           /* 1 for ending NULL character */ {
2482                 EM_DEBUG_EXCEPTION(" Invalid Parameter range_len[%d]", range_len);
2483                 error = EM_STORAGE_ERROR_INVALID_PARAM;
2484                 goto FINISH_OFF;
2485         }
2486         
2487         EM_DEBUG_LOG("id set count[%d] range_len[%d]", id_set_count, range_len);
2488         
2489         do {
2490                 first_uid = last_uid = current_uid = id_set[i].server_mail_id;
2491                 /* Start subset string by putting first server mail id in it from id_set*/
2492                 memset(subset_string, 0x00, max_subset_string_size);
2493                 SNPRINTF(subset_string, max_subset_string_size, "%lu", first_uid);
2494                 ++i;
2495                 
2496                 /* Check if only one server mail id was left in id_set */
2497                 if (i >= id_set_count) {
2498                         /* No more server mail id left in id_set */
2499                         if (false == em_core_append_subset_string_to_uid_range(subset_string, &current_node, uid_range_set, range_len, first_uid, last_uid)) {
2500                                 EM_DEBUG_EXCEPTION("em_core_append_subset_string_to_uid_range failed");
2501                                 goto FINISH_OFF;
2502                         }
2503                         break;
2504                 }
2505                 else {
2506                         /* More server mail id are present in id_set. Find out if first:last_uid is to be formed or only first_uid will be subset string */
2507                         do {
2508                                 current_uid = id_set[i].server_mail_id;
2509                                 if (current_uid == (last_uid + 1)) {
2510                                         last_uid = current_uid;
2511                                         ++i;                    
2512                                 }
2513                                 else {  
2514                                         memset(subset_string, 0x00, max_subset_string_size);
2515                                         if (first_uid != last_uid)      /* Form subset string by first_uid:last_uid */
2516                                                 SNPRINTF(subset_string, max_subset_string_size, "%lu:%lu", first_uid, last_uid);
2517                                         else    /* Form subset string by first_uid */
2518                                                 SNPRINTF(subset_string, max_subset_string_size, "%lu", first_uid);
2519                                         
2520                                         if (false == em_core_append_subset_string_to_uid_range(subset_string, &current_node, uid_range_set, range_len, first_uid, last_uid)) {
2521                                                 EM_DEBUG_EXCEPTION("em_core_append_subset_string_to_uid_range failed");
2522                                                 goto FINISH_OFF;
2523                                         }
2524                                         /* To Start formation of new subset string break out of inner loop */
2525                                         break;                                  
2526                                 }
2527                                 
2528                         } while (i < id_set_count);             
2529
2530                         /* Flow comes here in two cases :
2531                         1. id_set ended and has continuous numbers at end of id_set so form subset string by first_uid:last_uid . in this  case last_uid == current_uid
2532                         2. due to break statement */
2533
2534                         if (last_uid == current_uid) {
2535                                 /* Case 1 */
2536                                 
2537                                 memset(subset_string, 0x00, max_subset_string_size);
2538                                 SNPRINTF(subset_string, max_subset_string_size, "%lu:%lu", first_uid, last_uid);
2539                         
2540                                 if (false == em_core_append_subset_string_to_uid_range(subset_string, &current_node, uid_range_set, range_len, first_uid, last_uid)) {
2541                                         EM_DEBUG_EXCEPTION("em_core_append_subset_string_to_uid_range failed");
2542                                         goto FINISH_OFF;
2543                                 }
2544                         }
2545                         else {
2546                                 /* Case 2: Do Nothing */
2547                         }
2548                                 
2549                 }               
2550         } while (i < id_set_count);
2551
2552         ret = true;
2553         
2554 FINISH_OFF:
2555         if (NULL != err_code)
2556                 *err_code = error;
2557         EM_DEBUG_FUNC_END();
2558         return ret;
2559         
2560 }  
2561
2562 /**
2563  * @fn em_core_append_subset_string_to_uid_range(char *subset_string, emf_uid_range_set **uid_range_set, int range_len, unsigned long luid, unsigned long huid)
2564  * Appends the subset_string to uid range if the uid range has not exceeded maximum length(range_len), otherwise creates a new node in linked list of uid range set 
2565  * and stores the subset_string in its uid_range. Also sets the lowest and highest uids for the corresponsing uid_range
2566  * 
2567  * @author                                      h.gahlaut@samsung.com
2568  * @param[in] subset_string     Specifies the subset string to be appended. A subset string can be like X:Y or X where X and Y are uids.
2569  * @param[in] range_len         Specifies the maximum length of range string allowed. 
2570  * @param[in] luid                      Specifies the lowest uid in subset string
2571  * @param[in] huid                      Specifies the highest uid in subset string
2572  * @param[out] uid_range_set    Returns the uid_ranges formed in the form of a linked list with head stored in uid_range_set pointer
2573  * @param[out] err_code         Returns the error code.
2574  * @remarks                                                                             
2575  * @return This function returns true on success or false on failure.
2576  */
2577  
2578 int em_core_append_subset_string_to_uid_range(char *subset_string, emf_uid_range_set **current_node_adr, emf_uid_range_set **uid_range_set, int range_len, unsigned long luid, unsigned long huid)
2579 {
2580         EM_DEBUG_FUNC_BEGIN();
2581         emf_uid_range_set *current_node = NULL;
2582
2583         if (NULL == (*uid_range_set)) {
2584                 /*This happens only once when list  creation starts. Head Node is allocated */
2585                 current_node = (emf_uid_range_set *)em_core_malloc(sizeof(emf_uid_range_set));
2586                 if (NULL == current_node) {
2587                         EM_DEBUG_EXCEPTION("em_core_malloc failed");
2588                         return false;
2589                 }       
2590
2591                 current_node->uid_range = (char *)em_core_malloc(range_len);
2592                         
2593                 if (NULL == current_node->uid_range) {
2594                         EM_DEBUG_EXCEPTION("em_core_malloc failed");
2595                         EM_SAFE_FREE(current_node);
2596                         return false;
2597                 }
2598
2599                 SNPRINTF(current_node->uid_range, range_len, "%s,", subset_string);
2600
2601                 current_node->lowest_uid = luid;
2602                 current_node->highest_uid = huid;
2603                 (*uid_range_set) = current_node;
2604
2605                 (*current_node_adr) = current_node; 
2606                 
2607         }
2608         else {
2609                 /* Apart from first call to this function flow will always come here */
2610                 current_node = (*current_node_adr);
2611                 int len_sub_string = strlen(subset_string);
2612                 int space_left_in_buffer = range_len - strlen(current_node->uid_range);
2613
2614                 if ((len_sub_string + 1 + 1) <= space_left_in_buffer)   /* 1 for comma + 1 for ending null character */ {
2615                         SNPRINTF(current_node->uid_range + strlen(current_node->uid_range), space_left_in_buffer, "%s,", subset_string);
2616                         current_node->highest_uid = huid;
2617                 }
2618                 else {
2619                         /* No more space left in uid_range string.If continued on it, it will exceeded max size of range_len */
2620                         /* Allocate new node in Uid Range set */
2621                         emf_uid_range_set *new_node = NULL;
2622
2623                         new_node = (emf_uid_range_set *)em_core_malloc(sizeof(emf_uid_range_set));
2624
2625                         if (NULL == new_node) {
2626                                 EM_DEBUG_EXCEPTION("em_core_malloc failed");
2627                                 return false;
2628                         }
2629
2630                         /* Allocate uid_range of new node */
2631                 
2632                         new_node->uid_range =  (char *)em_core_malloc(range_len);
2633
2634                         if (NULL == new_node->uid_range) {
2635                                 EM_DEBUG_EXCEPTION("em_core_malloc failed");
2636                                 EM_SAFE_FREE(new_node);
2637                                 return false;
2638                         }
2639
2640                         SNPRINTF(new_node->uid_range, range_len, "%s, ", subset_string);
2641
2642                         new_node->lowest_uid = luid;
2643                         new_node->highest_uid = huid;
2644
2645                         current_node->next = new_node;
2646
2647                         (*current_node_adr) = new_node; 
2648                 }
2649         }
2650         EM_DEBUG_FUNC_END();
2651         return true;
2652 }
2653
2654 /**
2655  * void em_core_free_uid_range_set(emf_uid_range_set **uid_range_head)
2656  * Frees the linked list of uid ranges 
2657  *
2658  * @author                                      h.gahlaut@samsung.com
2659  * @param[in] uid_range_head    Head pointer of linked list of uid ranges               
2660  * @remarks                                                                     
2661  * @return This function does not return anything.
2662  */
2663  
2664 EXPORT_API
2665 void em_core_free_uid_range_set(emf_uid_range_set **uid_range_set)
2666 {
2667         EM_DEBUG_FUNC_BEGIN();
2668
2669         emf_uid_range_set *current_node = NULL;
2670         emf_uid_range_set *uid_range_head = NULL;
2671         
2672         current_node = uid_range_head = (*uid_range_set);       /* Make the current node and head ptr point to starting of  uid_range_set */
2673
2674         while (current_node) {          
2675                 uid_range_head = current_node->next;            /* Move the head ptr to next node*/
2676
2677                 EM_SAFE_FREE(current_node->uid_range);
2678                 EM_SAFE_FREE(current_node);                             /* Free the current node */
2679
2680                 current_node = uid_range_head;                  /* Make the current node point to head ptr */
2681         }
2682
2683         (*uid_range_set) = NULL;
2684         EM_DEBUG_FUNC_END();
2685 }
2686
2687
2688 /**
2689  * @fn em_core_form_comma_separated_strings(int numbers[], int num_count, int max_string_len, char *** strings, int *string_count, int *err_code)
2690  * Forms comma separated strings of a give max_string_len from an array of numbers 
2691  * 
2692  * @author                                      h.gahlaut@samsung.com
2693  * @param[in] numbers                   Specifies the array of numbers to be converted into comma separated strings.
2694  * @param[in] num_count         Specifies the count of numbers in numbers array. 
2695  * @param[in] max_string_len    Specifies the maximum length of comma separated strings that are to be formed.
2696  * @param[out] strings                  Returns the base address of a double dimension array which stores the strings.
2697  * @param[out] string_count             Returns the number of strings formed.
2698  * @param[out] err_code         Returns the error code.
2699  * @remarks                                     If Input to the function is five numbers like 2755 2754 2748 2749 2750 and a given max_string_len is 20.
2700  *                                                      Then this function will form two comma separated strings as follows -
2701  *                                                      "2755, 2754, 2748"
2702  *                                                      "2749, 2750"
2703  * @return This function returns true on success or false on failure.
2704  */
2705
2706 EXPORT_API int em_core_form_comma_separated_strings(int numbers[], int num_count, int max_string_len, char *** strings, int *string_count, int *err_code)
2707 {
2708         EM_DEBUG_FUNC_BEGIN();
2709
2710         int error = EM_STORAGE_ERROR_NONE;
2711         int ret = false;
2712
2713         char **string_list = NULL;
2714         int num_of_strings = 0;
2715         int i = 0;
2716         int j =0;
2717         char num[MAX_INTEGER_LENGTH + 1] = {0, };
2718         int num_len = 0;
2719         int space_in_buffer = 0;
2720         int len_of_string_formed = 0;
2721
2722         if (NULL == numbers || num_count <= 0 || \
2723                 max_string_len < (MAX_INTEGER_LENGTH + 2)|| NULL == strings || NULL == string_count)                    /*  32767, is the highest integer possible in string.This requires 7 bytes of storage in character type array (1 byte for ending NULL and 1 byte for ending comma) so max_string_len should not be less than worst case possible.  */ {
2724                 EM_DEBUG_EXCEPTION("Invalid Parameter numbers[%p] num_count [%d] max_string_len [%d] strings [%p] string_count[%p]", \
2725                         numbers, num_count, max_string_len, strings, string_count);
2726                 error = EM_STORAGE_ERROR_INVALID_PARAM;
2727                 goto FINISH_OFF;
2728         }
2729
2730         EM_DEBUG_LOG("num_count [%d] max_string_len [%d]", num_count, max_string_len);
2731
2732         string_list = em_core_malloc(sizeof(char *));
2733
2734         if (NULL == string_list) {
2735                 EM_DEBUG_EXCEPTION("em_core_malloc failed ");
2736                 goto FINISH_OFF;
2737         }
2738         
2739         string_list[num_of_strings] = em_core_malloc(max_string_len);
2740         
2741         if (NULL == string_list[num_of_strings]) {
2742                 EM_DEBUG_EXCEPTION("em_core_malloc failed ");
2743                 goto FINISH_OFF;
2744         }
2745         
2746         ++num_of_strings;
2747         space_in_buffer = max_string_len;
2748         
2749         for (j = 0; j < num_count;++j) {
2750                 memset(num, 0x00, MAX_INTEGER_LENGTH + 1);
2751                 SNPRINTF(num, MAX_INTEGER_LENGTH + 1, "%d", numbers[j]);
2752
2753                 num_len = strlen(num);
2754                 
2755                 len_of_string_formed = strlen(string_list[num_of_strings - 1]);
2756
2757                 space_in_buffer = max_string_len - len_of_string_formed ;
2758
2759                 if (space_in_buffer >= (num_len+1+1))                   /*  1 for comma and 1 for ending NULL */ {
2760                         SNPRINTF(string_list[num_of_strings - 1] + len_of_string_formed, max_string_len, "%d,", numbers[j]);
2761                 }
2762                 else {  /*  Removing comma at end of string  */
2763                         string_list[num_of_strings - 1][len_of_string_formed-1] = '\0';         
2764                         char **temp = NULL;
2765                         temp = (char **)realloc(string_list, sizeof(char *) * (num_of_strings + 1));    /*  Allocate new buffer to store a pointer to a new string */
2766
2767                         if (NULL == temp) {     
2768                                 EM_DEBUG_EXCEPTION("realloc failed");
2769                                 goto FINISH_OFF;
2770                         }
2771
2772                         memset(temp + num_of_strings, 0X00, sizeof(char *));
2773
2774                         string_list = temp;
2775                         temp = NULL;
2776                         string_list[num_of_strings] = em_core_malloc(max_string_len);/*  Allocate new buffer to store the string */
2777
2778                         if (NULL == string_list[num_of_strings]) {
2779                                 EM_DEBUG_EXCEPTION(" em_core_malloc failed ");
2780                                 goto FINISH_OFF;
2781                         }
2782                         ++num_of_strings;
2783                         SNPRINTF(string_list[num_of_strings - 1] , max_string_len, "%d,", numbers[j]);/*  Start making new string */
2784                 }
2785         }
2786
2787         /*  Removing comma at end of string  */
2788         len_of_string_formed = strlen(string_list[num_of_strings - 1]);
2789         string_list[num_of_strings - 1][len_of_string_formed-1] = '\0'; 
2790         ret = true;
2791
2792 FINISH_OFF:
2793
2794         if (false == ret)
2795                 em_core_free_comma_separated_strings(&string_list, &num_of_strings);
2796
2797         if (true == ret) {
2798                 for (i = 0; i < num_of_strings;++i)
2799                         EM_DEBUG_LOG("%s", string_list[i]);
2800                 *strings = string_list;
2801                 *string_count = num_of_strings;
2802         }
2803         
2804
2805         if (NULL != err_code)
2806                 *err_code = error;
2807
2808         EM_DEBUG_FUNC_END("ret [%d]", ret);
2809         return ret;
2810 }
2811 /**
2812  * @fn em_core_free_comma_separated_strings(char *** string_list, int *string_count)
2813  * Frees the double dimensional array of strings. 
2814  *
2815  * @author                                      h.gahlaut@samsung.com
2816  * @param[in] uid_range_head    Address of base address of double dimensional array of strings.
2817  * @param[in] string_count              Address of variable holding the count of strings.
2818  * @remarks                                                                     
2819  * @return This function does not return anything.
2820  */
2821 EXPORT_API void em_core_free_comma_separated_strings(char *** string_list, int *string_count)
2822 {
2823         EM_DEBUG_FUNC_BEGIN();
2824         int i = 0;
2825         char **str_list = NULL;
2826         int count = 0;
2827
2828         if (NULL != string_list) {
2829                 str_list = *string_list;
2830
2831                 if (0 != *string_count) {
2832                         count = *string_count;
2833                         for (i = 0; i < count; ++i)
2834                                 EM_SAFE_FREE(str_list[i]);
2835                 }
2836                 
2837                 EM_SAFE_FREE(str_list);
2838                 *string_list = NULL;    /*  This makes the pointer to be freed as NULL in calling function and saves it from being a dangling pointer for sometime in calling function */
2839                 *string_count = 0;
2840         }
2841         EM_DEBUG_FUNC_END();
2842 }
2843
2844
2845 #endif
2846
2847
2848 #include <sys/mman.h>
2849
2850 /* #define GETSP()                              ({ unsigned int sp; asm volatile ("mov %0, sp " : "=r"(sp)); sp;}) */
2851 #define BUF_SIZE                                256
2852 #define PAGE_SIZE                       (1 << 12)
2853 #define _ALIGN_UP(addr, size)   (((addr)+((size)-1))&(~((size)-1)))
2854 #define _ALIGN_DOWN(addr, size)  ((addr)&(~((size)-1)))
2855 #define PAGE_ALIGN(addr)                _ALIGN_DOWN(addr, PAGE_SIZE)
2856
2857 int stack_trim(void)
2858 {
2859         /*
2860         char buf[BUF_SIZE];
2861         FILE *file;
2862         unsigned int stacktop;
2863         int found = 0;
2864         unsigned int sp; 
2865
2866         asm volatile ("mov %0, sp " : "=r"(sp));
2867
2868         sprintf(buf, "/proc/%d/maps", getpid());
2869         file = fopen(buf, "r");
2870         while (fgets(buf, BUF_SIZE, file) != NULL) {
2871                 if (strstr(buf, "[stack]")) {
2872                         found = 1;
2873                         break;
2874                 }
2875         }
2876         
2877         fclose(file);
2878
2879         if (found) {
2880                 sscanf(buf, "%x-", &stacktop);
2881                 if (madvise((void *)PAGE_ALIGN(stacktop), PAGE_ALIGN(sp)-stacktop, MADV_DONTNEED) < 0)
2882                         perror("stack madvise fail");
2883         }
2884         */
2885         return 1;
2886 }
2887
2888
2889 EXPORT_API void em_core_flush_memory()
2890 {
2891         EM_DEBUG_FUNC_BEGIN();
2892         /*  flush memory in heap */
2893         malloc_trim(0);
2894
2895         /*  flush memory in stack */
2896         stack_trim();
2897
2898         /*  flush memory for sqlite */
2899         em_storage_flush_db_cache();
2900         EM_DEBUG_FUNC_END();
2901 }
2902
2903 EXPORT_API int em_core_make_attachment_file_name_with_extension(char *source_file_name, char *sub_type, char *result_file_name, int result_file_name_buffer_length, int *err_code)
2904 {
2905         EM_DEBUG_FUNC_BEGIN("source_file_name[%s], sub_type[%s], result_file_name_buffer_length[%d] ", source_file_name, sub_type, result_file_name_buffer_length);
2906         int ret = false, err = EMF_ERROR_NONE;
2907         char *extcheck = NULL;
2908         char attachment_file_name[MAX_PATH + 1] = { 0, };
2909
2910         if (!source_file_name || !result_file_name) {
2911                 EM_DEBUG_EXCEPTION("Invalid Parameter");
2912                 err  = EMF_ERROR_INVALID_PARAM;
2913                 goto FINISH_OFF;
2914         }
2915                                 
2916         strncpy(attachment_file_name, source_file_name, MAX_PATH);
2917         extcheck = strchr(attachment_file_name, '.');
2918
2919         if (extcheck)
2920                 EM_DEBUG_LOG("Extension Exist in the Attachment [%s] ", extcheck);
2921         else  { /* No extension attached, So add the Extension based on the subtype */
2922                 if (sub_type) {
2923                         strcat(attachment_file_name, ".");
2924                         strcat(attachment_file_name, sub_type);
2925                         EM_DEBUG_LOG("attachment_file_name with extension[%s] ", attachment_file_name);
2926                 }
2927                 else
2928                         EM_DEBUG_LOG("UnKnown Extesnsion");
2929
2930         }
2931         memset(result_file_name, 0 , result_file_name_buffer_length);
2932         EM_SAFE_STRNCPY(result_file_name, attachment_file_name, result_file_name_buffer_length - 1);
2933         EM_DEBUG_LOG("*result_file_name[%s]", result_file_name);
2934         ret = true;
2935
2936 FINISH_OFF:
2937         if (err_code)
2938                 *err_code = err;
2939         EM_DEBUG_FUNC_END();
2940         return ret;
2941 }
2942
2943 EXPORT_API char *em_core_get_extension_from_file_path(char *source_file_path, int *err_code)
2944 {
2945         EM_DEBUG_FUNC_BEGIN("source_file_path[%s]", source_file_path);
2946         int err = EMF_ERROR_NONE, pos_on_string = 0;
2947         char *extension = NULL;
2948
2949         if (!source_file_path) {
2950                 EM_DEBUG_EXCEPTION("Invalid Parameter");
2951                 err  = EMF_ERROR_INVALID_PARAM;
2952                 goto FINISH_OFF;
2953         }
2954         
2955         pos_on_string = strlen(source_file_path) - 1;   
2956
2957         while(pos_on_string > 0 && source_file_path[pos_on_string--] != '.') ;
2958
2959         if(pos_on_string > 0)
2960                 extension = source_file_path + pos_on_string + 2;
2961         
2962         EM_DEBUG_LOG("*extension [%s] pos_on_string [%d]", extension, pos_on_string);
2963
2964 FINISH_OFF:
2965         if (err_code)
2966                 *err_code = err;
2967         EM_DEBUG_FUNC_END();
2968         return extension;
2969 }
2970
2971 EXPORT_API int em_core_get_encoding_type_from_file_path(const char *input_file_path, char **output_encoding_type)
2972 {
2973         EM_DEBUG_FUNC_BEGIN("input_file_path[%d], output_encoding_type[%p]", input_file_path, output_encoding_type);
2974         int   err = EMF_ERROR_NONE;
2975         int   pos_of_filename = 0;
2976         int   pos_of_dot = 0;
2977         int   enf_of_string = 0;
2978         int   result_string_length = 0;
2979         char *filename = NULL;
2980         char *result_encoding_type = NULL;
2981
2982         if (!input_file_path || !output_encoding_type) {
2983                 EM_DEBUG_EXCEPTION("Invalid Parameter");
2984                 err  = EMF_ERROR_INVALID_PARAM;
2985                 goto FINISH_OFF;
2986         }
2987         
2988         enf_of_string = pos_of_filename = strlen(input_file_path) - 1;  
2989
2990         while(pos_of_filename >= 0 && input_file_path[pos_of_filename--] != '/') {
2991                 if(input_file_path[pos_of_filename] == '.')
2992                         pos_of_dot = pos_of_filename;
2993         }
2994
2995         if(pos_of_filename != 0) 
2996                 pos_of_filename += 2;
2997
2998         filename = (char*)input_file_path + pos_of_filename;
2999
3000         if(pos_of_dot != 0 && pos_of_dot > pos_of_filename) 
3001                 result_string_length = pos_of_dot - pos_of_filename;
3002         else
3003                 result_string_length = enf_of_string - pos_of_filename;
3004                 
3005         EM_DEBUG_LOG("pos_of_dot [%d], pos_of_filename [%d], enf_of_string[%d],result_string_length [%d]", pos_of_dot, pos_of_filename, enf_of_string, result_string_length);
3006
3007         if( !(result_encoding_type =    em_core_malloc(sizeof(char) * (result_string_length + 1))) ) {
3008                 EM_DEBUG_EXCEPTION("EMF_ERROR_OUT_OF_MEMORY");
3009                 err  = EMF_ERROR_OUT_OF_MEMORY;
3010                 goto FINISH_OFF;
3011         }
3012
3013         memcpy(result_encoding_type, input_file_path + pos_of_filename, result_string_length);
3014         
3015         EM_DEBUG_LOG("*result_encoding_type [%s]", result_encoding_type);
3016
3017         *output_encoding_type = result_encoding_type;
3018
3019 FINISH_OFF:
3020         EM_DEBUG_FUNC_END("err [%d]", err);
3021         return err;
3022 }
3023
3024
3025 EXPORT_API int em_core_get_content_type(const char *extension_string, int *err_code)
3026 {
3027         EM_DEBUG_FUNC_BEGIN("extension_string[%s]", extension_string);
3028         int i = 0, err = EMF_ERROR_NONE, result_content_type = TYPEAPPLICATION;
3029         char *image_extension[] = { "jpeg", "jpg", "png", "gif", "bmp", "pic", "agif", "tif", "wbmp" , NULL};
3030
3031         if (!extension_string) {
3032                 EM_DEBUG_EXCEPTION("Invalid Parameter");
3033                 err  = EMF_ERROR_INVALID_PARAM;
3034                 goto FINISH_OFF;
3035         }
3036         
3037         while(image_extension[i]) {
3038                 EM_DEBUG_LOG("image_extension[%d] [%s]", i, image_extension[i]);
3039                 if(strcasecmp(image_extension[i], extension_string) == 0) {
3040                         result_content_type = TYPEIMAGE;
3041                         break;
3042                 }
3043                 i++;
3044         }
3045
3046 FINISH_OFF:
3047         if (err_code)
3048                 *err_code = err;
3049         EM_DEBUG_FUNC_END();
3050         return result_content_type;
3051 }
3052
3053 #define DATE_TIME_STRING_LEGNTH 14
3054
3055 EXPORT_API char* em_core_get_current_time_string(int *err)
3056 {
3057         EM_DEBUG_FUNC_BEGIN("err [%p]", err);
3058         
3059         int err_code = EMF_ERROR_NONE;
3060         time_t t = time(NULL);
3061         struct tm *p_tm = NULL; 
3062         char *result_date_time = NULL;  
3063         
3064         p_tm = gmtime(&t);
3065
3066         if (!p_tm)  {
3067                 EM_DEBUG_EXCEPTION("localtime failed...");
3068                 err_code = EMF_ERROR_SYSTEM_FAILURE;
3069                 goto FINISH_OFF;
3070         }
3071
3072         result_date_time = em_core_malloc(DATE_TIME_STRING_LEGNTH + 1);
3073
3074         SNPRINTF(result_date_time, DATE_TIME_STRING_LEGNTH + 1, "%04d%02d%02d%02d%02d%02d",
3075                 p_tm->tm_year + 1900, p_tm->tm_mon + 1, p_tm->tm_mday, 
3076                 p_tm->tm_hour, p_tm->tm_min, p_tm->tm_sec);
3077
3078         EM_DEBUG_LOG("result_date_time [%s]", result_date_time);
3079 FINISH_OFF:
3080
3081         if(err)
3082                 *err = err_code;
3083
3084         EM_DEBUG_FUNC_END();
3085         return result_date_time;
3086 }
3087
3088
3089 #ifdef __LOCAL_ACTIVITY__
3090 EXPORT_API int em_core_activity_add(emf_activity_tbl_t *new_activity, int *err_code)
3091 {
3092         EM_DEBUG_FUNC_BEGIN();
3093         
3094         EM_DEBUG_LOG("\t new_activity[%p], err_code[%p]", new_activity, err_code);
3095
3096         /*  default variable */
3097         int ret = false;
3098         int err = EMF_ERROR_NONE;
3099         
3100         if (!new_activity) {
3101                 EM_DEBUG_LOG("\t new_activity[%p]\n", new_activity);
3102                 err = EMF_ERROR_INVALID_PARAM;
3103                 goto FINISH_OFF;
3104         }
3105         if (!em_storage_add_activity(new_activity, false, &err)) {
3106                 EM_DEBUG_LOG("\t em_storage_add_activity falied - %d\n", err);
3107                 
3108                 goto FINISH_OFF;
3109         }
3110         ret = true;
3111         
3112 FINISH_OFF:
3113         if (err_code)
3114                 *err_code = err;
3115         
3116         return ret;
3117 }
3118
3119 EXPORT_API int em_core_activity_delete(emf_activity_tbl_t *activity, int *err_code)
3120 {
3121         EM_DEBUG_FUNC_BEGIN();
3122         
3123         EM_DEBUG_LOG("\t new_activity[%p], err_code[%p]", activity, err_code);
3124         
3125         /*  default variable */
3126         int ret = false;
3127         int err = EMF_ERROR_NONE;
3128         if (!activity) {
3129                 EM_DEBUG_LOG("\t new_activity[%p]\n", activity);
3130                 
3131                 err = EMF_ERROR_INVALID_PARAM;
3132                 goto FINISH_OFF;
3133         }
3134         if (!em_storage_delete_local_activity(activity, true, &err)) {
3135                 EM_DEBUG_LOG("\t em_storage_delete_local_activity falied - %d\n", err);
3136                 
3137                 goto FINISH_OFF;
3138         }
3139         ret = true;
3140         
3141 FINISH_OFF:
3142         if (err_code)
3143                 *err_code = err;
3144         
3145         return ret;
3146 }
3147
3148 EXPORT_API int em_core_get_next_activity_id(int *activity_id, int *err_code)
3149 {
3150         EM_DEBUG_FUNC_BEGIN();
3151         
3152         int ret = false;
3153         int err = EMF_ERROR_NONE;
3154
3155         if (NULL == activity_id)
3156         {
3157                 EM_DEBUG_EXCEPTION("\t activity_id[%p]", activity_id);
3158                 
3159                 err = EM_STORAGE_ERROR_INVALID_PARAM;
3160                 goto FINISH_OFF;
3161         }
3162         
3163         if (false == em_storage_get_next_activity_id(activity_id, &err)) {
3164                 EM_DEBUG_LOG("\t em_storage_get_next_activity_id failed - %d\n", err);
3165                 goto FINISH_OFF;
3166         }
3167         
3168         ret = true;
3169         
3170         FINISH_OFF:
3171         if (NULL != err_code) {
3172                 *err_code = err;
3173         }
3174         
3175         return ret;
3176
3177 }
3178
3179 #endif /* __LOCAL_ACTIVITY__ */
3180
3181
3182
3183 /* EOF */