1 /* Purple is the legal property of its developers, whose names are too numerous
2 * to list here. Please refer to the COPYRIGHT file distributed with this
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
21 #include "conversation.h"
24 #include "glibcompat.h"
30 #include <json-glib/json-glib.h>
32 static char *custom_user_dir
= NULL
;
33 static char *user_dir
= NULL
;
34 static gchar
*cache_dir
= NULL
;
35 static gchar
*config_dir
= NULL
;
36 static gchar
*data_dir
= NULL
;
38 static JsonNode
*escape_js_node
= NULL
;
39 static JsonGenerator
*escape_js_gen
= NULL
;
42 purple_util_init(void)
44 escape_js_node
= json_node_new(JSON_NODE_VALUE
);
45 escape_js_gen
= json_generator_new();
46 json_node_set_boolean(escape_js_node
, FALSE
);
50 purple_util_uninit(void)
52 /* Free these so we don't have leaks at shutdown. */
54 g_free(custom_user_dir
);
55 custom_user_dir
= NULL
;
69 json_node_free(escape_js_node
);
70 escape_js_node
= NULL
;
72 g_object_unref(escape_js_gen
);
76 /**************************************************************************
78 **************************************************************************/
80 purple_base16_encode(const guchar
*data
, gsize len
)
85 g_return_val_if_fail(data
!= NULL
, NULL
);
86 g_return_val_if_fail(len
> 0, NULL
);
88 ascii
= g_malloc(len
* 2 + 1);
90 for (i
= 0; i
< len
; i
++)
91 g_snprintf(&ascii
[i
* 2], 3, "%02x", data
[i
] & 0xFF);
97 purple_base16_decode(const char *str
, gsize
*ret_len
)
99 gsize len
, i
, accumulator
= 0;
102 g_return_val_if_fail(str
!= NULL
, NULL
);
106 g_return_val_if_fail(*str
, 0);
107 g_return_val_if_fail(len
% 2 == 0, 0);
109 data
= g_malloc(len
/ 2);
111 for (i
= 0; i
< len
; i
++)
119 accumulator
|= str
[i
] - 48;
122 switch(tolower(str
[i
]))
124 case 'a': accumulator
|= 10; break;
125 case 'b': accumulator
|= 11; break;
126 case 'c': accumulator
|= 12; break;
127 case 'd': accumulator
|= 13; break;
128 case 'e': accumulator
|= 14; break;
129 case 'f': accumulator
|= 15; break;
134 data
[(i
- 1) / 2] = accumulator
;
144 purple_base16_encode_chunked(const guchar
*data
, gsize len
)
149 g_return_val_if_fail(data
!= NULL
, NULL
);
150 g_return_val_if_fail(len
> 0, NULL
);
152 /* For each byte of input, we need 2 bytes for the hex representation
153 * and 1 for the colon.
154 * The final colon will be replaced by a terminating NULL
156 ascii
= g_malloc(len
* 3 + 1);
158 for (i
= 0; i
< len
; i
++)
159 g_snprintf(&ascii
[i
* 3], 4, "%02x:", data
[i
] & 0xFF);
161 /* Replace the final colon with NULL */
162 ascii
[len
* 3 - 1] = 0;
167 /**************************************************************************
168 * Date/Time Functions
169 **************************************************************************/
172 purple_utf8_strftime(const char *format
, const struct tm
*tm
)
174 static char buf
[128];
178 g_return_val_if_fail(format
!= NULL
, NULL
);
182 dt
= g_date_time_new_now_local();
184 dt
= g_date_time_new_local(tm
->tm_year
+ 1900, tm
->tm_mon
+ 1,
185 tm
->tm_mday
, tm
->tm_hour
,
186 tm
->tm_min
, tm
->tm_sec
);
189 utf8
= g_date_time_format(dt
, format
);
190 g_date_time_unref(dt
);
193 purple_debug_error("util",
194 "purple_utf8_strftime(): Formatting failed\n");
198 g_strlcpy(buf
, utf8
, sizeof(buf
));
204 purple_date_format_short(const struct tm
*tm
)
206 return purple_utf8_strftime("%x", tm
);
210 purple_date_format_long(const struct tm
*tm
)
213 * This string determines how some dates are displayed. The default
214 * string "%x %X" shows the date then the time. Translators can
215 * change this to "%X %x" if they want the time to be shown first,
216 * followed by the date.
218 return purple_utf8_strftime(_("%x %X"), tm
);
222 purple_date_format_full(const struct tm
*tm
)
224 return purple_utf8_strftime("%c", tm
);
228 purple_time_format(const struct tm
*tm
)
230 return purple_utf8_strftime("%X", tm
);
234 purple_time_build(int year
, int month
, int day
, int hour
, int min
, int sec
)
238 tm
.tm_year
= year
- 1900;
239 tm
.tm_mon
= month
- 1;
243 tm
.tm_sec
= sec
>= 0 ? sec
: time(NULL
) % 60;
248 /* originally taken from GLib trunk 1-6-11 */
249 /* originally licensed as LGPL 2+ */
251 mktime_utc(struct tm
*tm
)
256 static const gint days_before
[] =
258 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
263 if (tm
->tm_mon
< 0 || tm
->tm_mon
> 11)
266 retval
= (tm
->tm_year
- 70) * 365;
267 retval
+= (tm
->tm_year
- 68) / 4;
268 retval
+= days_before
[tm
->tm_mon
] + tm
->tm_mday
- 1;
270 if (tm
->tm_year
% 4 == 0 && tm
->tm_mon
< 2)
273 retval
= ((((retval
* 24) + tm
->tm_hour
) * 60) + tm
->tm_min
) * 60 + tm
->tm_sec
;
275 retval
= timegm (tm
);
276 #endif /* !HAVE_TIMEGM */
282 purple_str_to_time(const char *timestamp
, gboolean utc
,
283 struct tm
*tm
, long *tz_off
, const char **rest
)
288 long tzoff
= PURPLE_NO_TZ_OFF
;
290 gboolean mktime_with_utc
= FALSE
;
295 g_return_val_if_fail(timestamp
!= NULL
, 0);
297 memset(&t
, 0, sizeof(struct tm
));
301 /* Strip leading whitespace */
302 while (g_ascii_isspace(*str
))
306 if (rest
!= NULL
&& *str
!= '\0')
312 if (!g_ascii_isdigit(*str
) && *str
!= '-' && *str
!= '+') {
313 if (rest
!= NULL
&& *str
!= '\0')
320 if (sscanf(str
, "%04d", &year
) && year
>= 1900) {
323 if (*str
== '-' || *str
== '/')
326 t
.tm_year
= year
- 1900;
330 if (!sscanf(str
, "%02d", &t
.tm_mon
)) {
331 if (rest
!= NULL
&& *str
!= '\0')
340 if (*str
== '-' || *str
== '/')
344 if (!sscanf(str
, "%02d", &t
.tm_mday
)) {
345 if (rest
!= NULL
&& *str
!= '\0')
353 /* Grab the year off the end if there's still stuff */
354 if (*str
== '/' || *str
== '-') {
355 /* But make sure we don't read the year twice */
357 if (rest
!= NULL
&& *str
!= '\0')
365 if (!sscanf(str
, "%04d", &t
.tm_year
)) {
366 if (rest
!= NULL
&& *str
!= '\0')
373 } else if (*str
== 'T' || *str
== '.') {
376 /* Continue grabbing the hours/minutes/seconds */
377 if ((sscanf(str
, "%02d:%02d:%02d", &t
.tm_hour
, &t
.tm_min
, &t
.tm_sec
) == 3 &&
379 (sscanf(str
, "%02d%02d%02d", &t
.tm_hour
, &t
.tm_min
, &t
.tm_sec
) == 3 &&
382 gint sign
, tzhrs
, tzmins
;
385 /* Cut off those pesky micro-seconds */
388 } while (*str
>= '0' && *str
<= '9');
391 sign
= (*str
== '+') ? 1 : -1;
393 /* Process the timezone */
394 if (*str
== '+' || *str
== '-') {
397 if (((sscanf(str
, "%02d:%02d", &tzhrs
, &tzmins
) == 2 && (str
+= 5)) ||
398 (sscanf(str
, "%02d%02d", &tzhrs
, &tzmins
) == 2 && (str
+= 4))))
400 mktime_with_utc
= TRUE
;
401 tzoff
= tzhrs
* 60 * 60 + tzmins
* 60;
404 } else if (*str
== 'Z') {
405 /* 'Z' = Zulu = UTC */
407 mktime_with_utc
= TRUE
;
411 if (!mktime_with_utc
)
413 /* No timezone specified. */
416 mktime_with_utc
= TRUE
;
426 if (rest
!= NULL
&& *str
!= '\0') {
427 /* Strip trailing whitespace */
428 while (g_ascii_isspace(*str
))
436 retval
= mktime_utc(&t
);
443 if (tzoff
!= PURPLE_NO_TZ_OFF
)
453 purple_str_to_date_time(const char *timestamp
, gboolean utc
)
462 gint microseconds
= 0;
464 GTimeZone
*tz
= NULL
;
467 g_return_val_if_fail(timestamp
!= NULL
, NULL
);
471 /* Strip leading whitespace */
472 while (g_ascii_isspace(*str
))
479 if (!g_ascii_isdigit(*str
) && *str
!= '-' && *str
!= '+') {
484 if (sscanf(str
, "%04d", &year
) && year
> 0) {
487 if (*str
== '-' || *str
== '/')
492 if (!sscanf(str
, "%02d", &month
)) {
498 if (*str
== '-' || *str
== '/')
502 if (!sscanf(str
, "%02d", &day
)) {
508 /* Grab the year off the end if there's still stuff */
509 if (*str
== '/' || *str
== '-') {
510 /* But make sure we don't read the year twice */
517 if (!sscanf(str
, "%04d", &year
)) {
520 } else if (*str
== 'T' || *str
== '.') {
523 /* Continue grabbing the hours/minutes/seconds */
524 if ((sscanf(str
, "%02d:%02d:%02d", &hour
, &minute
, &seconds
) == 3 &&
526 (sscanf(str
, "%02d%02d%02d", &hour
, &minute
, &seconds
) == 3 &&
531 if (sscanf(str
, "%d%n", µseconds
, &chars
) == 1) {
537 const gchar
*end
= str
;
538 if (*end
== '+' || *end
== '-') {
542 while (isdigit(*end
) || *end
== ':') {
547 /* Trim anything trailing a purely numeric time zone. */
548 gchar
*tzstr
= g_strndup(str
, end
- str
);
549 tz
= g_time_zone_new(tzstr
);
552 /* Just try whatever is there. */
553 tz
= g_time_zone_new(str
);
560 /* No timezone specified. */
562 tz
= g_time_zone_new_utc();
564 tz
= g_time_zone_new_local();
568 retval
= g_date_time_new(tz
, year
, month
, day
, hour
, minute
,
569 seconds
+ microseconds
* pow(10, -chars
));
570 g_time_zone_unref(tz
);
576 purple_uts35_to_str(const char *format
, size_t len
, struct tm
*tm
)
582 time_t now
= time(NULL
);
583 tm
= localtime(&now
);
586 string
= g_string_sized_new(len
);
590 while ((i
+ count
) < len
&& format
[i
] == format
[i
+count
])
598 } else if (count
== 4) {
600 } else if (count
>= 5) {
610 /* Two-digits only */
611 g_string_append(string
, purple_utf8_strftime("%y", tm
));
614 g_string_append_printf(string
, "%0*d",
620 /* Year (in "Week of Year" based calendars) */
623 /* Two-digits only */
633 /* Cyclic Year Name */
637 } else if (count
== 4) {
639 } else if (count
>= 5) {
650 } else if (count
== 3) {
652 } else if (count
>= 4) {
658 /* Stand-alone Quarter */
662 } else if (count
== 3) {
664 } else if (count
>= 4) {
674 g_string_append(string
, purple_utf8_strftime("%m", tm
));
675 } else if (count
== 3) {
677 g_string_append(string
, purple_utf8_strftime("%b", tm
));
678 } else if (count
== 4) {
680 g_string_append(string
, purple_utf8_strftime("%B", tm
));
681 } else if (count
>= 5) {
682 g_string_append_len(string
, purple_utf8_strftime("%b", tm
), 1);
687 /* Stand-alone Month */
691 g_string_append(string
, purple_utf8_strftime("%m", tm
));
692 } else if (count
== 3) {
694 g_string_append(string
, purple_utf8_strftime("%b", tm
));
695 } else if (count
== 4) {
697 g_string_append(string
, purple_utf8_strftime("%B", tm
));
698 } else if (count
>= 5) {
699 g_string_append_len(string
, purple_utf8_strftime("%b", tm
), 1);
711 g_string_append(string
, purple_utf8_strftime("%W", tm
));
712 count
= MIN(count
, 2);
723 g_string_append(string
, purple_utf8_strftime("%d", tm
));
724 count
= MIN(count
, 2);
729 g_string_append(string
, purple_utf8_strftime("%j", tm
));
730 count
= MIN(count
, 3);
733 /* Day of Year in Month */
738 /* Modified Julian Day */
747 g_string_append(string
, purple_utf8_strftime("%a", tm
));
748 } else if (count
== 4) {
750 g_string_append(string
, purple_utf8_strftime("%A", tm
));
751 } else if (count
>= 5) {
753 g_string_append_len(string
, purple_utf8_strftime("%a", tm
), 1);
758 /* Local Day of Week */
762 g_string_append(string
, purple_utf8_strftime("%u", tm
));
763 } else if (count
== 3) {
765 g_string_append(string
, purple_utf8_strftime("%a", tm
));
766 } else if (count
== 4) {
768 g_string_append(string
, purple_utf8_strftime("%A", tm
));
769 } else if (count
>= 5) {
771 g_string_append_len(string
, purple_utf8_strftime("%a", tm
), 1);
776 /* Stand-alone Local Day of Week */
780 g_string_append(string
, purple_utf8_strftime("%u", tm
));
782 } else if (count
== 3) {
784 g_string_append(string
, purple_utf8_strftime("%a", tm
));
785 } else if (count
== 4) {
787 g_string_append(string
, purple_utf8_strftime("%A", tm
));
788 } else if (count
>= 5) {
790 g_string_append_len(string
, purple_utf8_strftime("%a", tm
), 1);
798 g_string_append(string
, purple_utf8_strftime("%p", tm
));
806 g_string_append(string
, purple_utf8_strftime("%I", tm
));
807 } else if (count
>= 2) {
809 g_string_append(string
, purple_utf8_strftime("%I", tm
));
818 g_string_append(string
, purple_utf8_strftime("%H", tm
));
819 } else if (count
>= 2) {
821 g_string_append(string
, purple_utf8_strftime("%H", tm
));
830 } else if (count
>= 2) {
840 } else if (count
>= 2) {
846 /* Hour (hHkK by locale) */
853 g_string_append(string
, purple_utf8_strftime("%M", tm
));
854 count
= MIN(count
, 2);
860 g_string_append(string
, purple_utf8_strftime("%S", tm
));
861 count
= MIN(count
, 2);
864 /* Fractional Sub-second */
873 /* Time Zone (specific non-location format) */
877 } else if (count
>= 4) {
887 g_string_append(string
, purple_utf8_strftime("%z", tm
));
888 } else if (count
== 4) {
890 } else if (count
>= 5) {
892 g_string_append(string
, purple_utf8_strftime("%z", tm
));
897 /* Time Zone (generic non-location format) */
901 g_string_append(string
, purple_utf8_strftime("%Z", tm
));
903 } else if (count
>= 4) {
905 g_string_append(string
, purple_utf8_strftime("%Z", tm
));
915 } else if (count
>= 4) {
916 /* Generic Location Format) */
917 g_string_append(string
, purple_utf8_strftime("%Z", tm
));
924 g_string_append_len(string
, format
+ i
, count
);
931 return g_string_free(string
, FALSE
);
935 /**************************************************************************
937 **************************************************************************/
940 * This function is stolen from glib's gmarkup.c and modified to not
941 * replace ' with '
943 static void append_escaped_text(GString
*str
,
944 const gchar
*text
, gssize length
)
956 next
= g_utf8_next_char (p
);
961 g_string_append (str
, "&");
965 g_string_append (str
, "<");
969 g_string_append (str
, ">");
973 g_string_append (str
, """);
977 c
= g_utf8_get_char (p
);
978 if ((0x1 <= c
&& c
<= 0x8) ||
979 (0xb <= c
&& c
<= 0xc) ||
980 (0xe <= c
&& c
<= 0x1f) ||
981 (0x7f <= c
&& c
<= 0x84) ||
982 (0x86 <= c
&& c
<= 0x9f))
983 g_string_append_printf (str
, "&#x%x;", c
);
985 g_string_append_len (str
, p
, next
- p
);
993 /* This function is stolen from glib's gmarkup.c */
994 gchar
*purple_markup_escape_text(const gchar
*text
, gssize length
)
998 g_return_val_if_fail(text
!= NULL
, NULL
);
1001 length
= strlen(text
);
1003 /* prealloc at least as long as original text */
1004 str
= g_string_sized_new(length
);
1005 append_escaped_text(str
, text
, length
);
1007 return g_string_free(str
, FALSE
);
1011 purple_markup_unescape_entity(const char *text
, int *length
)
1016 if (!text
|| *text
!= '&')
1019 #define IS_ENTITY(s) (!g_ascii_strncasecmp(text, s, (len = sizeof(s) - 1)))
1021 if(IS_ENTITY("&"))
1023 else if(IS_ENTITY("<"))
1025 else if(IS_ENTITY(">"))
1027 else if(IS_ENTITY(" "))
1029 else if(IS_ENTITY("©"))
1030 pln
= "\302\251"; /* or use g_unichar_to_utf8(0xa9); */
1031 else if(IS_ENTITY("""))
1033 else if(IS_ENTITY("®"))
1034 pln
= "\302\256"; /* or use g_unichar_to_utf8(0xae); */
1035 else if(IS_ENTITY("'"))
1037 else if(text
[1] == '#' && (g_ascii_isxdigit(text
[2]) || text
[2] == 'x')) {
1039 const char *start
= text
+ 2;
1045 if (*start
== 'x') {
1050 pound
= g_ascii_strtoull(start
, &end
, base
);
1051 if (pound
== 0 || pound
> INT_MAX
|| *end
!= ';') {
1055 len
= (end
- text
) + 1;
1057 buflen
= g_unichar_to_utf8((gunichar
)pound
, buf
);
1070 purple_markup_get_css_property(const gchar
*style
,
1073 const gchar
*css_str
= style
;
1074 const gchar
*css_value_start
;
1075 const gchar
*css_value_end
;
1079 g_return_val_if_fail(opt
!= NULL
, NULL
);
1084 /* find the CSS property */
1087 /* skip whitespace characters */
1088 while (*css_str
&& g_ascii_isspace(*css_str
))
1090 if (!g_ascii_isalpha(*css_str
))
1092 if (g_ascii_strncasecmp(css_str
, opt
, strlen(opt
)))
1094 /* go to next css property positioned after the next ';' */
1095 while (*css_str
&& *css_str
!= '"' && *css_str
!= ';')
1105 /* find the CSS value position in the string */
1106 css_str
+= strlen(opt
);
1107 while (*css_str
&& g_ascii_isspace(*css_str
))
1109 if (*css_str
!= ':')
1112 while (*css_str
&& g_ascii_isspace(*css_str
))
1114 if (*css_str
== '\0' || *css_str
== '"' || *css_str
== ';')
1117 /* mark the CSS value */
1118 css_value_start
= css_str
;
1119 while (*css_str
&& *css_str
!= '"' && *css_str
!= ';')
1121 css_value_end
= css_str
- 1;
1123 /* Removes trailing whitespace */
1124 while (css_value_end
> css_value_start
&& g_ascii_isspace(*css_value_end
))
1127 tmp
= g_strndup(css_value_start
, css_value_end
- css_value_start
+ 1);
1128 ret
= purple_unescape_html(tmp
);
1134 gboolean
purple_markup_is_rtl(const char *html
)
1137 const gchar
*start
, *end
;
1138 gboolean res
= FALSE
;
1140 if (purple_markup_find_tag("span", html
, &start
, &end
, &attributes
))
1142 /* tmp is a member of attributes and is free with g_datalist_clear call */
1143 const char *tmp
= g_datalist_get_data(&attributes
, "dir");
1144 if (tmp
&& !g_ascii_strcasecmp(tmp
, "RTL"))
1148 tmp
= g_datalist_get_data(&attributes
, "style");
1151 char *tmp2
= purple_markup_get_css_property(tmp
, "direction");
1152 if (tmp2
&& !g_ascii_strcasecmp(tmp2
, "RTL"))
1158 g_datalist_clear(&attributes
);
1164 purple_markup_find_tag(const char *needle
, const char *haystack
,
1165 const char **start
, const char **end
, GData
**attributes
)
1168 const char *cur
= haystack
;
1170 gboolean found
= FALSE
;
1171 gboolean in_tag
= FALSE
;
1172 gboolean in_attr
= FALSE
;
1173 const char *in_quotes
= NULL
;
1176 g_return_val_if_fail( needle
!= NULL
, FALSE
);
1177 g_return_val_if_fail( *needle
!= '\0', FALSE
);
1178 g_return_val_if_fail( haystack
!= NULL
, FALSE
);
1179 g_return_val_if_fail( start
!= NULL
, FALSE
);
1180 g_return_val_if_fail( end
!= NULL
, FALSE
);
1181 g_return_val_if_fail(attributes
!= NULL
, FALSE
);
1183 needlelen
= strlen(needle
);
1184 g_datalist_init(&attribs
);
1186 while (*cur
&& !found
) {
1189 const char *close
= cur
;
1191 while (*close
&& *close
!= *in_quotes
)
1194 /* if we got the close quote, store the value and carry on from *
1195 * after it. if we ran to the end of the string, point to the NULL *
1196 * and we're outta here */
1198 /* only store a value if we have an attribute name */
1200 size_t len
= close
- cur
;
1201 char *val
= g_strndup(cur
, len
);
1203 g_datalist_set_data_full(&attribs
, name
, val
, g_free
);
1213 } else if (in_attr
) {
1214 const char *close
= cur
;
1216 while (*close
&& *close
!= '>' && *close
!= '"' &&
1217 *close
!= '\'' && *close
!= ' ' && *close
!= '=')
1220 /* if we got the equals, store the name of the attribute. if we got
1221 * the quote, save the attribute and go straight to quote mode.
1222 * otherwise the tag closed or we reached the end of the string,
1223 * so we can get outta here */
1231 size_t len
= close
- cur
;
1233 /* don't store a blank attribute name */
1236 name
= g_ascii_strdown(cur
, len
);
1254 /* swallow extra spaces inside tag */
1255 while (*cur
&& *cur
== ' ') cur
++;
1272 /* if we hit a < followed by the name of our tag... */
1273 if (*cur
== '<' && !g_ascii_strncasecmp(cur
+ 1, needle
, needlelen
)) {
1275 cur
= cur
+ needlelen
+ 1;
1277 /* if we're pointing at a space or a >, we found the right tag. if *
1278 * we're not, we've found a longer tag, so we need to skip to the *
1279 * >, but not being distracted by >s inside quotes. */
1280 if (*cur
== ' ' || *cur
== '>') {
1283 while (*cur
&& *cur
!= '"' && *cur
!= '\'' && *cur
!= '>') {
1286 while (*cur
&& *cur
!= '"')
1288 } else if (*cur
== '\'') {
1290 while (*cur
&& *cur
!= '\'')
1303 /* clean up any attribute name from a premature termination */
1307 *attributes
= attribs
;
1318 purple_markup_extract_info_field(const char *str
, int len
, PurpleNotifyUserInfo
*user_info
,
1319 const char *start_token
, int skip
,
1320 const char *end_token
, char check_value
,
1321 const char *no_value_token
,
1322 const char *display_name
, gboolean is_link
,
1323 const char *link_prefix
,
1324 PurpleInfoFieldFormatCallback format_cb
)
1328 g_return_val_if_fail(str
!= NULL
, FALSE
);
1329 g_return_val_if_fail(user_info
!= NULL
, FALSE
);
1330 g_return_val_if_fail(start_token
!= NULL
, FALSE
);
1331 g_return_val_if_fail(end_token
!= NULL
, FALSE
);
1332 g_return_val_if_fail(display_name
!= NULL
, FALSE
);
1334 p
= strstr(str
, start_token
);
1339 p
+= strlen(start_token
) + skip
;
1344 if (check_value
!= '\0' && *p
== check_value
)
1347 q
= strstr(p
, end_token
);
1349 /* Trim leading blanks */
1350 while (*p
!= '\n' && g_ascii_isspace(*p
)) {
1354 /* Trim trailing blanks */
1355 while (q
> p
&& g_ascii_isspace(*(q
- 1))) {
1359 /* Don't bother with null strings */
1363 if (q
!= NULL
&& (!no_value_token
||
1364 (no_value_token
&& strncmp(p
, no_value_token
,
1365 strlen(no_value_token
)))))
1367 GString
*dest
= g_string_new("");
1371 g_string_append(dest
, "<a href=\"");
1374 g_string_append(dest
, link_prefix
);
1376 if (format_cb
!= NULL
)
1378 char *reformatted
= format_cb(p
, q
- p
);
1379 g_string_append(dest
, reformatted
);
1380 g_free(reformatted
);
1383 g_string_append_len(dest
, p
, q
- p
);
1384 g_string_append(dest
, "\">");
1387 g_string_append(dest
, link_prefix
);
1389 g_string_append_len(dest
, p
, q
- p
);
1390 g_string_append(dest
, "</a>");
1394 if (format_cb
!= NULL
)
1396 char *reformatted
= format_cb(p
, q
- p
);
1397 g_string_append(dest
, reformatted
);
1398 g_free(reformatted
);
1401 g_string_append_len(dest
, p
, q
- p
);
1404 purple_notify_user_info_add_pair_html(user_info
, display_name
, dest
->str
);
1405 g_string_free(dest
, TRUE
);
1413 struct purple_parse_tag
{
1419 /* NOTE: Do not put `do {} while(0)` around this macro (as this is the method
1420 recommended in the GCC docs). It contains 'continue's that should
1421 affect the while-loop in purple_markup_html_to_xhtml and doing the
1422 above would break that.
1423 Also, remember to put braces in constructs that require them for
1424 multiple statements when using this macro. */
1425 #define ALLOW_TAG_ALT(x, y) if(!g_ascii_strncasecmp(c, "<" x " ", strlen("<" x " "))) { \
1426 const char *o = c + strlen("<" x); \
1427 const char *p = NULL, *q = NULL, *r = NULL; \
1428 /* o = iterating over full tag \
1429 * p = > (end of tag) \
1430 * q = start of quoted bit \
1431 * r = < inside tag \
1433 GString *innards = g_string_new(""); \
1435 if(!q && (*o == '\"' || *o == '\'') ) { \
1438 if(*o == *q) { /* end of quoted bit */ \
1439 char *unescaped = g_strndup(q+1, o-q-1); \
1440 char *escaped = g_markup_escape_text(unescaped, -1); \
1441 g_string_append_printf(innards, "%c%s%c", *q, escaped, *q); \
1442 g_free(unescaped); \
1445 } else if(*c == '\\') { \
1448 } else if(*o == '<') { \
1450 } else if(*o == '>') { \
1454 innards = g_string_append_c(innards, *o); \
1458 if(p && !r) { /* got an end of tag and no other < earlier */\
1459 if(*(p-1) != '/') { \
1460 struct purple_parse_tag *pt = g_new0(struct purple_parse_tag, 1); \
1463 tags = g_list_prepend(tags, pt); \
1466 xhtml = g_string_append(xhtml, "<" y); \
1467 xhtml = g_string_append(xhtml, innards->str); \
1468 xhtml = g_string_append_c(xhtml, '>'); \
1471 } else { /* got end of tag with earlier < *or* didn't get anything */ \
1473 xhtml = g_string_append(xhtml, "<"); \
1475 plain = g_string_append_c(plain, '<'); \
1478 g_string_free(innards, TRUE); \
1481 if(!g_ascii_strncasecmp(c, "<" x, strlen("<" x)) && \
1482 (*(c+strlen("<" x)) == '>' || \
1483 !g_ascii_strncasecmp(c+strlen("<" x), "/>", 2))) { \
1485 xhtml = g_string_append(xhtml, "<" y); \
1486 c += strlen("<" x); \
1488 struct purple_parse_tag *pt = g_new0(struct purple_parse_tag, 1); \
1491 tags = g_list_prepend(tags, pt); \
1493 xhtml = g_string_append_c(xhtml, '>'); \
1496 xhtml = g_string_append(xhtml, "/>");\
1498 c = strchr(c, '>') + 1; \
1501 /* Don't forget to check the note above for ALLOW_TAG_ALT. */
1502 #define ALLOW_TAG(x) ALLOW_TAG_ALT(x, x)
1504 purple_markup_html_to_xhtml(const char *html
, char **xhtml_out
,
1507 GString
*xhtml
= NULL
;
1508 GString
*plain
= NULL
;
1509 GString
*url
= NULL
;
1510 GString
*cdata
= NULL
;
1511 GList
*tags
= NULL
, *tag
;
1512 const char *c
= html
;
1515 #define CHECK_QUOTE(ptr) if (*(ptr) == '\'' || *(ptr) == '\"') \
1520 #define VALID_CHAR(ptr) (*(ptr) && *(ptr) != quote && (quote || (*(ptr) != ' ' && *(ptr) != '>')))
1522 g_return_if_fail(xhtml_out
!= NULL
|| plain_out
!= NULL
);
1525 xhtml
= g_string_new("");
1527 plain
= g_string_new("");
1531 if(*(c
+1) == '/') { /* closing tag */
1534 struct purple_parse_tag
*pt
= tag
->data
;
1535 if(!g_ascii_strncasecmp((c
+2), pt
->src_tag
, strlen(pt
->src_tag
)) && *(c
+strlen(pt
->src_tag
)+2) == '>') {
1536 c
+= strlen(pt
->src_tag
) + 3;
1543 struct purple_parse_tag
*pt
= tags
->data
;
1544 if(xhtml
&& !pt
->ignore
)
1545 g_string_append_printf(xhtml
, "</%s>", pt
->dest_tag
);
1546 if(plain
&& purple_strequal(pt
->src_tag
, "a")) {
1547 /* if this is a link, we have to add the url to the plaintext, too */
1549 (!g_string_equal(cdata
, url
) && (g_ascii_strncasecmp(url
->str
, "mailto:", 7) != 0 ||
1550 g_utf8_collate(url
->str
+ 7, cdata
->str
) != 0)))
1551 g_string_append_printf(plain
, " <%s>", g_strstrip(purple_unescape_html(url
->str
)));
1553 g_string_free(cdata
, TRUE
);
1560 tags
= g_list_remove(tags
, pt
);
1564 tags
= g_list_delete_link(tags
, tag
);
1566 /* a closing tag we weren't expecting...
1567 * we'll let it slide, if it's really a tag...if it's
1568 * just a </ we'll escape it properly */
1569 const char *end
= c
+2;
1570 while(*end
&& g_ascii_isalpha(*end
))
1576 xhtml
= g_string_append(xhtml
, "<");
1578 plain
= g_string_append_c(plain
, '<');
1582 } else { /* opening tag */
1583 ALLOW_TAG("blockquote");
1593 /* we only allow html to start the message */
1597 ALLOW_TAG_ALT("i", "em");
1598 ALLOW_TAG_ALT("italic", "em");
1608 /* we skip <HR> because it's not legal in XHTML-IM. However,
1609 * we still want to send something sensible, so we put a
1610 * linebreak in its place. <BR> also needs special handling
1611 * because putting a </BR> to close it would just be dumb. */
1612 if((!g_ascii_strncasecmp(c
, "<br", 3)
1613 || !g_ascii_strncasecmp(c
, "<hr", 3))
1614 && (*(c
+3) == '>' ||
1615 !g_ascii_strncasecmp(c
+3, "/>", 2) ||
1616 !g_ascii_strncasecmp(c
+3, " />", 3))) {
1617 c
= strchr(c
, '>') + 1;
1619 xhtml
= g_string_append(xhtml
, "<br/>");
1620 if(plain
&& *c
!= '\n')
1621 plain
= g_string_append_c(plain
, '\n');
1624 if(!g_ascii_strncasecmp(c
, "<b>", 3) || !g_ascii_strncasecmp(c
, "<bold>", strlen("<bold>")) || !g_ascii_strncasecmp(c
, "<strong>", strlen("<strong>"))) {
1625 struct purple_parse_tag
*pt
= g_new0(struct purple_parse_tag
, 1);
1628 else if (*(c
+2) == 'o')
1629 pt
->src_tag
= "bold";
1631 pt
->src_tag
= "strong";
1632 pt
->dest_tag
= "span";
1633 tags
= g_list_prepend(tags
, pt
);
1634 c
= strchr(c
, '>') + 1;
1636 xhtml
= g_string_append(xhtml
, "<span style='font-weight: bold;'>");
1639 if(!g_ascii_strncasecmp(c
, "<u>", 3) || !g_ascii_strncasecmp(c
, "<underline>", strlen("<underline>"))) {
1640 struct purple_parse_tag
*pt
= g_new0(struct purple_parse_tag
, 1);
1641 pt
->src_tag
= *(c
+2) == '>' ? "u" : "underline";
1642 pt
->dest_tag
= "span";
1643 tags
= g_list_prepend(tags
, pt
);
1644 c
= strchr(c
, '>') + 1;
1646 xhtml
= g_string_append(xhtml
, "<span style='text-decoration: underline;'>");
1649 if(!g_ascii_strncasecmp(c
, "<s>", 3) || !g_ascii_strncasecmp(c
, "<strike>", strlen("<strike>"))) {
1650 struct purple_parse_tag
*pt
= g_new0(struct purple_parse_tag
, 1);
1651 pt
->src_tag
= *(c
+2) == '>' ? "s" : "strike";
1652 pt
->dest_tag
= "span";
1653 tags
= g_list_prepend(tags
, pt
);
1654 c
= strchr(c
, '>') + 1;
1656 xhtml
= g_string_append(xhtml
, "<span style='text-decoration: line-through;'>");
1659 if(!g_ascii_strncasecmp(c
, "<sub>", 5)) {
1660 struct purple_parse_tag
*pt
= g_new0(struct purple_parse_tag
, 1);
1661 pt
->src_tag
= "sub";
1662 pt
->dest_tag
= "span";
1663 tags
= g_list_prepend(tags
, pt
);
1664 c
= strchr(c
, '>') + 1;
1666 xhtml
= g_string_append(xhtml
, "<span style='vertical-align:sub;'>");
1669 if(!g_ascii_strncasecmp(c
, "<sup>", 5)) {
1670 struct purple_parse_tag
*pt
= g_new0(struct purple_parse_tag
, 1);
1671 pt
->src_tag
= "sup";
1672 pt
->dest_tag
= "span";
1673 tags
= g_list_prepend(tags
, pt
);
1674 c
= strchr(c
, '>') + 1;
1676 xhtml
= g_string_append(xhtml
, "<span style='vertical-align:super;'>");
1679 if (!g_ascii_strncasecmp(c
, "<img", 4) && (*(c
+4) == '>' || *(c
+4) == ' ')) {
1680 const char *p
= c
+ 4;
1681 GString
*src
= NULL
, *alt
= NULL
;
1682 #define ESCAPE(from, to) \
1683 CHECK_QUOTE(from); \
1684 while (VALID_CHAR(from)) { \
1686 if ((*from == '&') && (purple_markup_unescape_entity(from, &len) == NULL)) \
1687 to = g_string_append(to, "&"); \
1688 else if (*from == '\'') \
1689 to = g_string_append(to, "'"); \
1691 to = g_string_append_c(to, *from); \
1695 while (*p
&& *p
!= '>') {
1696 if (!g_ascii_strncasecmp(p
, "src=", 4)) {
1697 const char *q
= p
+ 4;
1699 g_string_free(src
, TRUE
);
1700 src
= g_string_new("");
1703 } else if (!g_ascii_strncasecmp(p
, "alt=", 4)) {
1704 const char *q
= p
+ 4;
1706 g_string_free(alt
, TRUE
);
1707 alt
= g_string_new("");
1715 if ((c
= strchr(p
, '>')) != NULL
)
1719 /* src and alt are required! */
1721 g_string_append_printf(xhtml
, "<img src='%s' alt='%s' />", g_strstrip(src
->str
), alt
? alt
->str
: "");
1724 plain
= g_string_append(plain
, purple_unescape_html(alt
->str
));
1726 xhtml
= g_string_append(xhtml
, alt
->str
);
1727 g_string_free(alt
, TRUE
);
1729 g_string_free(src
, TRUE
);
1732 if (!g_ascii_strncasecmp(c
, "<a", 2) && (*(c
+2) == '>' || *(c
+2) == ' ')) {
1733 const char *p
= c
+ 2;
1734 struct purple_parse_tag
*pt
;
1735 while (*p
&& *p
!= '>') {
1736 if (!g_ascii_strncasecmp(p
, "href=", 5)) {
1737 const char *q
= p
+ 5;
1739 g_string_free(url
, TRUE
);
1740 url
= g_string_new("");
1742 g_string_free(cdata
, TRUE
);
1743 cdata
= g_string_new("");
1745 while (VALID_CHAR(q
)) {
1747 if ((*q
== '&') && (purple_markup_unescape_entity(q
, &len
) == NULL
))
1748 url
= g_string_append(url
, "&");
1750 url
= g_string_append(url
, """);
1752 url
= g_string_append_c(url
, *q
);
1760 if ((c
= strchr(p
, '>')) != NULL
)
1764 pt
= g_new0(struct purple_parse_tag
, 1);
1767 tags
= g_list_prepend(tags
, pt
);
1769 g_string_append_printf(xhtml
, "<a href=\"%s\">", url
? g_strstrip(url
->str
) : "");
1772 #define ESCAPE(from, to) \
1773 CHECK_QUOTE(from); \
1774 while (VALID_CHAR(from)) { \
1776 if ((*from == '&') && (purple_markup_unescape_entity(from, &len) == NULL)) \
1777 to = g_string_append(to, "&"); \
1778 else if (*from == '\'') \
1779 to = g_string_append_c(to, '\"'); \
1781 to = g_string_append_c(to, *from); \
1784 if(!g_ascii_strncasecmp(c
, "<font", 5) && (*(c
+5) == '>' || *(c
+5) == ' ')) {
1785 const char *p
= c
+ 5;
1786 GString
*style
= g_string_new("");
1787 struct purple_parse_tag
*pt
;
1788 while (*p
&& *p
!= '>') {
1789 if (!g_ascii_strncasecmp(p
, "back=", 5)) {
1790 const char *q
= p
+ 5;
1791 GString
*color
= g_string_new("");
1793 g_string_append_printf(style
, "background: %s; ", color
->str
);
1794 g_string_free(color
, TRUE
);
1796 } else if (!g_ascii_strncasecmp(p
, "color=", 6)) {
1797 const char *q
= p
+ 6;
1798 GString
*color
= g_string_new("");
1800 g_string_append_printf(style
, "color: %s; ", color
->str
);
1801 g_string_free(color
, TRUE
);
1803 } else if (!g_ascii_strncasecmp(p
, "face=", 5)) {
1804 const char *q
= p
+ 5;
1805 GString
*face
= g_string_new("");
1807 g_string_append_printf(style
, "font-family: %s; ", g_strstrip(face
->str
));
1808 g_string_free(face
, TRUE
);
1810 } else if (!g_ascii_strncasecmp(p
, "size=", 5)) {
1811 const char *q
= p
+ 5;
1813 const char *size
= "medium";
1840 g_string_append_printf(style
, "font-size: %s; ", size
);
1846 if ((c
= strchr(p
, '>')) != NULL
)
1850 pt
= g_new0(struct purple_parse_tag
, 1);
1851 pt
->src_tag
= "font";
1852 pt
->dest_tag
= "span";
1853 tags
= g_list_prepend(tags
, pt
);
1854 if(style
->len
&& xhtml
)
1855 g_string_append_printf(xhtml
, "<span style='%s'>", g_strstrip(style
->str
));
1858 g_string_free(style
, TRUE
);
1862 if (!g_ascii_strncasecmp(c
, "<body ", 6)) {
1863 const char *p
= c
+ 6;
1864 gboolean did_something
= FALSE
;
1865 while (*p
&& *p
!= '>') {
1866 if (!g_ascii_strncasecmp(p
, "bgcolor=", 8)) {
1867 const char *q
= p
+ 8;
1868 struct purple_parse_tag
*pt
= g_new0(struct purple_parse_tag
, 1);
1869 GString
*color
= g_string_new("");
1871 while (VALID_CHAR(q
)) {
1872 color
= g_string_append_c(color
, *q
);
1876 g_string_append_printf(xhtml
, "<span style='background: %s;'>", g_strstrip(color
->str
));
1877 g_string_free(color
, TRUE
);
1878 if ((c
= strchr(p
, '>')) != NULL
)
1882 pt
->src_tag
= "body";
1883 pt
->dest_tag
= "span";
1884 tags
= g_list_prepend(tags
, pt
);
1885 did_something
= TRUE
;
1890 if (did_something
) continue;
1892 /* this has to come after the special case for bgcolor */
1894 if(!g_ascii_strncasecmp(c
, "<!--", strlen("<!--"))) {
1895 char *p
= strstr(c
+ strlen("<!--"), "-->");
1898 xhtml
= g_string_append(xhtml
, "<!--");
1899 c
+= strlen("<!--");
1905 xhtml
= g_string_append(xhtml
, "<");
1907 plain
= g_string_append_c(plain
, '<');
1910 } else if(*c
== '&') {
1915 if ((pln
= purple_markup_unescape_entity(c
, &len
)) == NULL
) {
1917 g_snprintf(buf
, sizeof(buf
), "%c", *c
);
1921 xhtml
= g_string_append_len(xhtml
, c
, len
);
1923 plain
= g_string_append(plain
, pln
);
1925 cdata
= g_string_append_len(cdata
, c
, len
);
1929 xhtml
= g_string_append_c(xhtml
, *c
);
1931 plain
= g_string_append_c(plain
, *c
);
1933 cdata
= g_string_append_c(cdata
, *c
);
1938 for (tag
= tags
; tag
; tag
= tag
->next
) {
1939 struct purple_parse_tag
*pt
= tag
->data
;
1941 g_string_append_printf(xhtml
, "</%s>", pt
->dest_tag
);
1946 *xhtml_out
= g_string_free(xhtml
, FALSE
);
1948 *plain_out
= g_string_free(plain
, FALSE
);
1950 g_string_free(url
, TRUE
);
1952 g_string_free(cdata
, TRUE
);
1957 /* The following are probably reasonable changes:
1958 * - \n should be converted to a normal space
1959 * - in addition to <br>, <p> and <div> etc. should also be converted into \n
1960 * - We want to turn </td>#whitespace<td> sequences into a single tab
1961 * - We want to turn </tr>#whitespace<tr> sequences into a single \n
1962 * - <script>...</script> and <style>...</style> should be completely removed
1966 purple_markup_strip_html(const char *str
)
1968 int i
, j
, k
, entlen
;
1969 gboolean visible
= TRUE
;
1970 gboolean closing_td_p
= FALSE
;
1972 const gchar
*cdata_close_tag
= NULL
, *ent
;
1979 str2
= g_strdup(str
);
1981 for (i
= 0, j
= 0; str2
[i
]; i
++)
1985 if (cdata_close_tag
)
1987 /* Note: Don't even assume any other tag is a tag in CDATA */
1988 if (g_ascii_strncasecmp(str2
+ i
, cdata_close_tag
,
1989 strlen(cdata_close_tag
)) == 0)
1991 i
+= strlen(cdata_close_tag
) - 1;
1992 cdata_close_tag
= NULL
;
1996 else if (g_ascii_strncasecmp(str2
+ i
, "<td", 3) == 0 && closing_td_p
)
2001 else if (g_ascii_strncasecmp(str2
+ i
, "</td>", 5) == 0)
2003 closing_td_p
= TRUE
;
2008 closing_td_p
= FALSE
;
2014 if(g_ascii_isspace(str2
[k
]))
2018 /* Scan until we end the tag either implicitly (closed start
2019 * tag) or explicitly, using a sloppy method (i.e., < or >
2020 * inside quoted attributes will screw us up)
2022 while (str2
[k
] && str2
[k
] != '<' && str2
[k
] != '>')
2027 /* If we've got an <a> tag with an href, save the address
2028 * to print later. */
2029 if (g_ascii_strncasecmp(str2
+ i
, "<a", 2) == 0 &&
2030 g_ascii_isspace(str2
[i
+2]))
2032 int st
; /* start of href, inclusive [ */
2033 int end
; /* end of href, exclusive ) */
2035 /* Find start of href */
2036 for (st
= i
+ 3; st
< k
; st
++)
2038 if (g_ascii_strncasecmp(str2
+st
, "href=", 5) == 0)
2041 if (str2
[st
] == '"' || str2
[st
] == '\'')
2049 /* find end of address */
2050 for (end
= st
; end
< k
&& str2
[end
] != delim
; end
++)
2052 /* All the work is done in the loop construct above. */
2055 /* If there's an address, save it. If there was
2056 * already one saved, kill it. */
2061 tmp
= g_strndup(str2
+ st
, end
- st
);
2062 href
= purple_unescape_html(tmp
);
2068 /* Replace </a> with an ascii representation of the
2069 * address the link was pointing to. */
2070 else if (href
!= NULL
&& g_ascii_strncasecmp(str2
+ i
, "</a>", 4) == 0)
2072 size_t hrlen
= strlen(href
);
2074 /* Only insert the href if it's different from the CDATA. */
2075 if ((hrlen
!= (gsize
)(j
- href_st
) ||
2076 strncmp(str2
+ href_st
, href
, hrlen
)) &&
2077 (hrlen
!= (gsize
)(j
- href_st
+ 7) || /* 7 == strlen("http://") */
2078 strncmp(str2
+ href_st
, href
+ 7, hrlen
- 7)))
2082 memmove(str2
+ j
, href
, hrlen
);
2090 /* Check for tags which should be mapped to newline (but ignore some of
2091 * the tags at the beginning of the text) */
2092 else if ((j
&& (g_ascii_strncasecmp(str2
+ i
, "<p>", 3) == 0
2093 || g_ascii_strncasecmp(str2
+ i
, "<tr", 3) == 0
2094 || g_ascii_strncasecmp(str2
+ i
, "<hr", 3) == 0
2095 || g_ascii_strncasecmp(str2
+ i
, "<li", 3) == 0
2096 || g_ascii_strncasecmp(str2
+ i
, "<div", 4) == 0))
2097 || g_ascii_strncasecmp(str2
+ i
, "<br", 3) == 0
2098 || g_ascii_strncasecmp(str2
+ i
, "</table>", 8) == 0)
2102 /* Check for tags which begin CDATA and need to be closed */
2103 else if (g_ascii_strncasecmp(str2
+ i
, "<script", 7) == 0)
2105 cdata_close_tag
= "</script>";
2107 else if (g_ascii_strncasecmp(str2
+ i
, "<style", 6) == 0)
2109 cdata_close_tag
= "</style>";
2111 /* Update the index and continue checking after the tag */
2112 i
= (str2
[k
] == '<' || str2
[k
] == '\0')? k
- 1: k
;
2116 else if (cdata_close_tag
)
2120 else if (!g_ascii_isspace(str2
[i
]))
2125 if (str2
[i
] == '&' && (ent
= purple_markup_unescape_entity(str2
+ i
, &entlen
)) != NULL
)
2134 str2
[j
++] = g_ascii_isspace(str2
[i
])? ' ': str2
[i
];
2163 badentity(const char *c
)
2165 if (!g_ascii_strncasecmp(c
, "<", 4) ||
2166 !g_ascii_strncasecmp(c
, ">", 4) ||
2167 !g_ascii_strncasecmp(c
, """, 6)) {
2174 process_link(GString
*ret
,
2175 const char *start
, const char *c
,
2177 const char *urlprefix
,
2180 char *url_buf
, *tmpurlbuf
;
2184 if (!badchar(*t
) && !badentity(t
))
2187 if (t
- c
== matchlen
)
2190 if (*t
== ',' && *(t
+ 1) != ' ') {
2194 if (t
> start
&& *(t
- 1) == '.')
2196 if (t
> start
&& *(t
- 1) == ')' && inside_paren
> 0)
2199 url_buf
= g_strndup(c
, t
- c
);
2200 tmpurlbuf
= purple_unescape_html(url_buf
);
2201 g_string_append_printf(ret
, "<A HREF=\"%s%s\">%s</A>",
2203 tmpurlbuf
, url_buf
);
2213 purple_markup_linkify(const char *text
)
2215 const char *c
, *t
, *q
= NULL
;
2216 char *tmpurlbuf
, *url_buf
;
2218 gboolean inside_html
= FALSE
;
2219 int inside_paren
= 0;
2225 ret
= g_string_new("");
2230 if(*c
== '(' && !inside_html
) {
2232 ret
= g_string_append_c(ret
, *c
);
2238 inside_html
= FALSE
;
2239 } else if(!q
&& (*c
== '\"' || *c
== '\'')) {
2245 } else if(*c
== '<') {
2247 if (!g_ascii_strncasecmp(c
, "<A", 2)) {
2249 if (!g_ascii_strncasecmp(c
, "/A>", 3)) {
2250 inside_html
= FALSE
;
2253 ret
= g_string_append_c(ret
, *c
);
2259 } else if (!g_ascii_strncasecmp(c
, "http://", 7)) {
2260 c
= process_link(ret
, text
, c
, 7, "", inside_paren
);
2261 } else if (!g_ascii_strncasecmp(c
, "https://", 8)) {
2262 c
= process_link(ret
, text
, c
, 8, "", inside_paren
);
2263 } else if (!g_ascii_strncasecmp(c
, "ftp://", 6)) {
2264 c
= process_link(ret
, text
, c
, 6, "", inside_paren
);
2265 } else if (!g_ascii_strncasecmp(c
, "sftp://", 7)) {
2266 c
= process_link(ret
, text
, c
, 7, "", inside_paren
);
2267 } else if (!g_ascii_strncasecmp(c
, "file://", 7)) {
2268 c
= process_link(ret
, text
, c
, 7, "", inside_paren
);
2269 } else if (!g_ascii_strncasecmp(c
, "www.", 4) && c
[4] != '.' && (c
== text
|| badchar(c
[-1]) || badentity(c
-1))) {
2270 c
= process_link(ret
, text
, c
, 4, "http://", inside_paren
);
2271 } else if (!g_ascii_strncasecmp(c
, "ftp.", 4) && c
[4] != '.' && (c
== text
|| badchar(c
[-1]) || badentity(c
-1))) {
2272 c
= process_link(ret
, text
, c
, 4, "ftp://", inside_paren
);
2273 } else if (!g_ascii_strncasecmp(c
, "xmpp:", 5) && (c
== text
|| badchar(c
[-1]) || badentity(c
-1))) {
2274 c
= process_link(ret
, text
, c
, 5, "", inside_paren
);
2275 } else if (!g_ascii_strncasecmp(c
, "mailto:", 7)) {
2278 if (badchar(*t
) || badentity(t
)) {
2283 if (t
> text
&& *(t
- 1) == '.')
2285 if ((d
= strstr(c
+ 7, "?")) != NULL
&& d
< t
)
2286 url_buf
= g_strndup(c
+ 7, d
- c
- 7);
2288 url_buf
= g_strndup(c
+ 7, t
- c
- 7);
2289 if (!purple_email_is_valid(url_buf
)) {
2294 url_buf
= g_strndup(c
, t
- c
);
2295 tmpurlbuf
= purple_unescape_html(url_buf
);
2296 g_string_append_printf(ret
, "<A HREF=\"%s\">%s</A>",
2297 tmpurlbuf
, url_buf
);
2305 } else if (c
!= text
&& (*c
== '@')) {
2307 GString
*gurl_buf
= NULL
;
2308 const char illegal_chars
[] = "!@#$%^&*()[]{}/|\\<>\":;\r\n \0";
2310 if (strchr(illegal_chars
,*(c
- 1)) || strchr(illegal_chars
, *(c
+ 1)))
2314 gurl_buf
= g_string_new("");
2319 /* iterate backwards grabbing the local part of an email address */
2320 g
= g_utf8_get_char(t
);
2321 if (badchar(*t
) || (g
>= 127) || (*t
== '(') ||
2322 ((*t
== ';') && ((t
> (text
+2) && (!g_ascii_strncasecmp(t
- 3, "<", 4) ||
2323 !g_ascii_strncasecmp(t
- 3, ">", 4))) ||
2324 (t
> (text
+4) && (!g_ascii_strncasecmp(t
- 5, """, 6)))))) {
2325 /* local part will already be part of ret, strip it out */
2326 ret
= g_string_truncate(ret
, ret
->len
- (c
- t
));
2327 ret
= g_string_append_unichar(ret
, g
);
2330 g_string_prepend_unichar(gurl_buf
, g
);
2331 t
= g_utf8_find_prev_char(text
, t
);
2333 ret
= g_string_assign(ret
, "");
2339 t
= g_utf8_find_next_char(c
, NULL
);
2342 /* iterate forwards grabbing the domain part of an email address */
2343 g
= g_utf8_get_char(t
);
2344 if (badchar(*t
) || (g
>= 127) || (*t
== ')') || badentity(t
)) {
2347 url_buf
= g_string_free(gurl_buf
, FALSE
);
2349 /* strip off trailing periods */
2351 for (d
= url_buf
+ strlen(url_buf
) - 1; *d
== '.'; d
--, t
--)
2355 tmpurlbuf
= purple_unescape_html(url_buf
);
2356 if (purple_email_is_valid(tmpurlbuf
)) {
2357 g_string_append_printf(ret
, "<A HREF=\"mailto:%s\">%s</A>",
2358 tmpurlbuf
, url_buf
);
2360 g_string_append(ret
, url_buf
);
2368 g_string_append_unichar(gurl_buf
, g
);
2369 t
= g_utf8_find_next_char(t
, NULL
);
2374 if(*c
== ')' && !inside_html
) {
2376 ret
= g_string_append_c(ret
, *c
);
2383 ret
= g_string_append_c(ret
, *c
);
2387 return g_string_free(ret
, FALSE
);
2390 char *purple_unescape_text(const char *in
)
2398 ret
= g_string_new("");
2403 if ((ent
= purple_markup_unescape_entity(c
, &len
)) != NULL
) {
2404 g_string_append(ret
, ent
);
2407 g_string_append_c(ret
, *c
);
2412 return g_string_free(ret
, FALSE
);
2415 char *purple_unescape_html(const char *html
)
2418 const char *c
= html
;
2423 ret
= g_string_new("");
2428 if ((ent
= purple_markup_unescape_entity(c
, &len
)) != NULL
) {
2429 g_string_append(ret
, ent
);
2431 } else if (!strncmp(c
, "<br>", 4)) {
2432 g_string_append_c(ret
, '\n');
2435 g_string_append_c(ret
, *c
);
2440 return g_string_free(ret
, FALSE
);
2444 purple_markup_slice(const char *str
, guint x
, guint y
)
2449 gboolean appended
= FALSE
;
2453 g_return_val_if_fail(str
!= NULL
, NULL
);
2454 g_return_val_if_fail(x
<= y
, NULL
);
2457 return g_strdup("");
2459 ret
= g_string_new("");
2462 while (*str
&& (z
< y
)) {
2463 c
= g_utf8_get_char(str
);
2466 char *end
= strchr(str
, '>');
2469 g_string_free(ret
, TRUE
);
2470 while ((tag
= g_queue_pop_head(q
)))
2476 if (!g_ascii_strncasecmp(str
, "<img ", 5)) {
2477 z
+= strlen("[Image]");
2478 } else if (!g_ascii_strncasecmp(str
, "<br", 3)) {
2480 } else if (!g_ascii_strncasecmp(str
, "<hr>", 4)) {
2481 z
+= strlen("\n---\n");
2482 } else if (!g_ascii_strncasecmp(str
, "</", 2)) {
2486 tmp
= g_queue_pop_head(q
);
2490 /* push it unto the stack */
2493 tmp
= g_strndup(str
, end
- str
+ 1);
2494 g_queue_push_head(q
, tmp
);
2499 g_string_append_len(ret
, str
, end
- str
+ 1);
2503 } else if (c
== '&') {
2504 char *end
= strchr(str
, ';');
2506 g_string_free(ret
, TRUE
);
2507 while ((tag
= g_queue_pop_head(q
)))
2515 g_string_append_len(ret
, str
, end
- str
+ 1);
2520 if (z
== x
&& z
> 0 && !appended
) {
2525 g_string_append(ret
, tag
);
2532 g_string_append_unichar(ret
, c
);
2536 str
= g_utf8_next_char(str
);
2539 while ((tag
= g_queue_pop_head(q
))) {
2542 name
= purple_markup_get_tag_name(tag
);
2543 g_string_append_printf(ret
, "</%s>", name
);
2549 return g_string_free(ret
, FALSE
);
2553 purple_markup_get_tag_name(const char *tag
)
2556 g_return_val_if_fail(tag
!= NULL
, NULL
);
2557 g_return_val_if_fail(*tag
== '<', NULL
);
2559 for (i
= 1; tag
[i
]; i
++)
2560 if (tag
[i
] == '>' || tag
[i
] == ' ' || tag
[i
] == '/')
2563 return g_strndup(tag
+1, i
-1);
2566 /**************************************************************************
2567 * Path/Filename Functions
2568 **************************************************************************/
2570 purple_home_dir(void)
2573 return g_get_home_dir();
2575 return wpurple_home_dir();
2579 /* Returns the argument passed to -c IFF it was present, or ~/.purple. */
2581 purple_user_dir(void)
2583 if (custom_user_dir
!= NULL
)
2584 return custom_user_dir
;
2586 user_dir
= g_build_filename(purple_home_dir(), ".purple", NULL
);
2591 static const gchar
*
2592 purple_xdg_dir(gchar
**xdg_dir
, const gchar
*xdg_base_dir
, const gchar
*xdg_type
)
2595 if (!custom_user_dir
) {
2596 *xdg_dir
= g_build_filename(xdg_base_dir
, "purple", NULL
);
2598 *xdg_dir
= g_build_filename(custom_user_dir
, xdg_type
, NULL
);
2606 purple_cache_dir(void)
2608 return purple_xdg_dir(&cache_dir
, g_get_user_cache_dir(), "cache");
2612 purple_config_dir(void)
2614 return purple_xdg_dir(&config_dir
, g_get_user_config_dir(), "config");
2618 purple_data_dir(void)
2620 return purple_xdg_dir(&data_dir
, g_get_user_data_dir(), "data");
2624 purple_move_to_xdg_base_dir(const char *purple_xdg_dir
, char *path
)
2628 gboolean xdg_path_exists
;
2630 /* Create destination directory */
2631 mkdir_res
= purple_build_dir(purple_xdg_dir
, S_IRWXU
);
2632 if (mkdir_res
== -1) {
2633 purple_debug_error("util", "Error creating xdg directory %s: %s; failed migration\n",
2634 purple_xdg_dir
, g_strerror(errno
));
2638 xdg_path
= g_build_filename(purple_xdg_dir
, path
, NULL
);
2639 xdg_path_exists
= g_file_test(xdg_path
, G_FILE_TEST_EXISTS
);
2640 if (!xdg_path_exists
) {
2642 gboolean old_path_exists
;
2644 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
2645 old_path
= g_build_filename(purple_user_dir(), path
, NULL
);
2646 G_GNUC_END_IGNORE_DEPRECATIONS
2647 old_path_exists
= g_file_test(old_path
, G_FILE_TEST_EXISTS
);
2648 if (old_path_exists
) {
2651 rename_res
= g_rename(old_path
, xdg_path
);
2652 if (rename_res
== -1) {
2653 purple_debug_error("util", "Error renaming %s to %s; failed migration\n",
2654 old_path
, xdg_path
);
2670 void purple_util_set_user_dir(const char *dir
)
2672 g_free(custom_user_dir
);
2674 if (dir
!= NULL
&& *dir
)
2675 custom_user_dir
= g_strdup(dir
);
2677 custom_user_dir
= NULL
;
2680 int purple_build_dir(const char *path
, int mode
)
2682 return g_mkdir_with_parents(path
, mode
);
2686 purple_util_write_data_to_file_common(const char *dir
, const char *filename
, const char *data
, gssize size
)
2688 gchar
*filename_full
;
2689 gboolean ret
= FALSE
;
2691 g_return_val_if_fail(dir
!= NULL
, FALSE
);
2693 purple_debug_misc("util", "Writing file %s to directory %s",
2696 /* Ensure the directory exists */
2697 if (!g_file_test(dir
, G_FILE_TEST_IS_DIR
))
2699 if (g_mkdir(dir
, S_IRUSR
| S_IWUSR
| S_IXUSR
) == -1)
2701 purple_debug_error("util", "Error creating directory %s: %s\n",
2702 dir
, g_strerror(errno
));
2707 filename_full
= g_build_filename(dir
, filename
, NULL
);
2709 ret
= purple_util_write_data_to_file_absolute(filename_full
, data
, size
);
2711 g_free(filename_full
);
2716 purple_util_write_data_to_file(const char *filename
, const char *data
, gssize size
)
2718 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
2719 const char *user_dir
= purple_user_dir();
2720 G_GNUC_END_IGNORE_DEPRECATIONS
2721 gboolean ret
= purple_util_write_data_to_file_common(user_dir
, filename
, data
, size
);
2727 purple_util_write_data_to_cache_file(const char *filename
, const char *data
, gssize size
)
2729 const char *cache_dir
= purple_cache_dir();
2730 gboolean ret
= purple_util_write_data_to_file_common(cache_dir
, filename
, data
, size
);
2736 purple_util_write_data_to_config_file(const char *filename
, const char *data
, gssize size
)
2738 const char *config_dir
= purple_config_dir();
2739 gboolean ret
= purple_util_write_data_to_file_common(config_dir
, filename
, data
, size
);
2745 purple_util_write_data_to_data_file(const char *filename
, const char *data
, gssize size
)
2747 const char *data_dir
= purple_data_dir();
2748 gboolean ret
= purple_util_write_data_to_file_common(data_dir
, filename
, data
, size
);
2754 purple_util_write_data_to_file_absolute(const char *filename_full
, const char *data
, gssize size
)
2759 g_return_val_if_fail(size
>= -1, FALSE
);
2762 size
= strlen(data
);
2765 file
= g_file_new_for_path(filename_full
);
2767 if (!g_file_replace_contents(file
, data
, size
, NULL
, FALSE
,
2768 G_FILE_CREATE_PRIVATE
, NULL
, NULL
, &err
)) {
2769 purple_debug_error("util", "Error writing file: %s: %s\n",
2770 filename_full
, err
->message
);
2771 g_clear_error(&err
);
2772 g_object_unref(file
);
2776 g_object_unref(file
);
2781 purple_util_read_xml_from_file(const char *filename
, const char *description
)
2783 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
2784 return purple_xmlnode_from_file(purple_user_dir(), filename
, description
, "util");
2785 G_GNUC_END_IGNORE_DEPRECATIONS
2789 purple_util_read_xml_from_cache_file(const char *filename
, const char *description
)
2791 return purple_xmlnode_from_file(purple_cache_dir(), filename
, description
, "util");
2795 purple_util_read_xml_from_config_file(const char *filename
, const char *description
)
2797 return purple_xmlnode_from_file(purple_config_dir(), filename
, description
, "util");
2801 purple_util_read_xml_from_data_file(const char *filename
, const char *description
)
2803 return purple_xmlnode_from_file(purple_data_dir(), filename
, description
, "util");
2807 * Like mkstemp() but returns a file pointer, uses a pre-set template,
2808 * uses the semantics of tempnam() for the directory to use and allocates
2809 * the space for the filepath.
2811 * Caller is responsible for closing the file and removing it when done,
2812 * as well as freeing the space pointed-to by "path" with g_free().
2814 * Returns NULL on failure and cleans up after itself if so.
2816 static const char *purple_mkstemp_templ
= {"purpleXXXXXX"};
2819 purple_mkstemp(char **fpath
, gboolean binary
)
2821 const gchar
*tmpdir
;
2825 g_return_val_if_fail(fpath
!= NULL
, NULL
);
2827 if((tmpdir
= (gchar
*)g_get_tmp_dir()) != NULL
) {
2828 if((*fpath
= g_strdup_printf("%s" G_DIR_SEPARATOR_S
"%s", tmpdir
, purple_mkstemp_templ
)) != NULL
) {
2829 fd
= g_mkstemp(*fpath
);
2831 purple_debug(PURPLE_DEBUG_ERROR
, "purple_mkstemp",
2832 "Couldn't make \"%s\", error: %d\n",
2835 if((fp
= fdopen(fd
, "r+")) == NULL
) {
2837 purple_debug(PURPLE_DEBUG_ERROR
, "purple_mkstemp",
2838 "Couldn't fdopen(), error: %d\n", errno
);
2848 purple_debug(PURPLE_DEBUG_ERROR
, "purple_mkstemp",
2849 "g_get_tmp_dir() failed!\n");
2856 purple_program_is_valid(const char *program
)
2858 GError
*error
= NULL
;
2861 gboolean is_valid
= FALSE
;
2863 g_return_val_if_fail(program
!= NULL
, FALSE
);
2864 g_return_val_if_fail(*program
!= '\0', FALSE
);
2866 if (!g_shell_parse_argv(program
, NULL
, &argv
, &error
)) {
2867 purple_debug(PURPLE_DEBUG_ERROR
, "program_is_valid",
2868 "Could not parse program '%s': %s\n",
2869 program
, error
->message
);
2870 g_error_free(error
);
2878 progname
= g_find_program_in_path(argv
[0]);
2879 is_valid
= (progname
!= NULL
);
2881 if(purple_debug_is_verbose())
2882 purple_debug_info("program_is_valid", "Tested program %s. %s.\n", program
,
2883 is_valid
? "Valid" : "Invalid");
2893 purple_running_gnome(void)
2896 gchar
*tmp
= g_find_program_in_path("gvfs-open");
2899 tmp
= g_find_program_in_path("gnome-open");
2908 tmp
= (gchar
*)g_getenv("GNOME_DESKTOP_SESSION_ID");
2910 return ((tmp
!= NULL
) && (*tmp
!= '\0'));
2917 purple_running_kde(void)
2920 gchar
*tmp
= g_find_program_in_path("kfmclient");
2921 const char *session
;
2927 session
= g_getenv("KDE_FULL_SESSION");
2928 if (purple_strequal(session
, "true"))
2931 /* If you run Purple from Konsole under !KDE, this will provide a
2932 * a false positive. Since we do the GNOME checks first, this is
2933 * only a problem if you're running something !(KDE || GNOME) and
2934 * you run Purple from Konsole. This really shouldn't be a problem. */
2935 return ((g_getenv("KDEDIR") != NULL
) || g_getenv("KDEDIRS") != NULL
);
2942 purple_running_osx(void)
2944 #if defined(__APPLE__)
2951 typedef union purple_sockaddr
{
2953 struct sockaddr_in sa_in
;
2954 #if defined(AF_INET6)
2955 struct sockaddr_in6 sa_in6
;
2957 struct sockaddr_storage sa_stor
;
2961 purple_fd_get_ip(int fd
)
2963 PurpleSockaddr addr
;
2964 socklen_t namelen
= sizeof(addr
);
2967 g_return_val_if_fail(fd
!= 0, NULL
);
2969 if (getsockname(fd
, &(addr
.sa
), &namelen
))
2972 family
= addr
.sa
.sa_family
;
2974 if (family
== AF_INET
) {
2975 return g_strdup(inet_ntoa(addr
.sa_in
.sin_addr
));
2977 #if defined(AF_INET6) && defined(HAVE_INET_NTOP)
2978 else if (family
== AF_INET6
) {
2979 char host
[INET6_ADDRSTRLEN
];
2982 tmp
= inet_ntop(family
, &(addr
.sa_in6
.sin6_addr
), host
, sizeof(host
));
2983 return g_strdup(tmp
);
2991 purple_socket_get_family(int fd
)
2993 PurpleSockaddr addr
;
2994 socklen_t len
= sizeof(addr
);
2996 g_return_val_if_fail(fd
>= 0, -1);
2998 if (getsockname(fd
, &(addr
.sa
), &len
))
3001 return addr
.sa
.sa_family
;
3005 purple_socket_speaks_ipv4(int fd
)
3009 g_return_val_if_fail(fd
>= 0, FALSE
);
3011 family
= purple_socket_get_family(fd
);
3016 #if defined(IPV6_V6ONLY)
3020 socklen_t len
= sizeof(val
);
3022 if (getsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &val
, &len
) != 0)
3032 /**************************************************************************
3034 **************************************************************************/
3036 purple_normalize(PurpleAccount
*account
, const char *str
)
3038 const char *ret
= NULL
;
3039 static char buf
[BUF_LEN
];
3041 /* This should prevent a crash if purple_normalize gets called with NULL str, see #10115 */
3042 g_return_val_if_fail(str
!= NULL
, "");
3044 if (account
!= NULL
)
3046 PurpleProtocol
*protocol
=
3047 purple_protocols_find(purple_account_get_protocol_id(account
));
3049 if (protocol
!= NULL
)
3050 ret
= purple_protocol_client_iface_normalize(protocol
, account
, str
);
3057 tmp
= g_utf8_normalize(str
, -1, G_NORMALIZE_DEFAULT
);
3058 g_snprintf(buf
, sizeof(buf
), "%s", tmp
);
3068 * You probably don't want to call this directly, it is
3069 * mainly for use as a protocol callback function. See the
3070 * comments in util.h.
3073 purple_normalize_nocase(const PurpleAccount
*account
, const char *str
)
3075 static char buf
[BUF_LEN
];
3078 g_return_val_if_fail(str
!= NULL
, NULL
);
3080 tmp1
= g_utf8_strdown(str
, -1);
3081 tmp2
= g_utf8_normalize(tmp1
, -1, G_NORMALIZE_DEFAULT
);
3082 g_snprintf(buf
, sizeof(buf
), "%s", tmp2
? tmp2
: "");
3090 purple_validate(const PurpleProtocol
*protocol
, const char *str
)
3092 const char *normalized
;
3094 g_return_val_if_fail(protocol
!= NULL
, FALSE
);
3095 g_return_val_if_fail(str
!= NULL
, FALSE
);
3100 if (!PURPLE_PROTOCOL_IMPLEMENTS(protocol
, CLIENT
, normalize
))
3103 normalized
= purple_protocol_client_iface_normalize(PURPLE_PROTOCOL(protocol
),
3106 return (NULL
!= normalized
);
3110 purple_strdup_withhtml(const gchar
*src
)
3112 gulong destsize
, i
, j
;
3115 g_return_val_if_fail(src
!= NULL
, NULL
);
3117 /* New length is (length of src) + (number of \n's * 3) - (number of \r's) + 1 */
3119 for (i
= 0; src
[i
] != '\0'; i
++)
3123 else if (src
[i
] != '\r')
3127 dest
= g_malloc(destsize
);
3129 /* Copy stuff, ignoring \r's, because they are dumb */
3130 for (i
= 0, j
= 0; src
[i
] != '\0'; i
++) {
3131 if (src
[i
] == '\n') {
3132 strcpy(&dest
[j
], "<BR>");
3134 } else if (src
[i
] != '\r')
3138 dest
[destsize
-1] = '\0';
3144 purple_str_has_prefix(const char *s
, const char *p
)
3146 return g_str_has_prefix(s
, p
);
3150 purple_str_has_caseprefix(const gchar
*s
, const gchar
*p
)
3152 g_return_val_if_fail(s
, FALSE
);
3153 g_return_val_if_fail(p
, FALSE
);
3155 return (g_ascii_strncasecmp(s
, p
, strlen(p
)) == 0);
3159 purple_str_has_suffix(const char *s
, const char *x
)
3161 return g_str_has_suffix(s
, x
);
3165 purple_str_add_cr(const char *text
)
3171 g_return_val_if_fail(text
!= NULL
, NULL
);
3173 if (text
[0] == '\n')
3175 for (i
= 1; i
< strlen(text
); i
++)
3176 if (text
[i
] == '\n' && text
[i
- 1] != '\r')
3180 return g_strdup(text
);
3182 ret
= g_malloc0(strlen(text
) + count
+ 1);
3185 if (text
[i
] == '\n')
3187 ret
[j
++] = text
[i
++];
3188 for (; i
< strlen(text
); i
++) {
3189 if (text
[i
] == '\n' && text
[i
- 1] != '\r')
3198 purple_str_strip_char(char *text
, char thechar
)
3202 g_return_if_fail(text
!= NULL
);
3204 for (i
= 0, j
= 0; text
[i
]; i
++)
3205 if (text
[i
] != thechar
)
3206 text
[j
++] = text
[i
];
3212 purple_util_chrreplace(char *string
, char delimiter
,
3217 g_return_if_fail(string
!= NULL
);
3219 while (string
[i
] != '\0')
3221 if (string
[i
] == delimiter
)
3222 string
[i
] = replacement
;
3228 purple_strreplace(const char *string
, const char *delimiter
,
3229 const char *replacement
)
3234 g_return_val_if_fail(string
!= NULL
, NULL
);
3235 g_return_val_if_fail(delimiter
!= NULL
, NULL
);
3236 g_return_val_if_fail(replacement
!= NULL
, NULL
);
3238 split
= g_strsplit(string
, delimiter
, 0);
3239 ret
= g_strjoinv(replacement
, split
);
3246 purple_strcasereplace(const char *string
, const char *delimiter
,
3247 const char *replacement
)
3250 int length_del
, length_rep
, i
, j
;
3252 g_return_val_if_fail(string
!= NULL
, NULL
);
3253 g_return_val_if_fail(delimiter
!= NULL
, NULL
);
3254 g_return_val_if_fail(replacement
!= NULL
, NULL
);
3256 length_del
= strlen(delimiter
);
3257 length_rep
= strlen(replacement
);
3259 /* Count how many times the delimiter appears */
3260 i
= 0; /* position in the source string */
3261 j
= 0; /* number of occurrences of "delimiter" */
3262 while (string
[i
] != '\0') {
3263 if (!g_ascii_strncasecmp(&string
[i
], delimiter
, length_del
)) {
3272 ret
= g_malloc(j
+1);
3274 i
= 0; /* position in the source string */
3275 j
= 0; /* position in the destination string */
3276 while (string
[i
] != '\0') {
3277 if (!g_ascii_strncasecmp(&string
[i
], delimiter
, length_del
)) {
3278 strncpy(&ret
[j
], replacement
, length_rep
);
3293 /** TODO: Expose this when we can add API */
3295 purple_strcasestr_len(const char *haystack
, gssize hlen
, const char *needle
, gssize nlen
)
3297 const char *tmp
, *ret
;
3299 g_return_val_if_fail(haystack
!= NULL
, NULL
);
3300 g_return_val_if_fail(needle
!= NULL
, NULL
);
3303 hlen
= strlen(haystack
);
3305 nlen
= strlen(needle
);
3309 g_return_val_if_fail(hlen
> 0, NULL
);
3310 g_return_val_if_fail(nlen
> 0, NULL
);
3312 while (*tmp
&& !ret
&& (hlen
- (tmp
- haystack
)) >= nlen
) {
3313 if (!g_ascii_strncasecmp(needle
, tmp
, nlen
))
3323 purple_strcasestr(const char *haystack
, const char *needle
)
3325 return purple_strcasestr_len(haystack
, -1, needle
, -1);
3329 purple_str_seconds_to_string(guint secs
)
3332 guint days
, hrs
, mins
;
3336 return g_strdup_printf(dngettext(PACKAGE
, "%d second", "%d seconds", secs
), secs
);
3339 days
= secs
/ (60 * 60 * 24);
3340 secs
= secs
% (60 * 60 * 24);
3341 hrs
= secs
/ (60 * 60);
3342 secs
= secs
% (60 * 60);
3344 /* secs = secs % 60; */
3348 ret
= g_strdup_printf(dngettext(PACKAGE
, "%d day", "%d days", days
), days
);
3355 char *tmp
= g_strdup_printf(
3356 dngettext(PACKAGE
, "%s, %d hour", "%s, %d hours", hrs
),
3362 ret
= g_strdup_printf(dngettext(PACKAGE
, "%d hour", "%d hours", hrs
), hrs
);
3369 char *tmp
= g_strdup_printf(
3370 dngettext(PACKAGE
, "%s, %d minute", "%s, %d minutes", mins
),
3376 ret
= g_strdup_printf(dngettext(PACKAGE
, "%d minute", "%d minutes", mins
), mins
);
3384 purple_str_binary_to_ascii(const unsigned char *binary
, guint len
)
3389 g_return_val_if_fail(len
> 0, NULL
);
3391 ret
= g_string_sized_new(len
);
3393 for (i
= 0; i
< len
; i
++)
3394 if (binary
[i
] < 32 || binary
[i
] > 126)
3395 g_string_append_printf(ret
, "\\x%02x", binary
[i
] & 0xFF);
3396 else if (binary
[i
] == '\\')
3397 g_string_append(ret
, "\\\\");
3399 g_string_append_c(ret
, binary
[i
]);
3401 return g_string_free(ret
, FALSE
);
3405 purple_utf16_size(const gunichar2
*str
)
3407 /* UTF16 cannot contain two consequent NUL bytes starting at even
3408 * position - see Unicode standards Chapter 3.9 D91 or RFC2781
3414 g_return_val_if_fail(str
!= NULL
, 0);
3418 return i
* sizeof(gunichar2
);
3422 purple_str_wipe(gchar
*str
)
3426 memset(str
, 0, strlen(str
));
3431 purple_utf16_wipe(gunichar2
*str
)
3435 memset(str
, 0, purple_utf16_size(str
));
3439 /**************************************************************************
3441 **************************************************************************/
3443 void purple_got_protocol_handler_uri(const char *uri
)
3447 const char *tmp
, *param_string
;
3449 GHashTable
*params
= NULL
;
3451 if (!(tmp
= strchr(uri
, ':')) || tmp
== uri
) {
3452 purple_debug_error("util", "Malformed protocol handler message - missing protocol.\n");
3456 len
= MIN(sizeof(proto
) - 1, (gsize
)(tmp
- uri
));
3458 strncpy(proto
, uri
, len
);
3463 if (purple_strequal(proto
, "xmpp"))
3468 purple_debug_info("util", "Processing message '%s' for protocol '%s' using delimiter '%c'.\n", tmp
, proto
, delimiter
);
3470 if ((param_string
= strchr(tmp
, '?'))) {
3471 const char *keyend
= NULL
, *pairstart
;
3472 char *key
, *value
= NULL
;
3474 cmd
= g_strndup(tmp
, (param_string
- tmp
));
3477 params
= g_hash_table_new_full(g_str_hash
, g_str_equal
, g_free
, g_free
);
3478 pairstart
= tmp
= param_string
;
3480 while (*tmp
|| *pairstart
) {
3481 if (*tmp
== delimiter
|| !(*tmp
)) {
3482 /* If there is no explicit value */
3483 if (keyend
== NULL
) {
3486 /* without these brackets, clang won't
3487 * recognize tmp as a non-NULL
3490 if (keyend
&& keyend
!= pairstart
) {
3492 key
= g_strndup(pairstart
, (keyend
- pairstart
));
3493 /* If there is an explicit value */
3494 if (keyend
!= tmp
&& keyend
!= (tmp
- 1))
3495 value
= g_strndup(keyend
+ 1, (tmp
- keyend
- 1));
3496 for (p
= key
; *p
; ++p
)
3497 *p
= g_ascii_tolower(*p
);
3498 g_hash_table_insert(params
, key
, value
);
3500 keyend
= value
= NULL
;
3501 pairstart
= (*tmp
) ? tmp
+ 1 : tmp
;
3502 } else if (*tmp
== '=')
3509 cmd
= g_strdup(tmp
);
3511 purple_signal_emit_return_1(purple_get_core(), "uri-handler", proto
, cmd
, params
);
3515 g_hash_table_destroy(params
);
3519 purple_url_decode(const char *str
)
3521 static char buf
[BUF_LEN
];
3526 g_return_val_if_fail(str
!= NULL
, NULL
);
3529 * XXX - This check could be removed and buf could be made
3530 * dynamically allocated, but this is easier.
3532 if (strlen(str
) >= BUF_LEN
)
3535 for (i
= 0; i
< strlen(str
); i
++) {
3540 strncpy(hex
, str
+ ++i
, 2);
3543 /* i is pointing to the start of the number */
3547 * Now it's at the end and at the start of the for loop
3548 * will be at the next character.
3550 buf
[j
++] = strtol(hex
, NULL
, 16);
3556 if (!g_utf8_validate(buf
, -1, (const char **)&bum
))
3563 purple_url_encode(const char *str
)
3566 static char buf
[BUF_LEN
];
3570 g_return_val_if_fail(str
!= NULL
, NULL
);
3571 g_return_val_if_fail(g_utf8_validate(str
, -1, NULL
), NULL
);
3574 for (; *iter
&& j
< (BUF_LEN
- 1) ; iter
= g_utf8_next_char(iter
)) {
3575 gunichar c
= g_utf8_get_char(iter
);
3576 /* If the character is an ASCII character and is alphanumeric
3577 * no need to escape */
3578 if (c
< 128 && (isalnum(c
) || c
== '-' || c
== '.' || c
== '_' || c
== '~')) {
3581 int bytes
= g_unichar_to_utf8(c
, utf_char
);
3582 for (i
= 0; (int)i
< bytes
; i
++) {
3583 if (j
> (BUF_LEN
- 4))
3585 if (i
>= sizeof(utf_char
)) {
3586 g_warn_if_reached();
3589 sprintf(buf
+ j
, "%%%02X", utf_char
[i
] & 0xff);
3600 /* Originally lifted from
3601 * http://www.oreillynet.com/pub/a/network/excerpt/spcookbook_chap03/index3.html
3602 * ... and slightly modified to be a bit more rfc822 compliant
3603 * ... and modified a bit more to make domain checking rfc1035 compliant
3604 * with the exception permitted in rfc1101 for domains to start with digit
3605 * but not completely checking to avoid conflicts with IP addresses
3608 purple_email_is_valid(const char *address
)
3610 const char *c
, *domain
;
3611 static char *rfc822_specials
= "()<>@,;:\\\"[]";
3613 g_return_val_if_fail(address
!= NULL
, FALSE
);
3615 if (*address
== '.') return FALSE
;
3617 /* first we validate the name portion (name@domain) (rfc822)*/
3618 for (c
= address
; *c
; c
++) {
3619 if (*c
== '\"' && (c
== address
|| *(c
- 1) == '.' || *(c
- 1) == '\"')) {
3622 if (*c
++ && *c
< 127 && *c
> 0 && *c
!= '\n' && *c
!= '\r') continue;
3625 if (*c
== '\"') break;
3626 if (*c
< ' ' || *c
>= 127) return FALSE
;
3628 if (!*c
++) return FALSE
;
3629 if (*c
== '@') break;
3630 if (*c
!= '.') return FALSE
;
3633 if (*c
== '@') break;
3634 if (*c
<= ' ' || *c
>= 127) return FALSE
;
3635 if (strchr(rfc822_specials
, *c
)) return FALSE
;
3638 /* It's obviously not an email address if we didn't find an '@' above */
3639 if (*c
== '\0') return FALSE
;
3641 /* strictly we should return false if (*(c - 1) == '.') too, but I think
3642 * we should permit user.@domain type addresses - they do work :) */
3643 if (c
== address
) return FALSE
;
3645 /* next we validate the domain portion (name@domain) (rfc1035 & rfc1011) */
3646 if (!*(domain
= ++c
)) return FALSE
;
3648 if (*c
== '.' && (c
== domain
|| *(c
- 1) == '.' || *(c
- 1) == '-'))
3650 if (*c
== '-' && (*(c
- 1) == '.' || *(c
- 1) == '@')) return FALSE
;
3651 if ((*c
< '0' && *c
!= '-' && *c
!= '.') || (*c
> '9' && *c
< 'A') ||
3652 (*c
> 'Z' && *c
< 'a') || (*c
> 'z')) return FALSE
;
3655 if (*(c
- 1) == '-') return FALSE
;
3657 return ((c
- domain
) > 3 ? TRUE
: FALSE
);
3661 purple_ipv4_address_is_valid(const char *ip
)
3663 int c
, o1
, o2
, o3
, o4
;
3666 g_return_val_if_fail(ip
!= NULL
, FALSE
);
3668 c
= sscanf(ip
, "%d.%d.%d.%d%c", &o1
, &o2
, &o3
, &o4
, &end
);
3669 if (c
!= 4 || o1
< 0 || o1
> 255 || o2
< 0 || o2
> 255 || o3
< 0 || o3
> 255 || o4
< 0 || o4
> 255)
3675 purple_ipv6_address_is_valid(const gchar
*ip
)
3678 gboolean double_colon
= FALSE
;
3682 g_return_val_if_fail(ip
!= NULL
, FALSE
);
3687 for (c
= ip
; *c
; ++c
) {
3688 if ((*c
>= '0' && *c
<= '9') ||
3689 (*c
>= 'a' && *c
<= 'f') ||
3690 (*c
>= 'A' && *c
<= 'F')) {
3692 /* Only four hex digits per chunk */
3695 } else if (*c
== ':') {
3696 /* The start of a new chunk */
3699 if (*(c
+ 1) == ':') {
3701 * '::' indicates a consecutive series of chunks full
3702 * of zeroes. There can be only one of these per address.
3706 double_colon
= TRUE
;
3713 * Either we saw a '::' and there were fewer than 8 chunks -or-
3714 * we didn't see a '::' and saw exactly 8 chunks.
3716 return (double_colon
&& chunks
< 8) || (!double_colon
&& chunks
== 8);
3720 purple_ip_address_is_valid(const char *ip
)
3722 return (purple_ipv4_address_is_valid(ip
) || purple_ipv6_address_is_valid(ip
));
3725 /* Stolen from gnome_uri_list_extract_uris */
3727 purple_uri_list_extract_uris(const gchar
*uri_list
)
3731 GList
*result
= NULL
;
3733 g_return_val_if_fail (uri_list
!= NULL
, NULL
);
3737 /* We don't actually try to validate the URI according to RFC
3738 * 2396, or even check for allowed characters - we just ignore
3739 * comments and trim whitespace off the ends. We also
3740 * allow LF delimination as well as the specified CRLF.
3748 while (*q
&& (*q
!= '\n') && (*q
!= '\r'))
3753 while (q
> p
&& isspace(*q
))
3756 retval
= (gchar
*)g_malloc (q
- p
+ 2);
3757 strncpy (retval
, p
, q
- p
+ 1);
3758 retval
[q
- p
+ 1] = '\0';
3760 result
= g_list_prepend (result
, retval
);
3763 p
= strchr (p
, '\n');
3768 return g_list_reverse (result
);
3772 /* Stolen from gnome_uri_list_extract_filenames */
3774 purple_uri_list_extract_filenames(const gchar
*uri_list
)
3776 GList
*tmp_list
, *node
, *result
;
3778 g_return_val_if_fail (uri_list
!= NULL
, NULL
);
3780 result
= purple_uri_list_extract_uris(uri_list
);
3784 gchar
*s
= (gchar
*)tmp_list
->data
;
3787 tmp_list
= tmp_list
->next
;
3789 if (!strncmp (s
, "file:", 5)) {
3790 node
->data
= g_filename_from_uri (s
, NULL
, NULL
);
3791 /* not sure if this fallback is useful at all */
3792 if (!node
->data
) node
->data
= g_strdup (s
+5);
3794 result
= g_list_delete_link(result
, node
);
3802 purple_uri_escape_for_open(const char *unescaped
)
3804 /* Replace some special characters like $ with their percent-encoded value.
3805 * This shouldn't be necessary because we shell-escape the entire arg before
3806 * exec'ing the browser, however, we had a report that a URL containing
3807 * $(xterm) was causing xterm to start on his system. This is obviously a
3808 * bug on his system, but it's pretty easy for us to protect against it. */
3809 return g_uri_escape_string(unescaped
, "[]:;/%#,+?=&@", FALSE
);
3812 /**************************************************************************
3813 * UTF8 String Functions
3814 **************************************************************************/
3816 purple_utf8_try_convert(const char *str
)
3821 g_return_val_if_fail(str
!= NULL
, NULL
);
3823 if (g_utf8_validate(str
, -1, NULL
)) {
3824 return g_strdup(str
);
3827 utf8
= g_locale_to_utf8(str
, -1, &converted
, NULL
, NULL
);
3831 utf8
= g_convert(str
, -1, "UTF-8", "ISO-8859-15", &converted
, NULL
, NULL
);
3832 if ((utf8
!= NULL
) && (converted
== strlen(str
)))
3840 #define utf8_first(x) ((x & 0x80) == 0 || (x & 0xe0) == 0xc0 \
3841 || (x & 0xf0) == 0xe0 || (x & 0xf8) == 0xf0)
3843 purple_utf8_salvage(const char *str
)
3848 g_return_val_if_fail(str
!= NULL
, NULL
);
3850 workstr
= g_string_sized_new(strlen(str
));
3853 (void)g_utf8_validate(str
, -1, &end
);
3854 workstr
= g_string_append_len(workstr
, str
, end
- str
);
3859 workstr
= g_string_append_c(workstr
, '?');
3861 } while (!utf8_first(*str
));
3862 } while (*str
!= '\0');
3864 return g_string_free(workstr
, FALSE
);
3868 purple_utf8_strip_unprintables(const gchar
*str
)
3870 gchar
*workstr
, *iter
;
3874 /* Act like g_strdup */
3877 if (!g_utf8_validate(str
, -1, &bad
)) {
3878 purple_debug_error("util", "purple_utf8_strip_unprintables(%s) failed; "
3879 "first bad character was %02x (%c)\n",
3881 g_return_val_if_reached(NULL
);
3884 workstr
= iter
= g_new(gchar
, strlen(str
) + 1);
3886 gunichar ch
= g_utf8_get_char(str
);
3887 gchar
*next
= g_utf8_next_char(str
);
3889 * Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
3890 * [#x10000-#x10FFFF]
3892 if ((ch
== '\t' || ch
== '\n' || ch
== '\r') ||
3893 (ch
>= 0x20 && ch
<= 0xD7FF) ||
3894 (ch
>= 0xE000 && ch
<= 0xFFFD) ||
3895 (ch
>= 0x10000 && ch
<= 0x10FFFF)) {
3896 memcpy(iter
, str
, next
- str
);
3897 iter
+= (next
- str
);
3903 /* nul-terminate the new string */
3910 * This function is copied from g_strerror() but changed to use
3914 purple_gai_strerror(gint errnum
)
3916 static GPrivate msg_private
= G_PRIVATE_INIT(g_free
);
3918 int saved_errno
= errno
;
3920 const char *msg_locale
;
3922 msg_locale
= gai_strerror(errnum
);
3923 if (g_get_charset(NULL
))
3925 /* This string is already UTF-8--great! */
3926 errno
= saved_errno
;
3931 gchar
*msg_utf8
= g_locale_to_utf8(msg_locale
, -1, NULL
, NULL
, NULL
);
3934 /* Stick in the quark table so that we can return a static result */
3935 GQuark msg_quark
= g_quark_from_string(msg_utf8
);
3938 msg_utf8
= (gchar
*)g_quark_to_string(msg_quark
);
3939 errno
= saved_errno
;
3944 msg
= g_private_get(&msg_private
);
3948 msg
= g_new(gchar
, 64);
3949 g_private_set(&msg_private
, msg
);
3952 sprintf(msg
, "unknown error (%d)", errnum
);
3954 errno
= saved_errno
;
3959 purple_utf8_ncr_encode(const char *str
)
3963 g_return_val_if_fail(str
!= NULL
, NULL
);
3964 g_return_val_if_fail(g_utf8_validate(str
, -1, NULL
), NULL
);
3966 out
= g_string_new("");
3968 for(; *str
; str
= g_utf8_next_char(str
)) {
3969 gunichar wc
= g_utf8_get_char(str
);
3971 /* super simple check. hopefully not too wrong. */
3973 g_string_append_printf(out
, "&#%u;", (guint32
) wc
);
3975 g_string_append_unichar(out
, wc
);
3979 return g_string_free(out
, FALSE
);
3984 purple_utf8_ncr_decode(const char *str
)
3989 g_return_val_if_fail(str
!= NULL
, NULL
);
3990 g_return_val_if_fail(g_utf8_validate(str
, -1, NULL
), NULL
);
3993 out
= g_string_new("");
3995 while( (b
= strstr(buf
, "&#")) ) {
3999 /* append everything leading up to the &# */
4000 g_string_append_len(out
, buf
, b
-buf
);
4002 b
+= 2; /* skip past the &# */
4004 /* strtoul will treat 0x prefix as hex, but not just x */
4005 if(*b
== 'x' || *b
== 'X') {
4010 /* advances buf to the end of the ncr segment */
4011 wc
= (gunichar
) strtoul(b
, &buf
, base
);
4013 /* this mimics the previous impl of ncr_decode */
4015 g_string_append_unichar(out
, wc
);
4020 /* append whatever's left */
4021 g_string_append(out
, buf
);
4023 return g_string_free(out
, FALSE
);
4028 purple_utf8_strcasecmp(const char *a
, const char *b
)
4030 char *a_norm
= NULL
;
4031 char *b_norm
= NULL
;
4041 if(!g_utf8_validate(a
, -1, NULL
) || !g_utf8_validate(b
, -1, NULL
))
4043 purple_debug_error("purple_utf8_strcasecmp",
4044 "One or both parameters are invalid UTF8\n");
4048 a_norm
= g_utf8_casefold(a
, -1);
4049 b_norm
= g_utf8_casefold(b
, -1);
4050 ret
= g_utf8_collate(a_norm
, b_norm
);
4057 /* previously conversation::find_nick() */
4059 purple_utf8_has_word(const char *haystack
, const char *needle
)
4061 char *hay
, *pin
, *p
;
4062 const char *start
, *prev_char
;
4063 gunichar before
, after
;
4065 gboolean ret
= FALSE
;
4067 start
= hay
= g_utf8_strdown(haystack
, -1);
4069 pin
= g_utf8_strdown(needle
, -1);
4072 while ((p
= strstr(start
, pin
)) != NULL
) {
4073 prev_char
= g_utf8_find_prev_char(hay
, p
);
4076 before
= g_utf8_get_char(prev_char
);
4078 after
= g_utf8_get_char_validated(p
+ n
, - 1);
4081 /* The character before is a reasonable guess for a word boundary
4082 ("!g_unichar_isalnum()" is not a valid way to determine word
4083 boundaries, but it is the only reasonable thing to do here),
4084 and isn't the '&' from a "&" or some such entity*/
4085 (before
!= (gunichar
)-2 && !g_unichar_isalnum(before
) && *(p
- 1) != '&'))
4086 && after
!= (gunichar
)-2 && !g_unichar_isalnum(after
)) {
4099 gboolean
purple_message_meify(char *message
, gssize len
)
4102 gboolean inside_html
= FALSE
;
4104 g_return_val_if_fail(message
!= NULL
, FALSE
);
4107 len
= strlen(message
);
4109 for (c
= message
; *c
; c
++, len
--) {
4112 inside_html
= FALSE
;
4121 if(*c
&& !g_ascii_strncasecmp(c
, "/me ", 4)) {
4122 memmove(c
, c
+4, len
-3);
4129 char *purple_text_strip_mnemonic(const char *in
)
4136 g_return_val_if_fail(in
!= NULL
, NULL
);
4138 out
= g_malloc(strlen(in
)+1);
4142 a0
= a
; /* The last non-space char seen so far, or the first char */
4146 if(a
> out
&& b
> in
&& *(b
-1) == '(' && *(b
+1) && !(*(b
+1) & 0x80) && *(b
+2) == ')') {
4147 /* Detected CJK style shortcut (Bug 875311) */
4148 a
= a0
; /* undo the left parenthesis */
4149 b
+= 3; /* and skip the whole mess */
4150 } else if(*(b
+1) == '_') {
4157 /* We don't want to corrupt the middle of UTF-8 characters */
4158 } else if (!(*b
& 0x80)) { /* other 1-byte char */
4163 /* Multibyte utf8 char, don't look for _ inside these */
4166 if ((*b
& 0xe0) == 0xc0) {
4168 } else if ((*b
& 0xf0) == 0xe0) {
4170 } else if ((*b
& 0xf8) == 0xf0) {
4172 } else if ((*b
& 0xfc) == 0xf8) {
4174 } else if ((*b
& 0xfe) == 0xfc) {
4176 } else { /* Illegal utf8 */
4179 a0
= a
; /* unless we want to delete CJK spaces too */
4180 for (i
= 0; i
< n
&& *b
; i
+= 1) {
4190 const char* purple_unescape_filename(const char *escaped
) {
4191 return purple_url_decode(escaped
);
4195 /* this is almost identical to purple_url_encode (hence purple_url_decode
4196 * being used above), but we want to keep certain characters unescaped
4197 * for compat reasons */
4199 purple_escape_filename(const char *str
)
4202 static char buf
[BUF_LEN
];
4206 g_return_val_if_fail(str
!= NULL
, NULL
);
4207 g_return_val_if_fail(g_utf8_validate(str
, -1, NULL
), NULL
);
4210 for (; *iter
&& j
< (BUF_LEN
- 1) ; iter
= g_utf8_next_char(iter
)) {
4211 gunichar c
= g_utf8_get_char(iter
);
4212 /* If the character is an ASCII character and is alphanumeric,
4213 * or one of the specified values, no need to escape */
4214 if (c
< 128 && (g_ascii_isalnum(c
) || c
== '@' || c
== '-' ||
4215 c
== '_' || c
== '.' || c
== '#')) {
4218 int bytes
= g_unichar_to_utf8(c
, utf_char
);
4219 for (i
= 0; (int)i
< bytes
; i
++) {
4220 if (j
> (BUF_LEN
- 4))
4222 if (i
>= sizeof(utf_char
)) {
4223 g_warn_if_reached();
4226 sprintf(buf
+ j
, "%%%02x", utf_char
[i
] & 0xff);
4232 /* File/Directory names in windows cannot end in periods/spaces.
4233 * http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx
4235 while (j
> 0 && (buf
[j
- 1] == '.' || buf
[j
- 1] == ' '))
4243 gchar
* purple_escape_js(const gchar
*str
)
4247 json_node_set_string(escape_js_node
, str
);
4248 json_generator_set_root(escape_js_gen
, escape_js_node
);
4249 escaped
= json_generator_to_data(escape_js_gen
, NULL
);
4250 json_node_set_boolean(escape_js_node
, FALSE
);
4255 void purple_restore_default_signal_handlers(void)
4258 signal(SIGHUP
, SIG_DFL
); /* 1: terminal line hangup */
4259 signal(SIGINT
, SIG_DFL
); /* 2: interrupt program */
4260 signal(SIGQUIT
, SIG_DFL
); /* 3: quit program */
4261 signal(SIGILL
, SIG_DFL
); /* 4: illegal instruction (not reset when caught) */
4262 signal(SIGTRAP
, SIG_DFL
); /* 5: trace trap (not reset when caught) */
4263 signal(SIGABRT
, SIG_DFL
); /* 6: abort program */
4266 signal(SIGPOLL
, SIG_DFL
); /* 7: pollable event (POSIX) */
4267 #endif /* SIGPOLL */
4270 signal(SIGEMT
, SIG_DFL
); /* 7: EMT instruction (Non-POSIX) */
4273 signal(SIGFPE
, SIG_DFL
); /* 8: floating point exception */
4274 signal(SIGBUS
, SIG_DFL
); /* 10: bus error */
4275 signal(SIGSEGV
, SIG_DFL
); /* 11: segmentation violation */
4276 signal(SIGSYS
, SIG_DFL
); /* 12: bad argument to system call */
4277 signal(SIGPIPE
, SIG_DFL
); /* 13: write on a pipe with no reader */
4278 signal(SIGALRM
, SIG_DFL
); /* 14: real-time timer expired */
4279 signal(SIGTERM
, SIG_DFL
); /* 15: software termination signal */
4280 signal(SIGCHLD
, SIG_DFL
); /* 20: child status has changed */
4281 signal(SIGXCPU
, SIG_DFL
); /* 24: exceeded CPU time limit */
4282 signal(SIGXFSZ
, SIG_DFL
); /* 25: exceeded file size limit */
4283 #endif /* !_WIN32 */
4287 set_status_with_attrs(PurpleStatus
*status
, ...)
4290 va_start(args
, status
);
4291 purple_status_set_active_with_attrs(status
, TRUE
, args
);
4295 void purple_util_set_current_song(const char *title
, const char *artist
, const char *album
)
4297 GList
*list
= purple_accounts_get_all();
4298 for (; list
; list
= list
->next
) {
4299 PurplePresence
*presence
;
4301 PurpleAccount
*account
= list
->data
;
4302 if (!purple_account_get_enabled(account
, purple_core_get_ui()))
4305 presence
= purple_account_get_presence(account
);
4306 tune
= purple_presence_get_status(presence
, "tune");
4310 set_status_with_attrs(tune
,
4311 PURPLE_TUNE_TITLE
, title
,
4312 PURPLE_TUNE_ARTIST
, artist
,
4313 PURPLE_TUNE_ALBUM
, album
,
4316 purple_status_set_active(tune
, FALSE
);
4321 char * purple_util_format_song_info(const char *title
, const char *artist
, const char *album
, gpointer unused
)
4326 if (!title
|| !*title
)
4329 esc
= g_markup_escape_text(title
, -1);
4330 string
= g_string_new("");
4331 g_string_append_printf(string
, "%s", esc
);
4334 if (artist
&& *artist
) {
4335 esc
= g_markup_escape_text(artist
, -1);
4336 g_string_append_printf(string
, _(" - %s"), esc
);
4340 if (album
&& *album
) {
4341 esc
= g_markup_escape_text(album
, -1);
4342 g_string_append_printf(string
, _(" (%s)"), esc
);
4346 return g_string_free(string
, FALSE
);
4350 purple_get_host_name(void)
4352 return g_get_host_name();
4356 purple_uuid_random(void)
4360 tmp
= g_random_int();
4361 a
= 0x4000 | (tmp
& 0xFFF); /* 0x4000 to 0x4FFF */
4363 b
= ((1 << 3) << 12) | (tmp
& 0x3FFF); /* 0x8000 to 0xBFFF */
4365 tmp
= g_random_int();
4367 return g_strdup_printf("%08x-%04x-%04x-%04x-%04x%08x",
4372 (tmp
>> 16) & 0xFFFF, g_random_int());
4375 void purple_callback_set_zero(gpointer data
)
4377 gpointer
*ptr
= data
;
4379 g_return_if_fail(ptr
!= NULL
);
4385 purple_value_new(GType type
)
4389 g_return_val_if_fail(type
!= G_TYPE_NONE
, NULL
);
4391 ret
= g_new0(GValue
, 1);
4392 g_value_init(ret
, type
);
4398 purple_value_dup(GValue
*value
)
4402 g_return_val_if_fail(value
!= NULL
, NULL
);
4404 ret
= g_new0(GValue
, 1);
4405 g_value_init(ret
, G_VALUE_TYPE(value
));
4406 g_value_copy(value
, ret
);
4412 purple_value_free(GValue
*value
)
4414 g_return_if_fail(value
!= NULL
);
4416 g_value_unset(value
);
4420 gchar
*purple_http_digest_calculate_session_key(
4421 const gchar
*algorithm
,
4422 const gchar
*username
,
4424 const gchar
*password
,
4426 const gchar
*client_nonce
)
4431 g_return_val_if_fail(username
!= NULL
, NULL
);
4432 g_return_val_if_fail(realm
!= NULL
, NULL
);
4433 g_return_val_if_fail(password
!= NULL
, NULL
);
4434 g_return_val_if_fail(nonce
!= NULL
, NULL
);
4436 /* Check for a supported algorithm. */
4437 g_return_val_if_fail(algorithm
== NULL
||
4438 *algorithm
== '\0' ||
4439 g_ascii_strcasecmp(algorithm
, "MD5") ||
4440 g_ascii_strcasecmp(algorithm
, "MD5-sess"), NULL
);
4442 hasher
= g_checksum_new(G_CHECKSUM_MD5
);
4443 g_return_val_if_fail(hasher
!= NULL
, NULL
);
4445 g_checksum_update(hasher
, (guchar
*)username
, -1);
4446 g_checksum_update(hasher
, (guchar
*)":", -1);
4447 g_checksum_update(hasher
, (guchar
*)realm
, -1);
4448 g_checksum_update(hasher
, (guchar
*)":", -1);
4449 g_checksum_update(hasher
, (guchar
*)password
, -1);
4451 if (algorithm
!= NULL
&& !g_ascii_strcasecmp(algorithm
, "MD5-sess"))
4454 gsize digest_len
= 16;
4456 if (client_nonce
== NULL
)
4458 g_object_unref(hasher
);
4459 purple_debug_error("hash", "Required client_nonce missing for MD5-sess digest calculation.\n");
4463 g_checksum_get_digest(hasher
, digest
, &digest_len
);
4465 g_checksum_reset(hasher
);
4466 g_checksum_update(hasher
, digest
, sizeof(digest
));
4467 g_checksum_update(hasher
, (guchar
*)":", -1);
4468 g_checksum_update(hasher
, (guchar
*)nonce
, -1);
4469 g_checksum_update(hasher
, (guchar
*)":", -1);
4470 g_checksum_update(hasher
, (guchar
*)client_nonce
, -1);
4473 hash
= g_strdup(g_checksum_get_string(hasher
));
4474 g_checksum_free(hasher
);
4479 gchar
*purple_http_digest_calculate_response(
4480 const gchar
*algorithm
,
4481 const gchar
*method
,
4482 const gchar
*digest_uri
,
4484 const gchar
*entity
,
4486 const gchar
*nonce_count
,
4487 const gchar
*client_nonce
,
4488 const gchar
*session_key
)
4493 g_return_val_if_fail(method
!= NULL
, NULL
);
4494 g_return_val_if_fail(digest_uri
!= NULL
, NULL
);
4495 g_return_val_if_fail(nonce
!= NULL
, NULL
);
4496 g_return_val_if_fail(session_key
!= NULL
, NULL
);
4498 /* Check for a supported algorithm. */
4499 g_return_val_if_fail(algorithm
== NULL
||
4500 *algorithm
== '\0' ||
4501 g_ascii_strcasecmp(algorithm
, "MD5") ||
4502 g_ascii_strcasecmp(algorithm
, "MD5-sess"), NULL
);
4504 /* Check for a supported "quality of protection". */
4505 g_return_val_if_fail(qop
== NULL
||
4507 g_ascii_strcasecmp(qop
, "auth") ||
4508 g_ascii_strcasecmp(qop
, "auth-int"), NULL
);
4510 hash
= g_checksum_new(G_CHECKSUM_MD5
);
4511 g_return_val_if_fail(hash
!= NULL
, NULL
);
4513 g_checksum_update(hash
, (guchar
*)method
, -1);
4514 g_checksum_update(hash
, (guchar
*)":", -1);
4515 g_checksum_update(hash
, (guchar
*)digest_uri
, -1);
4517 if (qop
!= NULL
&& !g_ascii_strcasecmp(qop
, "auth-int"))
4523 g_checksum_free(hash
);
4524 purple_debug_error("hash", "Required entity missing for auth-int digest calculation.\n");
4528 entity_hash
= g_compute_checksum_for_string(G_CHECKSUM_MD5
,
4531 if (entity_hash
== NULL
) {
4532 g_checksum_free(hash
);
4533 g_return_val_if_reached(NULL
);
4536 g_checksum_update(hash
, (guchar
*)":", -1);
4537 g_checksum_update(hash
, (guchar
*)entity_hash
, -1);
4538 g_free(entity_hash
);
4541 hash2
= g_strdup(g_checksum_get_string(hash
));
4542 g_checksum_reset(hash
);
4544 if (hash2
== NULL
) {
4545 g_checksum_free(hash
);
4546 g_return_val_if_reached(NULL
);
4549 g_checksum_update(hash
, (guchar
*)session_key
, -1);
4550 g_checksum_update(hash
, (guchar
*)":", -1);
4551 g_checksum_update(hash
, (guchar
*)nonce
, -1);
4552 g_checksum_update(hash
, (guchar
*)":", -1);
4554 if (qop
!= NULL
&& *qop
!= '\0')
4556 if (nonce_count
== NULL
)
4558 g_checksum_free(hash
);
4559 purple_debug_error("hash", "Required nonce_count missing for digest calculation.\n");
4563 if (client_nonce
== NULL
)
4565 g_checksum_free(hash
);
4566 purple_debug_error("hash", "Required client_nonce missing for digest calculation.\n");
4570 g_checksum_update(hash
, (guchar
*)nonce_count
, -1);
4571 g_checksum_update(hash
, (guchar
*)":", -1);
4572 g_checksum_update(hash
, (guchar
*)client_nonce
, -1);
4573 g_checksum_update(hash
, (guchar
*)":", -1);
4575 g_checksum_update(hash
, (guchar
*)qop
, -1);
4577 g_checksum_update(hash
, (guchar
*)":", -1);
4580 g_checksum_update(hash
, (guchar
*)hash2
, -1);
4583 hash2
= g_strdup(g_checksum_get_string(hash
));
4584 g_checksum_free(hash
);
4590 _purple_fstat(int fd
, GStatBuf
*st
)
4594 g_return_val_if_fail(st
!= NULL
, -1);
4597 ret
= _fstat(fd
, st
);
4599 ret
= fstat(fd
, st
);