Included functionality to describe the document in the input file
[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 mkstemp (tempfile);
29 FILE *f = fopen (tempfile, "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 return tmpl;
39 }
40
41 // convert a document title to a file title - strip out the non-alpha
42 // chars and spaces
43 std::string convert_title (std::string title)
44 {
45 std::string output;
46 for (char c : title) {
47 if (isalnum (c))
48 output.append (1, c);
49 else if (isspace (c))
50 output.append (1, '_');
51 }
52 return output;
53 }
54
55 // escape HTML special characters
56 std::string escape_html (std::string source)
57 {
58 std::string replace_buf;
59 replace_buf.reserve (source.size());
60 for (char p : source)
61 {
62 switch (p)
63 {
64 case '&' : replace_buf.append ("&amp;"); break;
65 case '<' : replace_buf.append ("&lt;"); break;
66 case '>' : replace_buf.append ("&gt;"); break;
67 case '\"': replace_buf.append ("&quot;"); break;
68 case '\'': replace_buf.append ("&apos;"); break;
69 default : replace_buf.append (1, p);
70 }
71 }
72 return replace_buf;
73 }
74 }
75 #endif