generator.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. <?php
  2. global $options;
  3. global $preamble;
  4. $preamble = "";
  5. global $kpsefiles;
  6. $kpsefiles = [];
  7. global $existing_commands;
  8. global $included_usepackages;
  9. $included_usepackages = [];
  10. global $additional_usepackages;
  11. $additional_usepackages = [];
  12. $steps = 10;
  13. function user_consent($msg,$defaultyes = null,$defaultno = null)
  14. {
  15. global $options;
  16. if (isset($options["-n"]))
  17. return false;
  18. if ($defaultyes !== null && isset($options[$defaultyes]))
  19. return true;
  20. if ($defaultno !== null && isset($options[$defaultno]))
  21. return false;
  22. $response = false;
  23. do
  24. {
  25. echo "$msg (y/n)\n";
  26. $response = rtrim(fgets(STDIN));
  27. if ($response === "n" || $response == "N")
  28. return false;
  29. } while ($response !== "y" && $response !== "Y" && $response !== "");
  30. return true;
  31. }
  32. function user_prompt($msg,$default)
  33. {
  34. global $options;
  35. echo "$msg [Default: $default]\n";
  36. $response = "";
  37. if (!isset($options["-n"]))
  38. $response = rtrim(fgets(STDIN));
  39. if ($response == "")
  40. $response = $default;
  41. echo "You entered: '$response'\n";
  42. return $response;
  43. }
  44. function print_help()
  45. {
  46. $name = basename(__FILE__);
  47. echo<<<END
  48. Usage: php $name /path/folder1/main.tex /path/folder2/article.tex ... /path/folderN/paper.tex\n
  49. Generate a thesis template from the provided paper tex files and folders.
  50. The absolute minimum for a cumulative thesis is currently 3 papers first-authored and 6 in total.
  51. --force-overwrite overwrite files and folders
  52. --no-overwrite do not overwrite files and folders
  53. --no-compile-check do not perform a compile check
  54. --use-backups restore backups before making changes
  55. --not-sloppy disable use of sloppypar around places that struggle without
  56. (mainly the bibliographies)
  57. --cv add a CV
  58. (unusual for PhD theses, required for habilitation theses)
  59. --no-stat-declaration do not add the statutory declaration
  60. (required for PhD thesis, unusual for habilitation theses)
  61. -n skip all prompts (implies --no-overwrite)
  62. --help display this help and exit
  63. END;
  64. exit(0);
  65. }
  66. function error_exit($msg,$usage = false)
  67. {
  68. echo "ERROR: $msg\n";
  69. if ($usage)
  70. echo "Usage: php ".basename(__FILE__)." /path/folder1/main.tex /path/folder2/article.tex ... /path/folderN/paper.tex\n";
  71. exit(-1);
  72. }
  73. function check_software()
  74. {
  75. if (strpos(shell_exec("latexmk --version"),"Latexmk,") === false)
  76. error_exit("latexmk not installed");
  77. if (!str_starts_with(shell_exec("pdftotext --help 2>&1"),"pdftotext version"))
  78. error_exit("pdftotext not installed");
  79. }
  80. function rrmdir($dir) {
  81. if (is_dir($dir)) {
  82. $files = scandir($dir);
  83. foreach ($files as $file)
  84. if ($file != "." && $file != "..") rrmdir("$dir/$file");
  85. rmdir($dir);
  86. }
  87. else if (file_exists($dir)) unlink($dir);
  88. }
  89. function rcopy($src, $dst) {
  90. if (file_exists($dst)) rrmdir($dst);
  91. if (is_dir($src)) {
  92. mkdir($dst);
  93. $files = scandir($src);
  94. foreach ($files as $file)
  95. if ($file != "." && $file != "..") rcopy("$src/$file", "$dst/$file");
  96. }
  97. else if (file_exists($src)) copy($src, $dst);
  98. }
  99. function rscandir($dir,$extensions = []) {
  100. $result = [];
  101. if (!str_ends_with($dir,"/"))
  102. $dir .= "/";
  103. if (str_ends_with($dir,"latex.out/"))
  104. return $result;
  105. $array = scandir($dir);
  106. foreach ($array as $item) {
  107. if (!str_starts_with($item,"."))
  108. {
  109. if (!is_dir($dir.$item))
  110. {
  111. $extension_match = true;
  112. if ($extensions != [])
  113. {
  114. $extension_match = false;
  115. foreach ($extensions as $e)
  116. {
  117. if (str_ends_with($item,"$e"))
  118. {
  119. $extension_match = true;
  120. }
  121. }
  122. }
  123. if ($extension_match)
  124. $result[] = $dir.$item;
  125. }
  126. else
  127. $result = array_merge($result, rscandir($dir.$item,$extensions));
  128. }
  129. }
  130. return $result;
  131. }
  132. function unique_targets($targets)
  133. {
  134. $parts_required = 1;
  135. $unique_targets = [];
  136. while (count($unique_targets) != count($targets))
  137. {
  138. foreach ($targets as $t)
  139. {
  140. $tparts = explode("/",$t);
  141. $tpcount = count($tparts);
  142. $tparts = array_splice($tparts,$tpcount-$parts_required,$parts_required);
  143. $t = implode("_",$tparts);
  144. if (isset($unique_targets[$t]))
  145. {
  146. $parts_required++;
  147. $unique_targets = [];
  148. break;
  149. }
  150. $unique_targets[$t] = 1;
  151. }
  152. }
  153. return array_keys($unique_targets);
  154. }
  155. function check_folders($argv)
  156. {
  157. $args = array_slice($argv,1);
  158. $sourcedirs = [];
  159. foreach ($args as $a)
  160. {
  161. if (!str_starts_with($a,"-"))
  162. $sourcedirs[] = $a;
  163. }
  164. if (count($sourcedirs) < 1)
  165. {
  166. error_exit("Too few papers. Need at least one paper to run this.",true);
  167. }
  168. if (count($sourcedirs) < 3)
  169. {
  170. echo "Warning: Too few papers. The statutes require as an absolute minimum for a cumulative thesis at least 3 first-author papers and at least 6 in total.";
  171. }
  172. if (count($sourcedirs) < 5)
  173. {
  174. echo "Warning: Few papers. Check your institute guidelines to see how many papers are recommended. Also the statutes require as an absolute minimum for a cumulative thesis at least 6 papers in total.";
  175. }
  176. $texfiles = [];
  177. for ($i = 0; $i < count($sourcedirs); $i++)
  178. {
  179. $texfiles[$i] = basename($sourcedirs[$i]);
  180. $sourcedirs[$i] = dirname($sourcedirs[$i]);
  181. }
  182. $targets = unique_targets($sourcedirs);
  183. return [$targets,$texfiles,$sourcedirs];
  184. }
  185. function check_and_copy_folders($argv)
  186. {
  187. [$targets,$texfiles,$sourcedirs] = check_folders($argv);
  188. //echo "Source -> Target Directory Mapping:\n";
  189. $n = count($sourcedirs);
  190. //print_r($mapping);
  191. for ($i = 0; $i < $n; $i++)
  192. {
  193. $s = $sourcedirs[$i];
  194. $t = $targets[$i];
  195. $f = $texfiles[$i];
  196. if (str_ends_with($f,".pdf"))
  197. {
  198. if (!file_exists("$s/$f"))
  199. error_exit("$s/$f not found");
  200. if (file_exists("$t/$f.pdf") && !user_consent("$t/$f.pdf already exists... overwrite?","--force-overwrite","--no-overwrite"))
  201. {
  202. echo "Skipping $s/$f, $t/$f.pdf already exists...\n";
  203. }
  204. else
  205. {
  206. echo "Copying $s/$f to $t/$f...\n";
  207. if (!file_exists($t)) mkdir($t);
  208. rcopy("$s/$f","$t/$f");
  209. }
  210. }
  211. else
  212. {
  213. if (!file_exists($s))
  214. error_exit("$s not found");
  215. if (file_exists($t) && !user_consent("$t already exists... overwrite?","--force-overwrite","--no-overwrite"))
  216. {
  217. echo "Skipping ".$s.", ".$t." already exists...\n";
  218. }
  219. else
  220. {
  221. echo "Copying ".$s." to ".$t."...\n";
  222. rcopy($s,$t);
  223. }
  224. }
  225. }
  226. return array_combine($targets,$texfiles);
  227. }
  228. function file_get_and_backup($f,$bak = ".orig_bak")
  229. {
  230. global $options;
  231. if (isset($options["--use-backups"]))
  232. {
  233. if (file_exists("$f$bak"))
  234. copy("$f$bak", $f);
  235. }
  236. $content = file_get_contents("$f");
  237. if (!file_exists("$f$bak"))
  238. file_put_contents("$f$bak",$content);
  239. return $content;
  240. }
  241. function adjust_references($papers,$extensions = [])
  242. {
  243. $bibresources = [];
  244. foreach ($papers as $d => $f)
  245. {
  246. if (str_ends_with($f,".pdf"))
  247. continue;
  248. $files = rscandir($d,$extensions);
  249. foreach ($files as $file)
  250. {
  251. if (str_ends_with($file,".bib"))
  252. {
  253. $bib = file_get_and_backup($file);
  254. $bib = preg_replace("/(^\s*@\s*[a-z]+\s*\{\s*)((?!$d)\S)/i",'${1}'.$d.':${2}',$bib);
  255. $bib = preg_replace("/(\n\s*@\s*[a-z]+\s*\{\s*)((?!$d)\S)/i",'${1}'.$d.':${2}',$bib);
  256. $bib = preg_replace("/([\{\"].*)[^\\\\]#(.*)/i",'${1}\#${2}',$bib);
  257. $bib = preg_replace("/{\\\\i}/","{i}",$bib);
  258. file_put_contents($file,$bib);
  259. $bibresources[$d] = $file;
  260. }
  261. else
  262. {
  263. $tex = file_get_and_backup($file);
  264. // labels of lstlistings etc
  265. $tex = preg_replace("/([\[,]\s*label\s*=\s*)((?!$d)[^\[,]+[\[,])/i",'${1}'.$d.':${2}',$tex);
  266. // normal labels
  267. $tex = preg_replace("/(\\\label\s*\{\s*)((?!$d)[^}]+\})/i",'${1}'.$d.':${2}',$tex);
  268. // cref ref autoref
  269. $refs = [];
  270. preg_match_all("/\\\(cref|ref|autoref)\s*\{\s*[^}]+\}/i",$tex,$refs);
  271. foreach ($refs[0] as $ref)
  272. {
  273. $oldref = $ref;
  274. $ref = preg_replace("/([{,])\s*((?!$d)[^,}]+[},])/i",'${1}'.$d.':${2}',$ref);
  275. $ref = preg_replace("/([{,])\s*((?!$d)[^,}]+[},])/i",'${1}'.$d.':${2}',$ref);
  276. $tex = str_replace($oldref,$ref,$tex);
  277. }
  278. // cite citeA citeauthor etc
  279. $cites = [];
  280. preg_match_all("/\\\([a-z]*cite[a-z]*)\s*\{\s*[^}]+\}/i",$tex,$cites);
  281. foreach ($cites[0] as $cite)
  282. {
  283. $oldcite = $cite;
  284. $cite = preg_replace("/([{,])\s*((?!$d)[^,}]+[},])/i",'${1}'.$d.':${2}',$cite);
  285. $cite = preg_replace("/([{,])\s*((?!$d)[^,}]+[},])/i",'${1}'.$d.':${2}',$cite);
  286. $tex = str_replace($oldcite,$cite,$tex);
  287. }
  288. file_put_contents($file,$tex);
  289. }
  290. }
  291. }
  292. return $bibresources;
  293. }
  294. function handle_appendix($tex)
  295. {
  296. $appendix = false;
  297. $lines = explode("\n",$tex);
  298. for ($i = 0; $i < count($lines); $i++)
  299. {
  300. if ($appendix)
  301. {
  302. $lines[$i] = str_replace(['\subsubsection','\subsection','\section'],['\paragraph','\subsubsection','\subsection'],$lines[$i]);
  303. }
  304. if (str_starts_with($lines[$i],'\appendices') || str_starts_with($lines[$i],'\appendix'))
  305. {
  306. $lines[$i] = '\section*{Appendix}';
  307. $appendix = true;
  308. }
  309. }
  310. $tex = implode("\n",$lines);
  311. return $tex;
  312. }
  313. function stripformatting($tex)
  314. {
  315. return str_ireplace(['\Large ','\bf ','\rm ','\\\\'],[' ',' ',' ',' '],$tex);
  316. }
  317. function getusepackages($tex)
  318. {
  319. $packages = [];
  320. preg_match_all("/\n\s*(\\\\usepackage([^{}]*)(?<R>{((?:[^{}]+|(?&R))*)}))/i",$tex,$packages);
  321. if (isset($packages[1]))
  322. {
  323. return [$packages[1],$packages[4]];
  324. }
  325. return [[],[]];
  326. }
  327. function getmathops($tex)
  328. {
  329. $mathops = [];
  330. preg_match_all("/\n\s*(\\\\DeclareMath(Operator|Alphabet)\\*?((?<R>{((?:[^{}]+|(?&R))*)})([^{}]*)|\\\\[^\{]*)(?<P>{((?:[^{}]+|(?&P))*)})(?<Q>{((?:[^{}]+|(?&Q))*)})?(?<S>{((?:[^{}]+|(?&S))*)})?(?<T>{((?:[^{}]+|(?&T))*)})?)/i",$tex,$mathops);
  331. if (isset($mathops[4]))
  332. return [$mathops[1],$mathops[3]];
  333. return [];
  334. }
  335. function getnewcommands($tex)
  336. {
  337. $newcommands = [];
  338. preg_match_all("/\n\s*(\\\\newcommand([^{}]*)(?<R>{((?:[^{}]+|(?&R))*)})([^{}]*)(?<P>{((?:[^{}]+|(?&P))*)}))/i",$tex,$newcommands);
  339. if (isset($newcommands[4]))
  340. return $newcommands[4];
  341. return [];
  342. }
  343. function adjust_papers($papers,$extensions = [])
  344. {
  345. $tex = "";
  346. $paper_fulltitle = "";
  347. $authors = "";
  348. $institute = "";
  349. foreach ($papers as $d => $f)
  350. {
  351. if (str_ends_with($f,".pdf"))
  352. {
  353. $paper_fulltitle = trim(user_prompt("Please enter the full title for the paper in folder '$d'","TODO"));
  354. $paper_shorttitle = trim(user_prompt("Please enter a short title for the paper in folder '$d'","TODO"));
  355. $authors = trim(user_prompt("Please enter the author list for paper '$d'","TODO"));
  356. $header=<<<END
  357. \chapter[$paper_shorttitle]{{$paper_fulltitle}}\label{chapter:$d}
  358. \section*{Publication Data}
  359. \\fullcite{TODO}
  360. \section*{Contributions}
  361. TODO
  362. \includepdf[pages=-]{{$d}/{$f}}
  363. END;
  364. file_put_contents("$d/main.tex",$header);
  365. }
  366. $files = rscandir($d,$extensions);
  367. $authors = "";
  368. $institute = "";
  369. $title = "";
  370. $paper_fulltitle = "";
  371. $paper_shorttitle = "";
  372. foreach ($files as $file)
  373. {
  374. if (!str_ends_with($file,".tex") && !str_ends_with($file,".tikz") && !str_ends_with($file,".sty"))
  375. continue;
  376. $tex = file_get_and_backup($file,".interm_bak");
  377. if ($authors == "" && preg_match("/\n\s*\\\\author\s*(?<R>{((?:[^{}]+|(?&R))*)})/i",$tex) == 1)
  378. {
  379. preg_match_all("/\n\s*\\\\author\s*(?<R>{((?:[^{}]+|(?&R))*)})/i",$tex,$authors);
  380. if (isset($authors[2]) && isset($authors[2][0]))
  381. $authors = trim(stripformatting($authors[2][0]));
  382. }
  383. if ($institute == "" && preg_match("/\n\s*\\\\institute\s*(?<R>{((?:[^{}]+|(?&R))*)})/i",$tex) == 1)
  384. {
  385. preg_match_all("/\n\s*\\\\institute\s*(?<R>{((?:[^{}]+|(?&R))*)})/i",$tex,$institute);
  386. if (isset($institute[2]) && isset($institute[2][0]))
  387. $institute = trim(stripformatting($institute[2][0]));
  388. }
  389. if ($paper_shorttitle == "" && preg_match("/\n\s*\\\\title\s*(?<R>{((?:[^{}]+|(?&R))*)})/i",$tex) == 1)
  390. {
  391. preg_match_all("/\n\s*\\\\title\s*(?<R>{((?:[^{}]+|(?&R))*)})/i",$tex,$title);
  392. if (isset($title[2]) && isset($title[2][0]))
  393. $title = trim(stripformatting($title[2][0]));
  394. else
  395. $title = $d;
  396. $shorttitle = $title;
  397. if (strpos($title,":") !== false)
  398. $shorttitle = trim(explode(":",$title)[0]);
  399. $paper_fulltitle = trim(user_prompt("Please enter the full title for the paper in folder '$d'","$title"));
  400. $paper_shorttitle = trim(user_prompt("Please enter a short title for the paper in folder '$d'","$shorttitle"));
  401. }
  402. $header = "";
  403. if ($paper_fulltitle != "" && $paper_shorttitle != "" && $authors != "")
  404. {
  405. $header=<<<END
  406. \chapter[$paper_shorttitle]{{$paper_fulltitle}}\label{chapter:$d}
  407. \section*{Publication Data}
  408. \\fullcite{TODO}
  409. \section*{Contributions}
  410. TODO
  411. \\newpage
  412. \begin{center}
  413. {\Large \\textbf{
  414. $paper_fulltitle%
  415. }}\\\\\
  416. \\vspace{0.6cm}
  417. {\large $authors%
  418. } % TODO: check author list
  419. {\large $institute%
  420. } % TODO: check author list
  421. \\end{center}
  422. END;
  423. }
  424. [$mathopsfull,$mathops] = getmathops($tex);
  425. global $existing_mathops;
  426. global $preamble;
  427. $addmathops = array_diff($mathops,$existing_mathops);
  428. foreach ($addmathops as $k => $v)
  429. {
  430. $preamble .= $mathopsfull[$k] . "\n";
  431. $existing_mathops[] = $v;
  432. }
  433. $tex = preg_replace("/\\\documentclass.*\\n/i","
  434. ",$tex);
  435. $tex = preg_replace("/\\\begin{document}/i",$header,$tex);
  436. $tex = preg_replace("/\\\begin{abstract}/i",'\section*{Abstract}',$tex);
  437. $tex = preg_replace("/\\\\newcommand/i",'\declarecommand',$tex);
  438. $tex = preg_replace("/\\\\renewcommand/i",'\declarecommand',$tex);
  439. $tex = preg_replace("/\\\\end{abstract}/i",'',$tex);
  440. $tex = preg_replace("/\\\\DeclareMathOperator/i",'%$0',$tex);
  441. $tex = preg_replace("/\\\\DeclareMathAlphabet/i",'%$0',$tex);
  442. $tex = preg_replace("/\\\\usepackage[cache=false]{minted}/i",'\usepackage{minted}',$tex);
  443. $tex = preg_replace("/\\\\thispagestyle{empty}/i",'',$tex);
  444. $tex = preg_replace("/\\\\PassOptionsToPackage\s*(?<R>{((?:[^{}]+|(?&R))*)})(?<Q>{((?:[^{}]+|(?&Q))*)})/i",'',$tex);
  445. $tex = preg_replace("/(\\\\csvautobooktabular\s*([^{}]*)\s*)(?<R>{((?:[^{}]+|(?&R))*)})/i","\\1{{$d}/\\4}",$tex);
  446. $tex = preg_replace("/\\\\bibliographystyle\s*(?<R>{((?:[^{}]+|(?&R))*)})/i","",$tex);
  447. $tex = preg_replace("/\\\\usetikzlibrary\s*(?<R>{((?:[^{}]+|(?&R))*)})/i","",$tex);
  448. $tex = preg_replace("/\\\\DeclareFloatFont\s*(?<R>{((?:[^{}]+|(?&R))*)})(?<Q>{((?:[^{}]+|(?&Q))*)})/i","",$tex);
  449. $tex = preg_replace("/\\\\captionsetup\s*(?<R>\[((?:[^\[\]]+|(?&R))*)\])?(?<Q>{((?:[^{}]+|(?&Q))*)})/i","",$tex);
  450. $tex = preg_replace("/\\\\tikzexternalize\s*(?<R>\[((?:[^\[\]]+|(?&R))*)\])/i","",$tex);
  451. $tex = preg_replace("/\\\\floatsetup\s*(?<R>\[((?:[^\[\]]+|(?&R))*)\])(?<Q>{((?:[^{}]+|(?&Q))*)})/i","",$tex);
  452. $tex = preg_replace("/\s*\\\\bibliography\s*(?<R>{((?:[^{}]+|(?&R))*)})/i","\n".'\begin{sloppypar}
  453. \printbibliography[title={References}, heading=subbibliography]
  454. \end{sloppypar}',$tex);
  455. $tex = preg_replace("/\\\\end{document}/i",'',$tex);
  456. $tex = preg_replace("/\n\s*\\\\author\s*(?<R>{((?:[^{}]+|(?&R))*)})/i","",$tex);
  457. $tex = preg_replace("/\n\s*\\\\authorrunning\s*(?<R>{((?:[^{}]+|(?&R))*)})/i","",$tex);
  458. $tex = preg_replace("/\n\s*\\\\institute\s*(?<R>{((?:[^{}]+|(?&R))*)})/i","",$tex);
  459. $tex = preg_replace("/\n\s*\\\\title\s*(?<R>{((?:[^{}]+|(?&R))*)})/i","",$tex);
  460. $tex = preg_replace("/\n\s*\\\\date\s*(?<R>{((?:[^{}]+|(?&R))*)})/i","",$tex);
  461. $tex = preg_replace("/\\\\includegraphics\s*(?<R>\[((?:[^\[\]]+|(?&R))*)\])(?<Q>{((?:[^{}]+|(?&Q))*)})/i",'\includegraphics${1}{'.$d.'/${4}}',$tex);
  462. $tex = preg_replace("/\n\s*\\\\maketitle/i","",$tex);
  463. $tex = preg_replace("/\\\\IEEEoverridecommandlockouts/i","",$tex);
  464. $tex = preg_replace("/\\\\twocolumn/i","",$tex);
  465. $tex = preg_replace("/\n\s*\\\\tikzexternalize/i","",$tex);
  466. [$ups,$ps] = getusepackages($tex);
  467. global $included_usepackages;
  468. global $additional_usepackages;
  469. foreach (array_diff($ps,$included_usepackages) as $k => $v) {
  470. if (in_array($v,['minted']))
  471. {
  472. $additional_usepackages[] = "\usepackage{minted}";
  473. $included_usepackages[] = $v;
  474. }
  475. else if (!in_array($v,['usenix','usenix,epsfig,endnotes','flushend','mathptmx','usenixbadges','cite','csvenhanced']) && !($v == 'floatrow' && in_array('float',$included_usepackages)))
  476. {
  477. $additional_usepackages[] = $ups[$k];
  478. $included_usepackages[] = $v;
  479. }
  480. }
  481. array_unique($additional_usepackages);
  482. $tex = preg_replace("/\n\s*\\\\usepackage([^{}]*)(?<R>{((?:[^{}]+|(?&R))*)})/i","",$tex);
  483. $tex = preg_replace("/^\s*\\\\usepackage([^{}]*)(?<R>{((?:[^{}]+|(?&R))*)})/i","",$tex);
  484. $newcommands = getnewcommands($tex);
  485. global $existing_commands;
  486. $rmcommands = array_intersect($newcommands,$existing_commands);
  487. foreach ($rmcommands as $rmc)
  488. {
  489. //$tex = preg_replace("/\n\s*\\\\newcommand([^{}]*)({\s*\\".$rmc."\s*}.*\n)/i","\n",$tex);
  490. }
  491. $matches = [];
  492. $tex = preg_replace("/\n\s*\\\\pgfplotsset\s*(?<R>{((?:[^{}]+|(?&R))*)})/i","",$tex);
  493. $tex = preg_replace("/\n\s*\\\\setlength{\s*\\\marginparwidth.*\n/i","\n",$tex);
  494. if (stripos($tex,"\appendices") !== false || stripos($tex,"\appendix") !== false)
  495. $tex = handle_appendix($tex);
  496. if (!str_starts_with($tex,"\\makeatletter\n\def\\relativepath{\\import@path}\n\\makeatother\n"))
  497. $tex = "\\makeatletter\n\def\\relativepath{\\import@path}\n\\makeatother\n" . $tex;
  498. file_put_contents($file,$tex);
  499. }
  500. }
  501. return;
  502. }
  503. function check_options($argv)
  504. {
  505. $options = [];
  506. foreach ($argv as $a)
  507. {
  508. if (str_starts_with($a,"-"))
  509. $options[$a] = 1;
  510. if ($a == "-n")
  511. $options["--no-overwrite"] = 1;
  512. }
  513. return $options;
  514. }
  515. function compile_check($papers,$precopy = false)
  516. {
  517. //array_shift($papers); weird...
  518. if ($precopy)
  519. $papers = array_combine($papers,$papers);
  520. foreach ($papers as $p => $f)
  521. {
  522. if (str_ends_with($f,".pdf"))
  523. {
  524. echo "======= Skipping PDF: $f =======\n";
  525. continue;
  526. }
  527. echo "======= Paper $p -> $f START =======\n";
  528. if ($precopy)
  529. {
  530. echo "$p\n";
  531. if (strpos($p,"/") === false || str_starts_with($p,".") || !is_dir(dirname($p)))
  532. continue;
  533. $f = basename($p);
  534. $p = dirname($p);
  535. }
  536. else
  537. {
  538. shell_exec("cd $p; latexmk -c 2>/dev/null; latexmk -C 2>/dev/null; rm -f *.bbl");
  539. }
  540. $str = shell_exec("cd $p; latexmk -latexoption=\"-shell-escape\" -g -pdf $f 2>&1");
  541. $lines = explode("\n",$str);
  542. $skip = true;
  543. $failed = false;
  544. foreach($lines as $l)
  545. {
  546. if (str_starts_with($l,"Latexmk: ====List of undefined refs and citations:"))
  547. $skip = false;
  548. if ($skip)
  549. continue;
  550. if (stripos($l,"fail") !== false)
  551. $failed = true;
  552. echo "$l\n";
  553. }
  554. if ($failed || user_consent("Please check the PDF file. Are there any problems with invalid references to figures, tables or with the bibliography?","--","--no-overwrite"))
  555. error_exit("The paper did not compile properly, please fix the errors next before continuing.");
  556. echo "======= Paper $p -> $f END =======\n";
  557. }
  558. }
  559. function init_kpse()
  560. {
  561. global $kpsefiles;
  562. $kpsepath = shell_exec("kpsepath tex");
  563. $kpsepath = explode(":",$kpsepath);
  564. foreach ($kpsepath as $k)
  565. {
  566. $k = str_replace(["!!","\n","///","//"],["","","/","/"],$k);
  567. if (str_starts_with($k,"."))
  568. continue;
  569. $found = null;
  570. if (is_dir($k))
  571. $found = rscandir($k,[".sty"]);
  572. if ($found != null)
  573. {
  574. for ($i = 0; $i < count($found); $i++)
  575. $found[$i] = basename($found[$i]);
  576. $kpsefiles = array_unique(array_merge($kpsefiles,$found));
  577. }
  578. }
  579. sort($kpsefiles);
  580. }
  581. check_software();
  582. $options = check_options($argv);
  583. if (isset($options["--help"]))
  584. print_help();
  585. echo "\n=== Step 1/$steps: Check Folders ===\n\n";
  586. [$targets,$texfiles,$sourcedirs] = check_folders($argv);
  587. echo "\n=== Step 2/$steps: Pre-Copy Compile Check ===\n\n";
  588. $targets_exist = true;
  589. foreach ($targets as $t)
  590. if (!is_dir($t))
  591. $targets_exist = false;
  592. if (isset($options["--no-compile-check"]) || $targets_exist)
  593. echo "Skipping...\n";
  594. else
  595. compile_check($argv,true);
  596. echo "\n=== Step 3/$steps: Copying Files ===\n\n";
  597. $papers = check_and_copy_folders($argv);
  598. echo "\n=== Step 4/$steps: Adjusting References (in *.bib *.tex *.tikz) ===\n\n";
  599. $bibresources = adjust_references($papers,[".bib",".tex",".tikz"]);
  600. echo "\n=== Step 5/$steps: Compile Check ===\n\n";
  601. if (isset($options["--no-compile-check"]))
  602. echo "Skipping...\n";
  603. else
  604. compile_check($papers);
  605. [$_t,$usepackages1] = getusepackages(file_get_contents("main.tex.php"));
  606. [$_t,$usepackages2] = getusepackages(file_get_contents("tugraz_defaults.sty"));
  607. global $included_usepackages;
  608. $included_usepackages = array_unique(array_merge($usepackages1, $usepackages2));
  609. sort($included_usepackages);
  610. $cmds1 = getnewcommands(file_get_contents("main.tex.php"));
  611. $cmds2 = getnewcommands(file_get_contents("tugraz_defaults.sty"));
  612. global $existing_commands;
  613. $existing_commands = array_unique(array_merge($cmds1, $cmds2));
  614. [$del,$mathops1] = getmathops(file_get_contents("main.tex.php"));
  615. [$del,$mathops2] = getmathops(file_get_contents("tugraz_defaults.sty"));
  616. global $existing_mathops;
  617. $existing_mathops = array_unique(array_merge($mathops1, $mathops2));
  618. echo "\n=== Step 5/$steps: Adjusting Papers (checking *.tex and *.tikz files) ===\n\n";
  619. adjust_papers($papers,[".tex",".tikz",".sty"]);
  620. init_kpse();
  621. foreach ($papers as $k => $v)
  622. {
  623. if (str_ends_with($papers[$k],".pdf"))
  624. $papers[$k] = 'main.tex';
  625. else
  626. {
  627. $stys = rscandir($k,[".sty"]);
  628. foreach ($stys as $styf)
  629. {
  630. $styfb = basename($styf);
  631. if (in_array($styfb,$kpsefiles) === false && !file_exists("./$styfb"))
  632. {
  633. echo "Copying $styf to ./$styfb...\n";
  634. copy($styf,"./$styfb");
  635. }
  636. }
  637. }
  638. }
  639. echo "\n=== Step 6/$steps: Generate main.tex ===\n\n";
  640. $thesis_type = user_prompt("Enter Thesis Type ","PhD Thesis");
  641. $thesis_title = user_prompt("Enter Thesis Title ","Security of TODO");
  642. $thesis_part1_title = user_prompt("Enter Introductory Part Title ","Introduction to the Security of TODO");
  643. $thesis_author = user_prompt("Enter Your Name ","Harry Potter");
  644. $thesis_date = user_prompt("Enter Prospective Defense Month", "July 1998");
  645. $thesis_institute = user_prompt("Enter Your Institute","Institute for Applied Information Processing and Communications");
  646. $thesis_assessors = user_prompt("Enter Names of your Assessors (comma-separated)","Severus Snape, Minerva McGonagall");
  647. $num_publications_in_thesis = count($papers);
  648. $num_publications = user_prompt("How many publications did you co-author during your PhD? (6 is the absolute minimum for a cumulative thesis)","6");
  649. $sloppy_begin = "";
  650. $sloppy_end = "";
  651. if (!isset($options["--no-sloppy"]))
  652. {
  653. $sloppy_begin = '\begin{sloppypar}';
  654. $sloppy_end = '\end{sloppypar}';
  655. }
  656. ob_start();
  657. require "main.tex.php";
  658. $maintex_content = ob_get_contents();
  659. ob_end_clean();
  660. if (!file_exists("main.tex") || user_consent("main.tex already exists. overwrite?"))
  661. file_put_contents("main.tex",$maintex_content);
  662. if (!file_exists("mypreamble.sty") || user_consent("mypreamble.sty already exists... overwrite?","--force-overwrite","--no-overwrite"))
  663. file_put_contents("mypreamble.sty","\ProvidesPackage{mypreamble}\n\n".implode("\n",$additional_usepackages)."\n\n".$preamble);
  664. @mkdir("tikz");
  665. if (!file_exists("abstract.tex"))
  666. file_put_contents("abstract.tex","");
  667. if (!file_exists("intro.tex"))
  668. file_put_contents("intro.tex","");
  669. if (!file_exists("main.bib"))
  670. file_put_contents("main.bib",'@inproceedings{Kocher2019,
  671. author = {Paul Kocher and Jann Horn and Anders Fogh and Daniel Genkin and Daniel Gruss and Werner Haas and Mike Hamburg and Moritz Lipp and Stefan Mangard and Thomas Prescher and Michael Schwarz and Yuval Yarom},
  672. booktitle = {S\&P},
  673. title = {{Spectre Attacks: Exploiting Speculative Execution}},
  674. year = {2019}
  675. }');
  676. if (isset($options["--cv"]))
  677. {
  678. if (!file_exists("cv.bib"))
  679. file_put_contents("cv.bib","");
  680. if (!file_exists("cv.tex"))
  681. file_put_contents("cv.tex","This is my CV! Thanks for checking it out!");
  682. }
  683. ob_start();
  684. require "cover1.tex.php";
  685. $covertex_content = ob_get_contents();
  686. ob_end_clean();
  687. if (!file_exists("cover1.tex") || user_consent("cover1.tex already exists. overwrite?"))
  688. file_put_contents("cover1.tex",$covertex_content);
  689. shell_exec('latexmk -latexoption="-shell-escape" -g -pdf cover1.tex 1>/dev/null 2>/dev/null');
  690. ob_start();
  691. require "cover2.tex.php";
  692. $covertex_content = ob_get_contents();
  693. ob_end_clean();
  694. if (!file_exists("cover2.tex") || user_consent("cover2.tex already exists. overwrite?"))
  695. file_put_contents("cover2.tex",$covertex_content);
  696. shell_exec('latexmk -latexoption="-shell-escape" -g -pdf cover2.tex 1>/dev/null 2>/dev/null');
  697. echo "=== done ===\nNext step, run this command:\nlatexmk -latexoption=\"-shell-escape\" -g -pdf main.tex\n";
  698. ?>