generator.php 31 KB

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