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