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