50cfae68f8d5abfbdbbd94f1d9611bc3806cac96
[citadel.git] / webcit / http_datestring.c
1 /*
2  * $Id$
3  */
4 /**
5  * \defgroup HTTPDateTime Function to generate HTTP-compliant textual time/date stamp
6  * (This module was lifted directly from the Citadel server source)
7  *
8  * \ingroup WebcitHttpServer
9  */
10 /*@{*/
11 #include "webcit.h"
12
13 /** HTTP Months - do not translate - these are not for human consumption */
14 static char *httpdate_months[] = {
15         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
16         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
17 };
18
19 /** HTTP Weekdays - do not translate - these are not for human consumption */
20 static char *httpdate_weekdays[] = {
21         "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
22 };
23
24
25 /**
26  * \brief Supplied with a unix timestamp, generate a textual time/date stamp
27  * \param buf the return buffer
28  * \param n the size of the buffer
29  * \param xtime the time to format as string
30  */
31 void http_datestring(char *buf, size_t n, time_t xtime) {
32         struct tm t;
33
34         long offset;
35         char offsign;
36
37         localtime_r(&xtime, &t);
38
39         /** Convert "seconds west of GMT" to "hours/minutes offset" */
40 #ifdef HAVE_STRUCT_TM_TM_GMTOFF
41         offset = t.tm_gmtoff;
42 #else
43         offset = timezone;
44 #endif
45         if (offset > 0) {
46                 offsign = '+';
47         }
48         else {
49                 offset = 0L - offset;
50                 offsign = '-';
51         }
52         offset = ( (offset / 3600) * 100 ) + ( offset % 60 );
53
54         snprintf(buf, n, "%s, %02d %s %04d %02d:%02d:%02d %c%04ld",
55                 httpdate_weekdays[t.tm_wday],
56                 t.tm_mday,
57                 httpdate_months[t.tm_mon],
58                 t.tm_year + 1900,
59                 t.tm_hour,
60                 t.tm_min,
61                 t.tm_sec,
62                 offsign, offset
63         );
64 }
65
66
67 void tmplput_nowstr(StrBuf *Target, WCTemplputParams *TP)
68 {
69         char buf[64];
70         long bufused;
71         time_t now;
72         
73         now = time(NULL);
74 #ifdef HAVE_SOLARIS_LOCALTIME_R
75         asctime_r(localtime(&now), buf, sizeof(buf));
76 #else
77         asctime_r(localtime(&now), buf);
78 #endif
79         bufused = strlen(buf);
80         if ((bufused > 0) && (buf[bufused - 1] == '\n')) {
81                 buf[bufused - 1] = '\0';
82                 bufused --;
83         }
84         StrEscAppend(Target, NULL, buf, 0, 0);
85 }
86 void tmplput_nowno(StrBuf *Target, WCTemplputParams *TP)
87 {
88         time_t now;
89         now = time(NULL);
90         StrBufAppendPrintf(Target, "%ld", now);
91 }
92
93 void 
94 InitModule_DATE
95 (void)
96 {
97         RegisterNamespace("DATE:NOW:STR", 0, 0, tmplput_nowstr, NULL, CTX_NONE);
98         RegisterNamespace("DATE:NOW:NO", 0, 0, tmplput_nowno, NULL, CTX_NONE);
99 }
100
101 /*@}*/