Fix an incorrect call to soup_message_set_request.
[pidgin-git.git] / libpurple / log.c
blob956e9c8171ae6c69297efe4654e320e2dfe9226e
1 /* purple
3 * Purple is the legal property of its developers, whose names are too numerous
4 * to list here. Please refer to the COPYRIGHT file distributed with this
5 * source distribution.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
22 #include "internal.h"
23 #include "account.h"
24 #include "debug.h"
25 #include "glibcompat.h"
26 #include "image-store.h"
27 #include "log.h"
28 #include "prefs.h"
29 #include "util.h"
30 #include "stringref.h"
31 #include "time.h"
33 static GSList *loggers = NULL;
35 static PurpleLogLogger *html_logger;
36 static PurpleLogLogger *txt_logger;
37 static PurpleLogLogger *old_logger;
39 struct _purple_logsize_user {
40 char *name;
41 PurpleAccount *account;
43 static GHashTable *logsize_users = NULL;
44 static GHashTable *logsize_users_decayed = NULL;
46 static void log_get_log_sets_common(GHashTable *sets);
48 static gsize html_logger_write(PurpleLog *log, PurpleMessageFlags type,
49 const char *from, GDateTime *time, const char *message);
50 static void html_logger_finalize(PurpleLog *log);
51 static GList *html_logger_list(PurpleLogType type, const char *sn, PurpleAccount *account);
52 static GList *html_logger_list_syslog(PurpleAccount *account);
53 static char *html_logger_read(PurpleLog *log, PurpleLogReadFlags *flags);
54 static int html_logger_total_size(PurpleLogType type, const char *name, PurpleAccount *account);
56 static GList *old_logger_list(PurpleLogType type, const char *sn, PurpleAccount *account);
57 static int old_logger_total_size(PurpleLogType type, const char *name, PurpleAccount *account);
58 static char * old_logger_read (PurpleLog *log, PurpleLogReadFlags *flags);
59 static int old_logger_size (PurpleLog *log);
60 static void old_logger_get_log_sets(PurpleLogSetCallback cb, GHashTable *sets);
61 static void old_logger_finalize(PurpleLog *log);
63 static gsize txt_logger_write(PurpleLog *log, PurpleMessageFlags type,
64 const char *from, GDateTime *time, const char *message);
65 static void txt_logger_finalize(PurpleLog *log);
66 static GList *txt_logger_list(PurpleLogType type, const char *sn, PurpleAccount *account);
67 static GList *txt_logger_list_syslog(PurpleAccount *account);
68 static char *txt_logger_read(PurpleLog *log, PurpleLogReadFlags *flags);
69 static int txt_logger_total_size(PurpleLogType type, const char *name, PurpleAccount *account);
71 /**************************************************************************
72 * PUBLIC LOGGING FUNCTIONS ***********************************************
73 **************************************************************************/
75 PurpleLog *purple_log_new(PurpleLogType type, const char *name, PurpleAccount *account,
76 PurpleConversation *conv, GDateTime *time)
78 PurpleLog *log;
80 /* IMPORTANT: Make sure to initialize all the members of PurpleLog */
81 log = g_slice_new(PurpleLog);
83 log->type = type;
84 log->name = g_strdup(purple_normalize(account, name));
85 log->account = account;
86 log->conv = conv;
87 if (time)
88 log->time = g_date_time_ref(time);
89 else
90 log->time = NULL;
91 log->logger = purple_log_logger_get();
92 log->logger_data = NULL;
94 if (log->logger && log->logger->create)
95 log->logger->create(log);
96 return log;
99 void purple_log_free(PurpleLog *log)
101 g_return_if_fail(log);
102 if (log->logger && log->logger->finalize)
103 log->logger->finalize(log);
104 g_free(log->name);
105 if (log->time)
106 g_date_time_unref(log->time);
108 g_slice_free(PurpleLog, log);
111 void purple_log_write(PurpleLog *log, PurpleMessageFlags type,
112 const char *from, GDateTime *time, const char *message)
114 struct _purple_logsize_user *lu;
115 gsize written, total = 0;
116 gpointer ptrsize;
118 g_return_if_fail(log);
119 g_return_if_fail(log->logger);
120 g_return_if_fail(log->logger->write);
122 written = (log->logger->write)(log, type, from, time, message);
124 lu = g_new(struct _purple_logsize_user, 1);
126 lu->name = g_strdup(purple_normalize(log->account, log->name));
127 lu->account = log->account;
129 if(g_hash_table_lookup_extended(logsize_users, lu, NULL, &ptrsize)) {
130 char *tmp = lu->name;
132 total = GPOINTER_TO_INT(ptrsize);
133 total += written;
134 g_hash_table_replace(logsize_users, lu, GINT_TO_POINTER(total));
136 /* The hash table takes ownership of lu, so create a new one
137 * for the logsize_users_decayed check below. */
138 lu = g_new(struct _purple_logsize_user, 1);
139 lu->name = g_strdup(tmp);
140 lu->account = log->account;
143 if(g_hash_table_lookup_extended(logsize_users_decayed, lu, NULL, &ptrsize)) {
144 total = GPOINTER_TO_INT(ptrsize);
145 total += written;
146 g_hash_table_replace(logsize_users_decayed, lu, GINT_TO_POINTER(total));
147 } else {
148 g_free(lu->name);
149 g_free(lu);
153 char *purple_log_read(PurpleLog *log, PurpleLogReadFlags *flags)
155 PurpleLogReadFlags mflags;
156 g_return_val_if_fail(log && log->logger, NULL);
157 if (log->logger->read) {
158 char *ret = (log->logger->read)(log, flags ? flags : &mflags);
159 purple_str_strip_char(ret, '\r');
160 return ret;
162 return g_strdup(_("<b><font color=\"red\">The logger has no read function</font></b>"));
165 int purple_log_get_size(PurpleLog *log)
167 g_return_val_if_fail(log && log->logger, 0);
169 if (log->logger->size)
170 return log->logger->size(log);
171 return 0;
174 static guint _purple_logsize_user_hash(struct _purple_logsize_user *lu)
176 return g_str_hash(lu->name);
179 static guint _purple_logsize_user_equal(struct _purple_logsize_user *lu1,
180 struct _purple_logsize_user *lu2)
182 return (lu1->account == lu2->account && purple_strequal(lu1->name, lu2->name));
185 static void _purple_logsize_user_free_key(struct _purple_logsize_user *lu)
187 g_free(lu->name);
188 g_free(lu);
191 int purple_log_get_total_size(PurpleLogType type, const char *name, PurpleAccount *account)
193 gpointer ptrsize;
194 int size = 0;
195 GSList *n;
196 struct _purple_logsize_user *lu;
198 lu = g_new(struct _purple_logsize_user, 1);
199 lu->name = g_strdup(purple_normalize(account, name));
200 lu->account = account;
202 if(g_hash_table_lookup_extended(logsize_users, lu, NULL, &ptrsize)) {
203 size = GPOINTER_TO_INT(ptrsize);
204 g_free(lu->name);
205 g_free(lu);
206 } else {
207 for (n = loggers; n; n = n->next) {
208 PurpleLogLogger *logger = n->data;
210 if(logger->total_size){
211 size += (logger->total_size)(type, name, account);
212 } else if(logger->list) {
213 GList *logs = (logger->list)(type, name, account);
214 int this_size = 0;
216 while (logs) {
217 PurpleLog *log = (PurpleLog*)(logs->data);
218 this_size += purple_log_get_size(log);
219 purple_log_free(log);
220 logs = g_list_delete_link(logs, logs);
223 size += this_size;
227 g_hash_table_replace(logsize_users, lu, GINT_TO_POINTER(size));
229 return size;
232 gint purple_log_get_activity_score(PurpleLogType type, const char *name, PurpleAccount *account)
234 gpointer ptrscore;
235 int score;
236 GSList *n;
237 struct _purple_logsize_user *lu;
239 lu = g_new(struct _purple_logsize_user, 1);
240 lu->name = g_strdup(purple_normalize(account, name));
241 lu->account = account;
243 if(g_hash_table_lookup_extended(logsize_users_decayed, lu, NULL, &ptrscore)) {
244 score = GPOINTER_TO_INT(ptrscore);
245 g_free(lu->name);
246 g_free(lu);
247 } else {
248 GDateTime *now = g_date_time_new_now_utc();
249 double score_double = 0.0;
250 for (n = loggers; n; n = n->next) {
251 PurpleLogLogger *logger = n->data;
253 if(logger->list) {
254 GList *logs = (logger->list)(type, name, account);
256 while (logs) {
257 PurpleLog *log = (PurpleLog*)(logs->data);
258 if (!log) {
259 g_warn_if_reached();
260 continue;
262 /* Activity score counts bytes in the log, exponentially
263 decayed with a half-life of 14 days. */
264 score_double += purple_log_get_size(log) *
265 pow(0.5, g_date_time_difference(now, log->time)/(14LL*G_TIME_SPAN_DAY));
266 purple_log_free(log);
267 logs = g_list_delete_link(logs, logs);
271 g_date_time_unref(now);
273 score = (gint) ceil(score_double);
274 g_hash_table_replace(logsize_users_decayed, lu, GINT_TO_POINTER(score));
276 return score;
279 gboolean purple_log_is_deletable(PurpleLog *log)
281 g_return_val_if_fail(log != NULL, FALSE);
282 g_return_val_if_fail(log->logger != NULL, FALSE);
284 if (log->logger->remove == NULL)
285 return FALSE;
287 if (log->logger->is_deletable != NULL)
288 return log->logger->is_deletable(log);
290 return TRUE;
293 gboolean purple_log_delete(PurpleLog *log)
295 g_return_val_if_fail(log != NULL, FALSE);
296 g_return_val_if_fail(log->logger != NULL, FALSE);
298 if (log->logger->remove != NULL)
299 return log->logger->remove(log);
301 return FALSE;
304 char *
305 purple_log_get_log_dir(PurpleLogType type, const char *name, PurpleAccount *account)
307 PurpleProtocol *protocol;
308 const char *protocol_name;
309 char *acct_name;
310 const char *target;
311 char *dir;
313 protocol = purple_protocols_find(purple_account_get_protocol_id(account));
314 if (!protocol)
315 return NULL;
317 protocol_name = purple_protocol_class_list_icon(protocol, account, NULL);
319 acct_name = g_strdup(purple_escape_filename(purple_normalize(account,
320 purple_account_get_username(account))));
322 if (type == PURPLE_LOG_CHAT) {
323 char *temp = g_strdup_printf("%s.chat", purple_normalize(account, name));
324 target = purple_escape_filename(temp);
325 g_free(temp);
326 } else if(type == PURPLE_LOG_SYSTEM) {
327 target = ".system";
328 } else {
329 target = purple_escape_filename(purple_normalize(account, name));
332 dir = g_build_filename(purple_data_dir(), "logs", protocol_name, acct_name, target, NULL);
334 g_free(acct_name);
336 return dir;
339 /****************************************************************************
340 * LOGGER FUNCTIONS *********************************************************
341 ****************************************************************************/
343 static PurpleLogLogger *current_logger = NULL;
345 static void logger_pref_cb(const char *name, PurplePrefType type,
346 gconstpointer value, gpointer data)
348 PurpleLogLogger *logger;
349 GSList *l = loggers;
350 while (l) {
351 logger = l->data;
352 if (purple_strequal(logger->id, value)) {
353 purple_log_logger_set(logger);
354 return;
356 l = l->next;
358 purple_log_logger_set(txt_logger);
362 PurpleLogLogger *purple_log_logger_new(const char *id, const char *name, int functions, ...)
364 PurpleLogLogger *logger;
365 va_list args;
367 g_return_val_if_fail(id != NULL, NULL);
368 g_return_val_if_fail(name != NULL, NULL);
369 g_return_val_if_fail(functions >= 1, NULL);
371 logger = g_new0(PurpleLogLogger, 1);
372 logger->id = g_strdup(id);
373 logger->name = g_strdup(name);
375 va_start(args, functions);
377 if (functions >= 1)
378 logger->create = va_arg(args, void *);
379 if (functions >= 2)
380 logger->write = va_arg(args, void *);
381 if (functions >= 3)
382 logger->finalize = va_arg(args, void *);
383 if (functions >= 4)
384 logger->list = va_arg(args, void *);
385 if (functions >= 5)
386 logger->read = va_arg(args, void *);
387 if (functions >= 6)
388 logger->size = va_arg(args, void *);
389 if (functions >= 7)
390 logger->total_size = va_arg(args, void *);
391 if (functions >= 8)
392 logger->list_syslog = va_arg(args, void *);
393 if (functions >= 9)
394 logger->get_log_sets = va_arg(args, void *);
395 if (functions >= 10)
396 logger->remove = va_arg(args, void *);
397 if (functions >= 11)
398 logger->is_deletable = va_arg(args, void *);
400 if (functions >= 12)
401 purple_debug_info("log", "Dropping new functions for logger: %s (%s)\n", name, id);
403 va_end(args);
405 return logger;
408 void purple_log_logger_free(PurpleLogLogger *logger)
410 if (!logger)
411 return;
412 g_free(logger->name);
413 g_free(logger->id);
414 g_free(logger);
417 void purple_log_logger_add (PurpleLogLogger *logger)
419 g_return_if_fail(logger);
420 if (g_slist_find(loggers, logger))
421 return;
422 loggers = g_slist_append(loggers, logger);
423 if (purple_strequal(purple_prefs_get_string("/purple/logging/format"), logger->id)) {
424 purple_prefs_trigger_callback("/purple/logging/format");
428 void purple_log_logger_remove (PurpleLogLogger *logger)
430 g_return_if_fail(logger);
431 loggers = g_slist_remove(loggers, logger);
434 void purple_log_logger_set (PurpleLogLogger *logger)
436 g_return_if_fail(logger);
437 current_logger = logger;
440 PurpleLogLogger *purple_log_logger_get()
442 return current_logger;
445 GList *purple_log_logger_get_options(void)
447 GSList *n;
448 GList *list = NULL;
449 PurpleLogLogger *data;
451 for (n = loggers; n; n = n->next) {
452 data = n->data;
453 if (!data->write)
454 continue;
455 list = g_list_append(list, data->name);
456 list = g_list_append(list, data->id);
459 return list;
462 gint purple_log_compare(gconstpointer y, gconstpointer z)
464 const PurpleLog *a = y;
465 const PurpleLog *b = z;
467 /* Sort in reverse order. */
468 return g_date_time_compare(b->time, a->time);
471 GList *purple_log_get_logs(PurpleLogType type, const char *name, PurpleAccount *account)
473 GList *logs = NULL;
474 GSList *n;
475 for (n = loggers; n; n = n->next) {
476 PurpleLogLogger *logger = n->data;
477 if (!logger->list)
478 continue;
479 logs = g_list_concat(logger->list(type, name, account), logs);
482 return g_list_sort(logs, purple_log_compare);
485 gint purple_log_set_compare(gconstpointer y, gconstpointer z)
487 const PurpleLogSet *a = y;
488 const PurpleLogSet *b = z;
489 gint ret = 0;
491 /* This logic seems weird at first...
492 * If either account is NULL, we pretend the accounts are
493 * equal. This allows us to detect duplicates that will
494 * exist if one logger knows the account and another
495 * doesn't. */
496 if (a->account != NULL && b->account != NULL) {
497 ret = strcmp(purple_account_get_username(a->account), purple_account_get_username(b->account));
498 if (ret != 0)
499 return ret;
502 ret = strcmp(a->normalized_name, b->normalized_name);
503 if (ret != 0)
504 return ret;
506 return (gint)b->type - (gint)a->type;
509 static guint
510 log_set_hash(gconstpointer key)
512 const PurpleLogSet *set = key;
514 /* The account isn't hashed because we need PurpleLogSets with NULL accounts
515 * to be found when we search by a PurpleLogSet that has a non-NULL account
516 * but the same type and name. */
517 return g_int_hash(&set->type) + g_str_hash(set->name);
520 static gboolean
521 log_set_equal(gconstpointer a, gconstpointer b)
523 /* I realize that the choices made for GList and GHashTable
524 * make sense for those data types, but I wish the comparison
525 * functions were compatible. */
526 return !purple_log_set_compare(a, b);
529 static void
530 log_add_log_set_to_hash(GHashTable *sets, PurpleLogSet *set)
532 PurpleLogSet *existing_set = g_hash_table_lookup(sets, set);
534 if (existing_set == NULL)
535 g_hash_table_insert(sets, set, set);
536 else if (existing_set->account == NULL && set->account != NULL)
537 g_hash_table_replace(sets, set, set);
538 else
539 purple_log_set_free(set);
542 GHashTable *purple_log_get_log_sets(void)
544 GSList *n;
545 GHashTable *sets = g_hash_table_new_full(log_set_hash, log_set_equal,
546 (GDestroyNotify)purple_log_set_free, NULL);
548 /* Get the log sets from all the loggers. */
549 for (n = loggers; n; n = n->next) {
550 PurpleLogLogger *logger = n->data;
552 if (!logger->get_log_sets)
553 continue;
555 logger->get_log_sets(log_add_log_set_to_hash, sets);
558 log_get_log_sets_common(sets);
560 /* Return the GHashTable of unique PurpleLogSets. */
561 return sets;
564 void purple_log_set_free(PurpleLogSet *set)
566 g_return_if_fail(set != NULL);
568 g_free(set->name);
569 if (set->normalized_name != set->name)
570 g_free(set->normalized_name);
572 g_slice_free(PurpleLogSet, set);
575 GList *purple_log_get_system_logs(PurpleAccount *account)
577 GList *logs = NULL;
578 GSList *n;
579 for (n = loggers; n; n = n->next) {
580 PurpleLogLogger *logger = n->data;
581 if (!logger->list_syslog)
582 continue;
583 logs = g_list_concat(logger->list_syslog(account), logs);
586 return g_list_sort(logs, purple_log_compare);
589 /****************************************************************************
590 * LOG SUBSYSTEM ************************************************************
591 ****************************************************************************/
593 void *
594 purple_log_get_handle(void)
596 static int handle;
598 return &handle;
601 void purple_log_init(void)
603 void *handle = purple_log_get_handle();
605 purple_prefs_add_none("/purple/logging");
606 purple_prefs_add_bool("/purple/logging/log_ims", TRUE);
607 purple_prefs_add_bool("/purple/logging/log_chats", TRUE);
608 purple_prefs_add_bool("/purple/logging/log_system", FALSE);
610 purple_prefs_add_string("/purple/logging/format", "html");
612 html_logger = purple_log_logger_new("html", _("HTML"), 11,
613 NULL,
614 html_logger_write,
615 html_logger_finalize,
616 html_logger_list,
617 html_logger_read,
618 purple_log_common_sizer,
619 html_logger_total_size,
620 html_logger_list_syslog,
621 NULL,
622 purple_log_common_deleter,
623 purple_log_common_is_deletable);
624 purple_log_logger_add(html_logger);
626 txt_logger = purple_log_logger_new("txt", _("Plain text"), 11,
627 NULL,
628 txt_logger_write,
629 txt_logger_finalize,
630 txt_logger_list,
631 txt_logger_read,
632 purple_log_common_sizer,
633 txt_logger_total_size,
634 txt_logger_list_syslog,
635 NULL,
636 purple_log_common_deleter,
637 purple_log_common_is_deletable);
638 purple_log_logger_add(txt_logger);
640 old_logger = purple_log_logger_new("old", _("Old flat format"), 9,
641 NULL,
642 NULL,
643 old_logger_finalize,
644 old_logger_list,
645 old_logger_read,
646 old_logger_size,
647 old_logger_total_size,
648 NULL,
649 old_logger_get_log_sets);
650 purple_log_logger_add(old_logger);
652 purple_signal_register(handle, "log-timestamp",
653 purple_marshal_POINTER__POINTER_POINTER_BOOLEAN,
654 G_TYPE_STRING, 3,
655 PURPLE_TYPE_LOG,
656 G_TYPE_OBJECT,
657 G_TYPE_BOOLEAN);
659 purple_prefs_connect_callback(NULL, "/purple/logging/format",
660 logger_pref_cb, NULL);
661 purple_prefs_trigger_callback("/purple/logging/format");
663 logsize_users = g_hash_table_new_full((GHashFunc)_purple_logsize_user_hash,
664 (GEqualFunc)_purple_logsize_user_equal,
665 (GDestroyNotify)_purple_logsize_user_free_key, NULL);
666 logsize_users_decayed = g_hash_table_new_full((GHashFunc)_purple_logsize_user_hash,
667 (GEqualFunc)_purple_logsize_user_equal,
668 (GDestroyNotify)_purple_logsize_user_free_key, NULL);
671 void
672 purple_log_uninit(void)
674 purple_signals_unregister_by_instance(purple_log_get_handle());
676 purple_log_logger_remove(html_logger);
677 purple_log_logger_free(html_logger);
678 html_logger = NULL;
680 purple_log_logger_remove(txt_logger);
681 purple_log_logger_free(txt_logger);
682 txt_logger = NULL;
684 purple_log_logger_remove(old_logger);
685 purple_log_logger_free(old_logger);
686 old_logger = NULL;
688 g_hash_table_destroy(logsize_users);
689 g_hash_table_destroy(logsize_users_decayed);
692 static PurpleLog *
693 purple_log_copy(PurpleLog *log)
695 PurpleLog *log_copy;
697 g_return_val_if_fail(log != NULL, NULL);
699 log_copy = g_new(PurpleLog, 1);
700 *log_copy = *log;
702 return log_copy;
705 GType
706 purple_log_get_type(void)
708 static GType type = 0;
710 if (type == 0) {
711 type = g_boxed_type_register_static("PurpleLog",
712 (GBoxedCopyFunc)purple_log_copy,
713 (GBoxedFreeFunc)g_free);
716 return type;
719 /****************************************************************************
720 * LOGGERS ******************************************************************
721 ****************************************************************************/
723 static char *log_get_timestamp(PurpleLog *log, GDateTime *when)
725 gboolean show_date;
726 char *date;
727 GDateTime *dt;
729 dt = g_date_time_new_now_utc();
730 show_date = (log->type == PURPLE_LOG_SYSTEM) || (g_date_time_difference(dt, when) > 20L * G_TIME_SPAN_MINUTE);
731 g_date_time_unref(dt);
733 date = purple_signal_emit_return_1(purple_log_get_handle(),
734 "log-timestamp",
735 log, when, show_date);
736 if (date != NULL)
737 return date;
739 dt = g_date_time_to_local(when);
740 if (show_date)
741 date = g_date_time_format(dt, _("%x %X"));
742 else
743 date = g_date_time_format(dt, "%X");
744 g_date_time_unref(dt);
746 return date;
749 /* NOTE: This can return msg (which you may or may not want to g_free())
750 * NOTE: or a newly allocated string which you MUST g_free().
751 * TODO: XXX: does it really works?
753 static char *
754 convert_image_tags(const PurpleLog *log, const char *msg)
756 const char *tmp;
757 const char *start;
758 const char *end;
759 GData *attributes;
760 GString *newmsg = NULL;
762 tmp = msg;
764 while (purple_markup_find_tag("img", tmp, &start, &end, &attributes)) {
765 int imgid = 0;
766 char *idstr = NULL;
768 if (newmsg == NULL)
769 newmsg = g_string_new("");
771 /* copy any text before the img tag */
772 if (tmp < start)
773 g_string_append_len(newmsg, tmp, start - tmp);
775 if ((idstr = g_datalist_get_data(&attributes, "id")) != NULL)
776 imgid = atoi(idstr);
778 if (imgid != 0)
780 FILE *image_file;
781 char *dir;
782 PurpleImage *image;
783 gconstpointer image_data;
784 const gchar *new_filename = NULL;
785 char *path = NULL;
786 size_t image_byte_count;
788 image = purple_image_store_get(imgid);
789 if (image == NULL)
791 /* This should never happen. */
792 /* This *does* happen for failed Direct-IMs -DAA */
793 g_string_free(newmsg, TRUE);
794 g_return_val_if_reached((char *)msg);
797 image_data = purple_image_get_data(image);
798 image_byte_count = purple_image_get_data_size(image);
799 dir = purple_log_get_log_dir(log->type, log->name, log->account);
800 new_filename = purple_image_generate_filename(image);
802 path = g_build_filename(dir, new_filename, NULL);
804 /* Only save unique files. */
805 if (!g_file_test(path, G_FILE_TEST_EXISTS))
807 if ((image_file = g_fopen(path, "wb")) != NULL)
809 if (!fwrite(image_data, image_byte_count, 1, image_file))
811 purple_debug_error("log", "Error writing %s: %s\n",
812 path, g_strerror(errno));
813 fclose(image_file);
815 /* Attempt to not leave half-written files around. */
816 if (g_unlink(path)) {
817 purple_debug_error("log", "Error deleting partial "
818 "file %s: %s\n", path, g_strerror(errno));
821 else
823 purple_debug_info("log", "Wrote image file: %s\n", path);
824 fclose(image_file);
827 else
829 purple_debug_error("log", "Unable to create file %s: %s\n",
830 path, g_strerror(errno));
834 /* Write the new image tag */
835 g_string_append_printf(newmsg, "<img src=\"%s\">", new_filename);
836 g_free(path);
837 g_free(dir);
840 /* Continue from the end of the tag */
841 tmp = end + 1;
844 if (newmsg == NULL)
846 /* No images were found to change. */
847 return (char *)msg;
850 /* Append any remaining message data */
851 g_string_append(newmsg, tmp);
853 return g_string_free(newmsg, FALSE);
856 void purple_log_common_writer(PurpleLog *log, const char *ext)
858 PurpleLogCommonLoggerData *data = log->logger_data;
860 if (data == NULL)
862 /* This log is new */
863 char *dir;
864 GDateTime *dt;
865 const char *tz;
866 gchar *date;
867 char *filename;
868 char *path;
870 dir = purple_log_get_log_dir(log->type, log->name, log->account);
871 if (dir == NULL)
872 return;
874 purple_build_dir (dir, S_IRUSR | S_IWUSR | S_IXUSR);
876 dt = g_date_time_to_local(log->time);
877 tz = purple_escape_filename(g_date_time_get_timezone_abbreviation(dt));
878 date = g_date_time_format(dt, "%Y-%m-%d.%H%M%S%z");
879 g_date_time_unref(dt);
881 filename = g_strdup_printf("%s%s%s", date, tz, ext ? ext : "");
883 path = g_build_filename(dir, filename, NULL);
884 g_free(dir);
885 g_free(date);
886 g_free(filename);
888 log->logger_data = data = g_slice_new0(PurpleLogCommonLoggerData);
890 data->file = g_fopen(path, "a");
891 if (data->file == NULL)
893 purple_debug(PURPLE_DEBUG_ERROR, "log",
894 "Could not create log file %s\n", path);
896 if (log->conv != NULL)
897 purple_conversation_write_system_message(log->conv,
898 _("Logging of this conversation failed."),
899 PURPLE_MESSAGE_ERROR);
901 g_free(path);
902 return;
904 g_free(path);
908 GList *purple_log_common_lister(PurpleLogType type, const char *name, PurpleAccount *account, const char *ext, PurpleLogLogger *logger)
910 GDir *dir;
911 GList *list = NULL;
912 const char *filename;
913 char *path;
915 if(!account)
916 return NULL;
918 path = purple_log_get_log_dir(type, name, account);
919 if (path == NULL)
920 return NULL;
922 if (!(dir = g_dir_open(path, 0, NULL)))
924 g_free(path);
925 return NULL;
928 while ((filename = g_dir_read_name(dir)))
930 if (purple_str_has_suffix(filename, ext) &&
931 strlen(filename) >= (17 + strlen(ext)))
933 PurpleLog *log;
934 PurpleLogCommonLoggerData *data;
935 GDateTime *stamp = purple_str_to_date_time(purple_unescape_filename(filename), FALSE);
937 log = purple_log_new(type, name, account, NULL, stamp);
938 log->logger = logger;
939 log->logger_data = data = g_slice_new0(PurpleLogCommonLoggerData);
941 data->path = g_build_filename(path, filename, NULL);
942 list = g_list_prepend(list, log);
944 g_date_time_unref(stamp);
947 g_dir_close(dir);
948 g_free(path);
949 return list;
952 int purple_log_common_total_sizer(PurpleLogType type, const char *name, PurpleAccount *account, const char *ext)
954 GDir *dir;
955 int size = 0;
956 const char *filename;
957 char *path;
959 if(!account)
960 return 0;
962 path = purple_log_get_log_dir(type, name, account);
963 if (path == NULL)
964 return 0;
966 if (!(dir = g_dir_open(path, 0, NULL)))
968 g_free(path);
969 return 0;
972 while ((filename = g_dir_read_name(dir)))
974 if (purple_str_has_suffix(filename, ext) &&
975 strlen(filename) >= (17 + strlen(ext)))
977 char *tmp = g_build_filename(path, filename, NULL);
978 GStatBuf st;
979 if (g_stat(tmp, &st))
981 purple_debug_error("log", "Error stating log file: %s\n", tmp);
982 g_free(tmp);
983 continue;
985 g_free(tmp);
986 size += st.st_size;
989 g_dir_close(dir);
990 g_free(path);
991 return size;
994 int purple_log_common_sizer(PurpleLog *log)
996 GStatBuf st;
997 PurpleLogCommonLoggerData *data = log->logger_data;
999 g_return_val_if_fail(data != NULL, 0);
1001 if (!data->path || g_stat(data->path, &st))
1002 st.st_size = 0;
1004 return st.st_size;
1007 /* This will build log sets for all loggers that use the common logger
1008 * functions because they use the same directory structure. */
1009 static void log_get_log_sets_common(GHashTable *sets)
1011 gchar *log_path = g_build_filename(purple_data_dir(), "logs", NULL);
1012 GDir *log_dir = g_dir_open(log_path, 0, NULL);
1013 const gchar *protocol;
1015 if (log_dir == NULL) {
1016 g_free(log_path);
1017 return;
1020 while ((protocol = g_dir_read_name(log_dir)) != NULL) {
1021 gchar *protocol_path = g_build_filename(log_path, protocol, NULL);
1022 GDir *protocol_dir;
1023 const gchar *username;
1024 gchar *protocol_unescaped;
1025 GList *account_iter;
1026 GList *accounts = NULL;
1028 if ((protocol_dir = g_dir_open(protocol_path, 0, NULL)) == NULL) {
1029 g_free(protocol_path);
1030 continue;
1033 /* Using g_strdup() to cover the one-in-a-million chance that a
1034 * protocol's list_icon function uses purple_unescape_filename(). */
1035 protocol_unescaped = g_strdup(purple_unescape_filename(protocol));
1037 /* Find all the accounts for protocol. */
1038 for (account_iter = purple_accounts_get_all() ; account_iter != NULL ; account_iter = account_iter->next) {
1039 PurpleProtocol *protocol;
1041 protocol = purple_protocols_find(purple_account_get_protocol_id((PurpleAccount *)account_iter->data));
1042 if (!protocol)
1043 continue;
1045 if (purple_strequal(protocol_unescaped, purple_protocol_class_list_icon(protocol, (PurpleAccount *)account_iter->data, NULL)))
1046 accounts = g_list_prepend(accounts, account_iter->data);
1048 g_free(protocol_unescaped);
1050 while ((username = g_dir_read_name(protocol_dir)) != NULL) {
1051 gchar *username_path = g_build_filename(protocol_path, username, NULL);
1052 GDir *username_dir;
1053 const gchar *username_unescaped;
1054 PurpleAccount *account = NULL;
1055 gchar *name;
1057 if ((username_dir = g_dir_open(username_path, 0, NULL)) == NULL) {
1058 g_free(username_path);
1059 continue;
1062 /* Find the account for username in the list of accounts for protocol. */
1063 username_unescaped = purple_unescape_filename(username);
1064 for (account_iter = g_list_first(accounts) ; account_iter != NULL ; account_iter = account_iter->next) {
1065 if (purple_strequal(purple_account_get_username((PurpleAccount *)account_iter->data), username_unescaped)) {
1066 account = account_iter->data;
1067 break;
1071 /* Don't worry about the cast, name will point to dynamically allocated memory shortly. */
1072 while ((name = (gchar *)g_dir_read_name(username_dir)) != NULL) {
1073 size_t len;
1074 PurpleLogSet *set;
1076 /* IMPORTANT: Always initialize all members of PurpleLogSet */
1077 set = g_slice_new(PurpleLogSet);
1079 /* Unescape the filename. */
1080 name = g_strdup(purple_unescape_filename(name));
1082 /* Get the (possibly new) length of name. */
1083 len = strlen(name);
1085 set->type = PURPLE_LOG_IM;
1086 set->name = name;
1087 set->account = account;
1088 /* set->buddy is always set below */
1089 set->normalized_name = g_strdup(purple_normalize(account, name));
1091 /* Check for .chat or .system at the end of the name to determine the type. */
1092 if (len >= 7) {
1093 gchar *tmp = &name[len - 7];
1094 if (purple_strequal(tmp, ".system")) {
1095 set->type = PURPLE_LOG_SYSTEM;
1096 *tmp = '\0';
1099 if (len > 5) {
1100 gchar *tmp = &name[len - 5];
1101 if (purple_strequal(tmp, ".chat")) {
1102 set->type = PURPLE_LOG_CHAT;
1103 *tmp = '\0';
1107 /* Determine if this (account, name) combination exists as a buddy. */
1108 if (account != NULL && *name != '\0')
1109 set->buddy = (purple_blist_find_buddy(account, name) != NULL);
1110 else
1111 set->buddy = FALSE;
1113 log_add_log_set_to_hash(sets, set);
1115 g_free(username_path);
1116 g_dir_close(username_dir);
1118 g_free(protocol_path);
1119 g_list_free(accounts);
1120 g_dir_close(protocol_dir);
1122 g_free(log_path);
1123 g_dir_close(log_dir);
1126 gboolean purple_log_common_deleter(PurpleLog *log)
1128 PurpleLogCommonLoggerData *data;
1129 int ret;
1131 g_return_val_if_fail(log != NULL, FALSE);
1133 data = log->logger_data;
1134 if (data == NULL)
1135 return FALSE;
1137 if (data->path == NULL)
1138 return FALSE;
1140 ret = g_unlink(data->path);
1141 if (ret == 0)
1142 return TRUE;
1143 else if (ret == -1)
1145 purple_debug_error("log", "Failed to delete: %s - %s\n", data->path, g_strerror(errno));
1147 else
1149 /* I'm not sure that g_unlink() will ever return
1150 * something other than 0 or -1. -- rlaager */
1151 purple_debug_error("log", "Failed to delete: %s\n", data->path);
1154 return FALSE;
1157 gboolean purple_log_common_is_deletable(PurpleLog *log)
1159 PurpleLogCommonLoggerData *data;
1160 #ifndef _WIN32
1161 gchar *dirname;
1162 #endif
1164 g_return_val_if_fail(log != NULL, FALSE);
1166 data = log->logger_data;
1167 if (data == NULL)
1168 return FALSE;
1170 if (data->path == NULL)
1171 return FALSE;
1173 #ifndef _WIN32
1174 dirname = g_path_get_dirname(data->path);
1175 if (g_access(dirname, W_OK) == 0)
1177 g_free(dirname);
1178 return TRUE;
1180 purple_debug_info("log", "access(%s) failed: %s\n", dirname, g_strerror(errno));
1181 g_free(dirname);
1182 #else
1183 /* Unless and until someone writes equivalent win32 code,
1184 * we'll assume the file is deletable. */
1185 return TRUE;
1186 #endif
1188 return FALSE;
1191 static char *process_txt_log(char *txt, char *to_free)
1193 char *tmp;
1195 /* The to_free argument allows us to save a
1196 * g_strdup() in some cases. */
1198 if (to_free == NULL)
1199 to_free = txt;
1201 /* g_markup_escape_text requires valid UTF-8 */
1202 if (!g_utf8_validate(txt, -1, NULL))
1204 tmp = purple_utf8_salvage(txt);
1205 g_free(to_free);
1206 to_free = txt = tmp;
1209 tmp = g_markup_escape_text(txt, -1);
1210 g_free(to_free);
1211 txt = purple_markup_linkify(tmp);
1212 g_free(tmp);
1214 return txt;
1217 /****************************
1218 ** HTML LOGGER *************
1219 ****************************/
1221 static gsize html_logger_write(PurpleLog *log, PurpleMessageFlags type,
1222 const char *from, GDateTime *time, const char *message)
1224 char *msg_fixed;
1225 char *image_corrected_msg;
1226 char *date;
1227 char *header;
1228 char *escaped_from;
1229 PurpleProtocol *protocol =
1230 purple_protocols_find(purple_account_get_protocol_id(log->account));
1231 PurpleLogCommonLoggerData *data = log->logger_data;
1232 gsize written = 0;
1234 if(!data) {
1235 const char *proto = purple_protocol_class_list_icon(protocol, log->account, NULL);
1236 GDateTime *dt;
1237 gchar *date;
1238 purple_log_common_writer(log, ".html");
1240 data = log->logger_data;
1242 /* if we can't write to the file, give up before we hurt ourselves */
1243 if (!data || !data->file) {
1244 return 0;
1247 dt = g_date_time_to_local(log->time);
1248 date = g_date_time_format(dt, "%c");
1249 g_date_time_unref(dt);
1251 written += fprintf(data->file, "<html><head>");
1252 written += fprintf(data->file, "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
1253 written += fprintf(data->file, "<title>");
1254 if (log->type == PURPLE_LOG_SYSTEM)
1255 header = g_strdup_printf("System log for account %s (%s) connected at %s",
1256 purple_account_get_username(log->account), proto, date);
1257 else
1258 header = g_strdup_printf("Conversation with %s at %s on %s (%s)",
1259 log->name, date, purple_account_get_username(log->account), proto);
1261 written += fprintf(data->file, "%s", header);
1262 written += fprintf(data->file, "</title></head><body>");
1263 written += fprintf(data->file, "<h3>%s</h3>\n", header);
1264 g_free(date);
1265 g_free(header);
1268 /* if we can't write to the file, give up before we hurt ourselves */
1269 if(!data->file)
1270 return 0;
1272 escaped_from = g_markup_escape_text(from != NULL ? from : "<NULL>",
1273 -1);
1275 image_corrected_msg = convert_image_tags(log, message);
1276 purple_markup_html_to_xhtml(image_corrected_msg, &msg_fixed, NULL);
1278 /* Yes, this breaks encapsulation. But it's a static function and
1279 * this saves a needless strdup(). */
1280 if (image_corrected_msg != message)
1281 g_free(image_corrected_msg);
1283 date = log_get_timestamp(log, time);
1285 if(log->type == PURPLE_LOG_SYSTEM){
1286 written += fprintf(data->file, "---- %s @ %s ----<br/>\n", msg_fixed, date);
1287 } else {
1288 if (type & PURPLE_MESSAGE_SYSTEM)
1289 written += fprintf(data->file, "<font size=\"2\">(%s)</font><b> %s</b><br/>\n", date, msg_fixed);
1290 else if (type & PURPLE_MESSAGE_RAW)
1291 written += fprintf(data->file, "<font size=\"2\">(%s)</font> %s<br/>\n", date, msg_fixed);
1292 else if (type & PURPLE_MESSAGE_ERROR)
1293 written += fprintf(data->file, "<font color=\"#FF0000\"><font size=\"2\">(%s)</font><b> %s</b></font><br/>\n", date, msg_fixed);
1294 else if (type & PURPLE_MESSAGE_AUTO_RESP) {
1295 if (type & PURPLE_MESSAGE_SEND)
1296 written += fprintf(data->file, _("<font color=\"#16569E\"><font size=\"2\">(%s)</font> <b>%s &lt;AUTO-REPLY&gt;:</b></font> %s<br/>\n"), date, escaped_from, msg_fixed);
1297 else if (type & PURPLE_MESSAGE_RECV)
1298 written += fprintf(data->file, _("<font color=\"#A82F2F\"><font size=\"2\">(%s)</font> <b>%s &lt;AUTO-REPLY&gt;:</b></font> %s<br/>\n"), date, escaped_from, msg_fixed);
1299 } else if (type & PURPLE_MESSAGE_RECV) {
1300 if(purple_message_meify(msg_fixed, -1))
1301 written += fprintf(data->file, "<font color=\"#062585\"><font size=\"2\">(%s)</font> <b>***%s</b></font> %s<br/>\n",
1302 date, escaped_from, msg_fixed);
1303 else
1304 written += fprintf(data->file, "<font color=\"#A82F2F\"><font size=\"2\">(%s)</font> <b>%s:</b></font> %s<br/>\n",
1305 date, escaped_from, msg_fixed);
1306 } else if (type & PURPLE_MESSAGE_SEND) {
1307 if(purple_message_meify(msg_fixed, -1))
1308 written += fprintf(data->file, "<font color=\"#062585\"><font size=\"2\">(%s)</font> <b>***%s</b></font> %s<br/>\n",
1309 date, escaped_from, msg_fixed);
1310 else
1311 written += fprintf(data->file, "<font color=\"#16569E\"><font size=\"2\">(%s)</font> <b>%s:</b></font> %s<br/>\n",
1312 date, escaped_from, msg_fixed);
1313 } else {
1314 purple_debug_error("log", "Unhandled message type.\n");
1315 written += fprintf(data->file, "<font size=\"2\">(%s)</font><b> %s:</b></font> %s<br/>\n",
1316 date, escaped_from, msg_fixed);
1319 g_free(date);
1320 g_free(msg_fixed);
1321 g_free(escaped_from);
1322 fflush(data->file);
1324 return written;
1327 static void html_logger_finalize(PurpleLog *log)
1329 PurpleLogCommonLoggerData *data = log->logger_data;
1330 if (data) {
1331 if(data->file) {
1332 fprintf(data->file, "</body></html>\n");
1333 fclose(data->file);
1335 g_free(data->path);
1337 g_slice_free(PurpleLogCommonLoggerData, data);
1341 static GList *html_logger_list(PurpleLogType type, const char *sn, PurpleAccount *account)
1343 return purple_log_common_lister(type, sn, account, ".html", html_logger);
1346 static GList *html_logger_list_syslog(PurpleAccount *account)
1348 return purple_log_common_lister(PURPLE_LOG_SYSTEM, ".system", account, ".html", html_logger);
1351 static char *html_logger_read(PurpleLog *log, PurpleLogReadFlags *flags)
1353 char *read;
1354 PurpleLogCommonLoggerData *data = log->logger_data;
1355 *flags = PURPLE_LOG_READ_NO_NEWLINE;
1356 if (!data || !data->path)
1357 return g_strdup(_("<font color=\"red\"><b>Unable to find log path!</b></font>"));
1358 if (g_file_get_contents(data->path, &read, NULL, NULL)) {
1359 char *minus_header = strchr(read, '\n');
1361 if (!minus_header)
1362 return read;
1364 minus_header = g_strdup(minus_header + 1);
1365 g_free(read);
1367 return minus_header;
1369 return g_strdup_printf(_("<font color=\"red\"><b>Could not read file: %s</b></font>"), data->path);
1372 static int html_logger_total_size(PurpleLogType type, const char *name, PurpleAccount *account)
1374 return purple_log_common_total_sizer(type, name, account, ".html");
1378 /****************************
1379 ** PLAIN TEXT LOGGER *******
1380 ****************************/
1382 static gsize txt_logger_write(PurpleLog *log, PurpleMessageFlags type,
1383 const char *from, GDateTime *time, const char *message)
1385 char *date;
1386 PurpleProtocol *protocol =
1387 purple_protocols_find(purple_account_get_protocol_id(log->account));
1388 PurpleLogCommonLoggerData *data = log->logger_data;
1389 char *stripped = NULL;
1391 gsize written = 0;
1393 if (data == NULL) {
1394 /* This log is new. We could use the loggers 'new' function, but
1395 * creating a new file there would result in empty files in the case
1396 * that you open a convo with someone, but don't say anything.
1398 const char *proto = purple_protocol_class_list_icon(protocol, log->account, NULL);
1399 GDateTime *dt;
1400 gchar *date;
1401 purple_log_common_writer(log, ".txt");
1403 data = log->logger_data;
1405 /* if we can't write to the file, give up before we hurt ourselves */
1406 if(!data || !data->file)
1407 return 0;
1409 dt = g_date_time_to_local(log->time);
1410 date = g_date_time_format(dt, "%c");
1411 if (log->type == PURPLE_LOG_SYSTEM)
1412 written += fprintf(data->file, "System log for account %s (%s) connected at %s\n",
1413 purple_account_get_username(log->account), proto,
1414 date);
1415 else
1416 written += fprintf(data->file, "Conversation with %s at %s on %s (%s)\n",
1417 log->name, date,
1418 purple_account_get_username(log->account), proto);
1419 g_free(date);
1420 g_date_time_unref(dt);
1423 /* if we can't write to the file, give up before we hurt ourselves */
1424 if(!data->file)
1425 return 0;
1427 stripped = purple_markup_strip_html(message);
1428 date = log_get_timestamp(log, time);
1430 if(log->type == PURPLE_LOG_SYSTEM){
1431 written += fprintf(data->file, "---- %s @ %s ----\n", stripped, date);
1432 } else {
1433 if (type & PURPLE_MESSAGE_SEND ||
1434 type & PURPLE_MESSAGE_RECV) {
1435 if (type & PURPLE_MESSAGE_AUTO_RESP) {
1436 written += fprintf(data->file, _("(%s) %s <AUTO-REPLY>: %s\n"), date,
1437 from, stripped);
1438 } else {
1439 if(purple_message_meify(stripped, -1))
1440 written += fprintf(data->file, "(%s) ***%s %s\n", date, from,
1441 stripped);
1442 else
1443 written += fprintf(data->file, "(%s) %s: %s\n", date, from,
1444 stripped);
1446 } else if (type & PURPLE_MESSAGE_SYSTEM ||
1447 type & PURPLE_MESSAGE_ERROR ||
1448 type & PURPLE_MESSAGE_RAW)
1449 written += fprintf(data->file, "(%s) %s\n", date, stripped);
1450 else if (type & PURPLE_MESSAGE_NO_LOG) {
1451 /* This shouldn't happen */
1452 g_free(stripped);
1453 return written;
1454 } else
1455 written += fprintf(data->file, "(%s) %s%s %s\n", date, from ? from : "",
1456 from ? ":" : "", stripped);
1458 g_free(date);
1459 g_free(stripped);
1460 fflush(data->file);
1462 return written;
1465 static void txt_logger_finalize(PurpleLog *log)
1467 PurpleLogCommonLoggerData *data = log->logger_data;
1468 if (data) {
1469 if(data->file)
1470 fclose(data->file);
1471 g_free(data->path);
1473 g_slice_free(PurpleLogCommonLoggerData, data);
1477 static GList *txt_logger_list(PurpleLogType type, const char *sn, PurpleAccount *account)
1479 return purple_log_common_lister(type, sn, account, ".txt", txt_logger);
1482 static GList *txt_logger_list_syslog(PurpleAccount *account)
1484 return purple_log_common_lister(PURPLE_LOG_SYSTEM, ".system", account, ".txt", txt_logger);
1487 static char *txt_logger_read(PurpleLog *log, PurpleLogReadFlags *flags)
1489 char *read, *minus_header;
1490 PurpleLogCommonLoggerData *data = log->logger_data;
1491 *flags = 0;
1492 if (!data || !data->path)
1493 return g_strdup(_("<font color=\"red\"><b>Unable to find log path!</b></font>"));
1494 if (g_file_get_contents(data->path, &read, NULL, NULL)) {
1495 minus_header = strchr(read, '\n');
1497 if (minus_header)
1498 return process_txt_log(minus_header + 1, read);
1499 else
1500 return process_txt_log(read, NULL);
1502 return g_strdup_printf(_("<font color=\"red\"><b>Could not read file: %s</b></font>"), data->path);
1505 static int txt_logger_total_size(PurpleLogType type, const char *name, PurpleAccount *account)
1507 return purple_log_common_total_sizer(type, name, account, ".txt");
1511 /****************
1512 * OLD LOGGER ***
1513 ****************/
1515 /* The old logger doesn't write logs, only reads them. This is to include
1516 * old logs in the log viewer transparently.
1519 struct old_logger_data {
1520 PurpleStringref *pathref;
1521 int offset;
1522 int length;
1525 static GList *old_logger_list(PurpleLogType type, const char *sn, PurpleAccount *account)
1527 char *logfile = g_strdup_printf("%s.log", purple_normalize(account, sn));
1528 char *pathstr = g_build_filename(purple_data_dir(), "logs", logfile, NULL);
1529 PurpleStringref *pathref = purple_stringref_new(pathstr);
1530 GStatBuf st;
1531 time_t log_last_modified;
1532 FILE *index;
1533 FILE *file;
1534 int file_fd, index_fd;
1535 char *index_tmp;
1536 char buf[BUF_LONG];
1537 gint year, month, day, hour, minute, second;
1538 char month_str[4];
1539 struct old_logger_data *data = NULL;
1540 int logfound = 0;
1541 int lastoff = 0;
1542 int newlen;
1543 GDateTime *lasttime = NULL;
1545 PurpleLog *log = NULL;
1546 GList *list = NULL;
1548 g_free(logfile);
1550 file_fd = g_open(purple_stringref_value(pathref), 0, O_RDONLY);
1551 if (file_fd == -1 || (file = fdopen(file_fd, "rb")) == NULL) {
1552 purple_debug_error("log",
1553 "Failed to open log file \"%s\" for reading: %s\n",
1554 purple_stringref_value(pathref), g_strerror(errno));
1555 purple_stringref_unref(pathref);
1556 g_free(pathstr);
1557 return NULL;
1559 if (_purple_fstat(file_fd, &st) == -1) {
1560 purple_stringref_unref(pathref);
1561 g_free(pathstr);
1562 fclose(file);
1563 return NULL;
1564 } else
1565 log_last_modified = st.st_mtime;
1567 /* Change the .log extension to .idx */
1568 strcpy(pathstr + strlen(pathstr) - 3, "idx");
1570 index_fd = g_open(pathstr, 0, O_RDONLY);
1571 if (index_fd != -1) {
1572 if (_purple_fstat(index_fd, &st) != 0) {
1573 close(index_fd);
1574 index_fd = -1;
1578 if (index_fd != -1) {
1579 if (st.st_mtime < log_last_modified)
1581 purple_debug_warning("log", "Index \"%s\" exists, but is older than the log.\n", pathstr);
1582 close(index_fd);
1584 else
1586 /* The index file exists and is at least as new as the log, so open it. */
1587 if (!(index = fdopen(index_fd, "rb"))) {
1588 purple_debug_error("log", "Failed to open index file \"%s\" for reading: %s\n",
1589 pathstr, g_strerror(errno));
1591 /* Fall through so that we'll parse the log file. */
1592 } else {
1593 purple_debug_info("log", "Using index: %s\n", pathstr);
1594 g_free(pathstr);
1595 while (fgets(buf, BUF_LONG, index))
1597 unsigned long idx_time;
1598 if (sscanf(buf, "%d\t%d\t%lu", &lastoff, &newlen, &idx_time) == 3)
1600 log = purple_log_new(PURPLE_LOG_IM, sn, account, NULL, NULL);
1601 log->logger = old_logger;
1602 log->time = g_date_time_new_from_unix_local(idx_time);
1604 /* IMPORTANT: Always set all members of struct old_logger_data */
1605 data = g_slice_new(struct old_logger_data);
1607 data->pathref = purple_stringref_ref(pathref);
1608 data->offset = lastoff;
1609 data->length = newlen;
1611 log->logger_data = data;
1612 list = g_list_prepend(list, log);
1615 fclose(index);
1616 purple_stringref_unref(pathref);
1618 fclose(file);
1619 return list;
1624 index_tmp = g_strdup_printf("%s.XXXXXX", pathstr);
1625 if ((index_fd = g_mkstemp(index_tmp)) == -1) {
1626 purple_debug_error("log", "Failed to open index temp file: %s\n",
1627 g_strerror(errno));
1628 g_free(pathstr);
1629 g_free(index_tmp);
1630 index = NULL;
1631 } else {
1632 if ((index = fdopen(index_fd, "wb")) == NULL)
1634 purple_debug_error("log", "Failed to fdopen() index temp file: %s\n",
1635 g_strerror(errno));
1636 close(index_fd);
1637 if (index_tmp != NULL)
1639 g_unlink(index_tmp);
1640 g_free(index_tmp);
1642 g_free(pathstr);
1646 while (fgets(buf, BUF_LONG, file)) {
1647 if (strstr(buf, "---- New C") != NULL) {
1648 int length;
1649 int offset;
1650 char convostart[32];
1651 char *temp = strchr(buf, '@');
1653 if (temp == NULL || strlen(temp) < 2)
1654 continue;
1656 temp++;
1657 length = strcspn(temp, "-");
1658 if (length > 31) length = 31;
1660 offset = ftell(file);
1662 if (logfound) {
1663 newlen = offset - lastoff - length;
1664 if(strstr(buf, "----</H3><BR>")) {
1665 newlen -=
1666 sizeof("<HR><BR><H3 Align=Center> ---- New Conversation @ ") +
1667 sizeof("----</H3><BR>") - 2;
1668 } else {
1669 newlen -=
1670 sizeof("---- New Conversation @ ") + sizeof("----") - 2;
1673 if(strchr(buf, '\r'))
1674 newlen--;
1676 if (newlen != 0) {
1677 log = purple_log_new(PURPLE_LOG_IM, sn, account, NULL, lasttime);
1678 log->logger = old_logger;
1680 /* IMPORTANT: Always set all members of struct old_logger_data */
1681 data = g_slice_new(struct old_logger_data);
1683 data->pathref = purple_stringref_ref(pathref);
1684 data->offset = lastoff;
1685 data->length = newlen;
1687 log->logger_data = data;
1688 list = g_list_prepend(list, log);
1690 if (index != NULL) {
1691 fprintf(index, "%d\t%d\t%" G_GINT64_FORMAT "\n",
1692 data->offset, data->length,
1693 g_date_time_to_unix(log->time));
1698 logfound = 1;
1699 lastoff = offset;
1701 g_snprintf(convostart, length, "%s", temp);
1702 year = month = day = hour = minute = second = 0;
1703 if (sscanf(convostart, "%*s %3s %d %d:%d:%d %d", month_str,
1704 &day, &hour, &minute, &second, &year) != 6)
1706 purple_debug_warning("log", "invalid date format\n");
1708 /* Ugly hack, in case current locale is not English */
1709 if (purple_strequal(month_str, "Jan")) {
1710 month = 1;
1711 } else if (purple_strequal(month_str, "Feb")) {
1712 month = 2;
1713 } else if (purple_strequal(month_str, "Mar")) {
1714 month = 3;
1715 } else if (purple_strequal(month_str, "Apr")) {
1716 month = 4;
1717 } else if (purple_strequal(month_str, "May")) {
1718 month = 5;
1719 } else if (purple_strequal(month_str, "Jun")) {
1720 month = 6;
1721 } else if (purple_strequal(month_str, "Jul")) {
1722 month = 7;
1723 } else if (purple_strequal(month_str, "Aug")) {
1724 month = 8;
1725 } else if (purple_strequal(month_str, "Sep")) {
1726 month = 9;
1727 } else if (purple_strequal(month_str, "Oct")) {
1728 month = 10;
1729 } else if (purple_strequal(month_str, "Nov")) {
1730 month = 11;
1731 } else if (purple_strequal(month_str, "Dec")) {
1732 month = 12;
1734 if (lasttime)
1735 g_date_time_unref(lasttime);
1736 lasttime = g_date_time_new_local(year, month, day,
1737 hour, minute, second);
1741 if (logfound) {
1742 if ((newlen = ftell(file) - lastoff) != 0) {
1743 log = purple_log_new(PURPLE_LOG_IM, sn, account, NULL, lasttime);
1744 log->logger = old_logger;
1746 /* IMPORTANT: Always set all members of struct old_logger_data */
1747 data = g_slice_new(struct old_logger_data);
1749 data->pathref = purple_stringref_ref(pathref);
1750 data->offset = lastoff;
1751 data->length = newlen;
1753 log->logger_data = data;
1754 list = g_list_prepend(list, log);
1756 if (index != NULL) {
1757 fprintf(index, "%d\t%d\t%" G_GINT64_FORMAT "\n", data->offset,
1758 data->length, g_date_time_to_unix(log->time));
1763 if (lasttime)
1764 g_date_time_unref(lasttime);
1765 purple_stringref_unref(pathref);
1766 fclose(file);
1767 if (index != NULL)
1769 fclose(index);
1771 if (index_tmp == NULL)
1773 g_free(pathstr);
1774 g_return_val_if_reached(list);
1777 if (g_rename(index_tmp, pathstr))
1779 purple_debug_warning("log", "Failed to rename index temp file \"%s\" to \"%s\": %s\n",
1780 index_tmp, pathstr, g_strerror(errno));
1781 g_unlink(index_tmp);
1783 else
1784 purple_debug_info("log", "Built index: %s\n", pathstr);
1786 g_free(index_tmp);
1787 g_free(pathstr);
1789 return list;
1792 static int old_logger_total_size(PurpleLogType type, const char *name, PurpleAccount *account)
1794 char *logfile = g_strdup_printf("%s.log", purple_normalize(account, name));
1795 char *pathstr = g_build_filename(purple_data_dir(), "logs", logfile, NULL);
1796 int size;
1797 GStatBuf st;
1799 if (g_stat(pathstr, &st))
1800 size = 0;
1801 else
1802 size = st.st_size;
1804 g_free(logfile);
1805 g_free(pathstr);
1807 return size;
1810 static char * old_logger_read (PurpleLog *log, PurpleLogReadFlags *flags)
1812 size_t result;
1813 struct old_logger_data *data = log->logger_data;
1814 const char *path = purple_stringref_value(data->pathref);
1815 FILE *file = g_fopen(path, "rb");
1816 char *read;
1818 g_return_val_if_fail(file, g_strdup(""));
1819 read = g_malloc(data->length + 1);
1821 if (fseek(file, data->offset, SEEK_SET) != 0)
1822 result = 0;
1823 else
1824 result = fread(read, data->length, 1, file);
1825 if (result != 1)
1826 purple_debug_error("log", "Unable to read from log file: %s\n", path);
1827 fclose(file);
1828 read[data->length] = '\0';
1829 *flags = 0;
1830 if (strstr(read, "<BR>"))
1832 *flags |= PURPLE_LOG_READ_NO_NEWLINE;
1833 return read;
1836 return process_txt_log(read, NULL);
1839 static int old_logger_size (PurpleLog *log)
1841 struct old_logger_data *data = log->logger_data;
1842 return data ? data->length : 0;
1845 static void old_logger_get_log_sets(PurpleLogSetCallback cb, GHashTable *sets)
1847 char *log_path = g_build_filename(purple_data_dir(), "logs", NULL);
1848 GDir *log_dir = g_dir_open(log_path, 0, NULL);
1849 gchar *name;
1850 PurpleBlistNode *gnode, *cnode, *bnode;
1852 g_free(log_path);
1853 if (log_dir == NULL)
1854 return;
1856 /* Don't worry about the cast, name will be filled with a dynamically allocated data shortly. */
1857 while ((name = (gchar *)g_dir_read_name(log_dir)) != NULL) {
1858 size_t len;
1859 gchar *ext;
1860 PurpleLogSet *set;
1861 gboolean found = FALSE;
1863 /* Unescape the filename. */
1864 name = g_strdup(purple_unescape_filename(name));
1866 /* Get the (possibly new) length of name. */
1867 len = strlen(name);
1869 if (len < 5) {
1870 g_free(name);
1871 continue;
1874 /* Make sure we're dealing with a log file. */
1875 ext = &name[len - 4];
1876 if (!purple_strequal(ext, ".log")) {
1877 g_free(name);
1878 continue;
1881 /* IMPORTANT: Always set all members of PurpleLogSet */
1882 set = g_slice_new(PurpleLogSet);
1884 /* Chat for .chat at the end of the name to determine the type. */
1885 *ext = '\0';
1886 set->type = PURPLE_LOG_IM;
1887 if (len > 9) {
1888 char *tmp = &name[len - 9];
1889 if (purple_strequal(tmp, ".chat")) {
1890 set->type = PURPLE_LOG_CHAT;
1891 *tmp = '\0';
1895 set->name = set->normalized_name = name;
1897 /* Search the buddy list to find the account and to determine if this is a buddy. */
1898 for (gnode = purple_blist_get_default_root();
1899 !found && gnode != NULL;
1900 gnode = purple_blist_node_get_sibling_next(gnode)) {
1901 if (!PURPLE_IS_GROUP(gnode))
1902 continue;
1904 for (cnode = purple_blist_node_get_first_child(gnode);
1905 !found && cnode != NULL;
1906 cnode = purple_blist_node_get_sibling_next(cnode))
1908 if (!PURPLE_IS_CONTACT(cnode))
1909 continue;
1911 for (bnode = purple_blist_node_get_first_child(cnode);
1912 !found && bnode != NULL;
1913 bnode = purple_blist_node_get_sibling_next(bnode))
1915 PurpleBuddy *buddy = (PurpleBuddy *)bnode;
1917 if (purple_strequal(purple_buddy_get_name(buddy), name)) {
1918 set->account = purple_buddy_get_account(buddy);
1919 set->buddy = TRUE;
1920 found = TRUE;
1926 if (!found)
1928 set->account = NULL;
1929 set->buddy = FALSE;
1932 cb(sets, set);
1934 g_dir_close(log_dir);
1937 static void old_logger_finalize(PurpleLog *log)
1939 struct old_logger_data *data = log->logger_data;
1940 purple_stringref_unref(data->pathref);
1941 g_slice_free(struct old_logger_data, data);