Separated the strings used for document tree generation from code
[biaweb2.git] / biawebutil.hpp
1 #ifndef __BIAWEBUTIL__
2 #define __BIAWEBUTIL__
3 #include <string>
4
5 // "discount" markdown library is a C library and hence requires to be wrapped in
6 // extern "C"
7 extern "C" {
8 #include <mkdio.h>
9 }
10
11 // utility functions for Biaweb that don't fit into any class and can be used by
12 // any class
13 namespace biaweb {
14
15 // convert markdown
16 std::string convert_to_markdown (std::string str) {
17 // discount is a C library and it doesn't work well with C++ streams
18 // and there seems no way to get the output of any of these functions
19 // into an std::string.
20 // the only option seems to be to write the output of the markdown()
21 // function to a temporary working file and then read it back into C++
22 // with the normal std::ifstream and feed it into the std::string
23 // till a cleaner solution can be found.
24 MMIOT *doc;
25 doc = mkd_string (str.c_str(), str.size(), 0);
26 char tempfile[20];
27 strcpy (tempfile, "/tmp/biawebXXXXXX");
28 int fd = mkstemp (tempfile);
29 FILE *f = fdopen (fd, "w");
30 markdown (doc, f, 0);
31 fclose (f);
32 std::ifstream ftmp (tempfile);
33 std::string tmpl ( (std::istreambuf_iterator<char> (ftmp)),
34 (std::istreambuf_iterator<char> ())
35 );
36 ftmp.close ();
37 mkd_cleanup (doc);
38 remove (tempfile);
39 return tmpl;
40 }
41
42 // convert a document title to a file title - strip out the non-alpha
43 // chars and spaces
44 std::string convert_title (std::string title)
45 {
46 std::string output;
47 for (char c : title) {
48 if (isalnum (c))
49 output.append (1, c);
50 else if (isspace (c))
51 output.append (1, '_');
52 }
53 return output;
54 }
55
56 // escape HTML special characters
57 std::string escape_html (std::string source)
58 {
59 std::string replace_buf;
60 replace_buf.reserve (source.size());
61 for (char p : source)
62 {
63 switch (p)
64 {
65 case '&' : replace_buf.append ("&amp;"); break;
66 case '<' : replace_buf.append ("&lt;"); break;
67 case '>' : replace_buf.append ("&gt;"); break;
68 case '\"': replace_buf.append ("&quot;"); break;
69 case '\'': replace_buf.append ("&apos;"); break;
70 default : replace_buf.append (1, p);
71 }
72 }
73 return replace_buf;
74 }
75 }
76 #endif