comments.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #define _GNU_SOURCE //asks stdio.h to include asprintf
  2. #include <stdio.h>
  3. #include "comments.h"
  4. #include "stopif.h"
  5. void printAuthors(const char *authorName, const char *anonName) {
  6. printf("\"%s\" is now \"%s\"\n", authorName, anonName);
  7. }
  8. char* anonymizeAuthor(binn *authors, const xmlChar *authorName) {
  9. static int authorsCount = 0;
  10. char *name = (char*)authorName;
  11. char *newName = binn_object_str(authors, name);
  12. if (newName)
  13. return newName;
  14. asprintf(&newName, "Author%d", ++authorsCount);
  15. binn_object_set_str(authors, name, newName);
  16. printAuthors(name, newName);
  17. free(newName);
  18. return binn_object_str(authors, name);
  19. }
  20. int processAuthors(const xmlXPathObjectPtr authors) {
  21. binn *anonAuthors = binn_object();
  22. for (int i=0; i < authors->nodesetval->nodeNr; i++){
  23. xmlChar *authorName = (xmlChar*)"";
  24. authorName = xmlNodeGetContent(authors->nodesetval->nodeTab[i]);
  25. char *anonAuthor = anonymizeAuthor(anonAuthors, authorName);
  26. xmlNodeSetContent(authors->nodesetval->nodeTab[i], (xmlChar*)anonAuthor);
  27. xmlFree(authorName);
  28. }
  29. binn_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. }