comments.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #define _GNU_SOURCE //asks stdio.h to include asprintf
  2. #include <stdio.h>
  3. #include "comments.h"
  4. #include "stopif.h"
  5. char* anonymizeAuthor(dictionary *authors, xmlChar const *authorName) {
  6. char *name = (char*)authorName;
  7. char *newName = (char*)dictionary_find(authors, name);
  8. if (newName)
  9. return newName;
  10. asprintf(&newName, "Author%d", authors->length+1);
  11. dictionary_add(authors, name, newName);
  12. free(newName);
  13. return (char*)dictionary_find(authors, name);
  14. }
  15. void printAuthors(dictionary *authors) {
  16. for (int i=0; i<authors->length; i++)
  17. printf("\"%s\" is now \"%s\"\n", authors->pairs[i]->key, (char*)authors->pairs[i]->value);
  18. }
  19. int processAuthors(xmlXPathObjectPtr authors) {
  20. dictionary *anonAuthors = dictionary_new();
  21. for (int i=0; i < authors->nodesetval->nodeNr; i++){
  22. xmlChar *authorName = (xmlChar*)"";
  23. authorName = xmlNodeGetContent(authors->nodesetval->nodeTab[i]);
  24. char *anonAuthor = anonymizeAuthor(anonAuthors, authorName);
  25. xmlNodeSetContent(authors->nodesetval->nodeTab[i], (xmlChar*)anonAuthor);
  26. xmlFree(authorName);
  27. }
  28. printAuthors(anonAuthors);
  29. dictionary_free(anonAuthors);
  30. return 1;
  31. }
  32. int anonymizeComments(XMLBuff *infile) {
  33. const xmlChar *authorPath = (xmlChar*)"//w:comment/@w:author";
  34. xmlDocPtr doc = xmlReadMemory(infile->data, infile->size, infile->name, NULL, 0);
  35. Stopif(!doc, return 0, "Unable to parse file %s!\n", infile->name);
  36. xmlXPathContextPtr context = xmlXPathNewContext(doc);
  37. Stopif(!context, return 0, "Unable to create new XPath context!\n");
  38. const xmlChar* prefix = (xmlChar*)"w";
  39. const xmlChar* ns = (xmlChar*)"http://schemas.openxmlformats.org/wordprocessingml/2006/main";
  40. Stopif(xmlXPathRegisterNs(context, prefix, ns), return 0, "Can't add namespace!\n");
  41. xmlXPathObjectPtr authors = xmlXPathEvalExpression(authorPath, context);
  42. Stopif(!authors, return 0, "Something is wrong with XPATH %s!\n", authorPath);
  43. Stopif(!processAuthors(authors), return 0, "Can't process authors!\n");
  44. xmlChar *buf;
  45. xmlDocDumpMemoryEnc(doc, &buf, &infile->size, "UTF-8");
  46. infile->data = (char*)buf;
  47. Stopif(!infile->size, return 0, "Unable to save file %s!\n", infile->name);
  48. xmlXPathFreeObject(authors);
  49. xmlXPathFreeContext(context);
  50. xmlFreeDoc(doc);
  51. xmlCleanupParser();
  52. return 1;
  53. }