hotpotatoes.lib.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Code library for HotPotatoes integration.
  5. *
  6. * @package chamilo.exercise
  7. *
  8. * @author Istvan Mandak (original author)
  9. */
  10. /* TODO: This is a global variable with too simple name, conflicts are possible.
  11. Better eliminate it. Correct the test unit too. */
  12. $dbTable = Database::get_course_table(TABLE_DOCUMENT);
  13. /**
  14. * Creates a hotpotato directory.
  15. *
  16. * If a directory of that name already exists, don't create any.
  17. * If a file of that name exists, remove it and create a directory.
  18. *
  19. * @param string $base_work_dir Wanted path
  20. *
  21. * @return bool Always true so far
  22. */
  23. function hotpotatoes_init($base_work_dir)
  24. {
  25. //global $_course, $_user;
  26. $document_path = $base_work_dir.'/';
  27. if (!is_dir($document_path)) {
  28. if (is_file($document_path)) {
  29. @unlink($document_path);
  30. }
  31. @mkdir($document_path, api_get_permissions_for_new_directories());
  32. return true;
  33. } else {
  34. return false;
  35. }
  36. //why create a .htaccess here?
  37. //if (!is_file($document_path.".htacces"))
  38. //{
  39. // if (!($fp = fopen($document_path.".htaccess", "w"))) {
  40. // }
  41. // $str = "order deny,allow\nallow from all";
  42. // if (!fwrite($fp,$str)) { }
  43. //}
  44. }
  45. /**
  46. * Gets the title of the quiz file given as parameter.
  47. *
  48. * @param string $fname File name
  49. * @param string $fpath File path
  50. *
  51. * @return string The exercise title
  52. */
  53. function GetQuizName($fname, $fpath)
  54. {
  55. $title = GetComment($fname);
  56. if (trim($title) == '') {
  57. if (file_exists($fpath.$fname)) {
  58. if (!($fp = @fopen($fpath.$fname, 'r'))) {
  59. //die('Could not open Quiz input.');
  60. return basename($fname);
  61. }
  62. $contents = @fread($fp, filesize($fpath.$fname));
  63. @fclose($fp);
  64. $title = api_get_title_html($contents);
  65. }
  66. }
  67. if ($title == '') {
  68. $title = basename($fname);
  69. }
  70. return (string) $title;
  71. }
  72. /**
  73. * Gets the comment about a file from the corresponding database record.
  74. *
  75. * @param string $path File path
  76. * @param string $courseCode (if not given, the course will be taken from the context)
  77. *
  78. * @return string comment from the database record
  79. * Added conditional to the table if is empty
  80. */
  81. function GetComment($path, $courseCode = '')
  82. {
  83. $dbTable = Database::get_course_table(TABLE_DOCUMENT);
  84. $course_info = api_get_course_info($courseCode);
  85. $path = Database::escape_string($path);
  86. if (!empty($course_info) && !empty($path)) {
  87. $query = "SELECT comment FROM $dbTable WHERE c_id = {$course_info['real_id']}";
  88. $result = Database::query($query);
  89. while ($row = Database::fetch_array($result)) {
  90. return $row[0];
  91. }
  92. }
  93. return null;
  94. }
  95. /**
  96. * Sets the comment in the database for a particular path.
  97. *
  98. * @param string $path File path
  99. * @param string $comment Comment to set
  100. *
  101. * @return Doctrine\DBAL\Driver\Statement|null
  102. * Result of the database operation
  103. * (Database::query will output some message directly on error anyway)
  104. */
  105. function SetComment($path, $comment)
  106. {
  107. $dbTable = Database::get_course_table(TABLE_DOCUMENT);
  108. $path = Database::escape_string($path);
  109. $comment = Database::escape_string($comment);
  110. $course_id = api_get_course_int_id();
  111. $query = "UPDATE $dbTable SET comment = '$comment'
  112. WHERE $course_id AND path = '$path'";
  113. $result = Database::query($query);
  114. return $result;
  115. }
  116. /**
  117. * Reads the file contents into a string.
  118. *
  119. * @param string $full_file_path Urlencoded path
  120. *
  121. * @return string The file contents or false on security error
  122. */
  123. function ReadFileCont($full_file_path)
  124. {
  125. if (empty($full_file_path)) {
  126. return false;
  127. }
  128. if (Security::check_abs_path(dirname($full_file_path).'/', api_get_path(SYS_COURSE_PATH))) {
  129. if (is_file($full_file_path)) {
  130. if (!($fp = fopen(urldecode($full_file_path), 'r'))) {
  131. return '';
  132. }
  133. $contents = fread($fp, filesize($full_file_path));
  134. fclose($fp);
  135. return $contents;
  136. }
  137. }
  138. return false;
  139. }
  140. /**
  141. * Writes the file contents into the given file path.
  142. *
  143. * @param string $full_file_path Urlencoded path
  144. * @param string $content The file contents
  145. *
  146. * @return bool True on success, false on security error
  147. */
  148. function WriteFileCont($full_file_path, $content)
  149. {
  150. // Check if this is not an attack, trying to get into other directories or something like that.
  151. $_course = api_get_course_info();
  152. if (Security::check_abs_path(
  153. dirname($full_file_path).'/',
  154. api_get_path(SYS_COURSE_PATH).$_course['path'].'/'
  155. )) {
  156. // Check if this is not an attack, trying to upload a php file or something like that.
  157. if (basename($full_file_path) != Security::filter_filename(basename($full_file_path))) {
  158. return false;
  159. }
  160. //if (!($fp = fopen(urldecode($full_file_path), 'w'))) {
  161. //die('Could not open Quiz input.');
  162. //}
  163. $fp = fopen(urldecode($full_file_path), 'w');
  164. if ($fp !== false) {
  165. fwrite($fp, $content);
  166. fclose($fp);
  167. return true;
  168. }
  169. }
  170. return false;
  171. }
  172. /**
  173. * Gets the name of an img whose path is given (without directories or extensions).
  174. *
  175. * @param string $imageTag An image tag (<img src="...." ...>)
  176. *
  177. * @return string The image file name or an empty string
  178. */
  179. function GetImgName($imageTag)
  180. {
  181. // Select src tag from img tag.
  182. $match = [];
  183. //preg_match('/(src=(["\'])1.*(["\'])1)/i', $imageTag, $match); //src
  184. preg_match('/src(\s)*=(\s)*[\'"]([^\'"]*)[\'"]/i', $imageTag, $match); //get the img src as contained between " or '
  185. //list($key, $srctag) = each($match);
  186. $src = $match[3];
  187. //$src = substr($srctag, 5, (strlen($srctag) - 7));
  188. if (stristr($src, 'http') === false) {
  189. // Valid or invalid image name.
  190. if ($src == '') {
  191. return '';
  192. } else {
  193. $tmp_src = basename($src);
  194. if ($tmp_src == '') {
  195. return $src;
  196. } else {
  197. return $tmp_src;
  198. }
  199. }
  200. } else {
  201. // The img tag contained "http", which means it is probably external. Ignore it.
  202. return '';
  203. }
  204. }
  205. /**
  206. * Gets the source path of an image tag.
  207. *
  208. * @param string $imageTag An image tag
  209. *
  210. * @return string The image source or ""
  211. */
  212. function GetSrcName($imageTag)
  213. {
  214. // Select src tag from img tag.
  215. $match = [];
  216. preg_match("|(src=\".*\" )|U", $imageTag, $match); //src
  217. $srctag = reset($match);
  218. $src = substr($srctag, 5, (strlen($srctag) - 7));
  219. if (stristr($src, 'http') === false) {
  220. // valid or invalid image name
  221. return $src;
  222. } else {
  223. return '';
  224. }
  225. }
  226. /**
  227. * Gets the image parameters from an image path.
  228. *
  229. * @param string $fname File name
  230. * @param string $fpath File path
  231. * @param array $imgparams Reference to a list of image parameters (emptied, then used to return results)
  232. * @param int $imgcount Reference to a counter of images (emptied, then used to return results)
  233. */
  234. function GetImgParams($fname, $fpath, &$imgparams, &$imgcount)
  235. {
  236. // Select img tags from context.
  237. $imgparams = [];
  238. //phpinfo();
  239. $contents = ReadFileCont("$fpath"."$fname");
  240. $matches = [];
  241. preg_match_all('(<img .*>)', $contents, $matches);
  242. $imgcount = 0;
  243. foreach ($matches as $match) {
  244. // Each match consists of a key and a value.
  245. foreach ($match as $imageTag) {
  246. $imgname = GetImgName($imageTag);
  247. if ($imgname != '' && !in_array($imgname, $imgparams)) {
  248. array_push($imgparams, $imgname); // name (+ type) of the images in the html test
  249. $imgcount = $imgcount + 1; // number of images in the html test
  250. }
  251. }
  252. }
  253. }
  254. /**
  255. * Generates a list of hidden fields with the image params given as parameter to this function.
  256. *
  257. * @param array $imgparams List of image parameters
  258. *
  259. * @return string String containing the hidden parameters built from the list given
  260. */
  261. function GenerateHiddenList($imgparams)
  262. {
  263. $list = '';
  264. if (is_array($imgparams)) {
  265. foreach ($imgparams as $string) {
  266. $list .= "<input type=\"hidden\" name=\"imgparams[]\" value=\"$string\" />\n";
  267. }
  268. }
  269. return $list;
  270. }
  271. /**
  272. * Searches for a node in the given array.
  273. *
  274. * @param array $array Reference to the array to search
  275. * @param string $node Node we are looking for in the array
  276. *
  277. * @return mixed Node name or false if not found
  278. */
  279. function myarraysearch(&$array, $node)
  280. {
  281. $match = false;
  282. $tmp_array = [];
  283. for ($i = 0; $i < count($array); $i++) {
  284. if (!strcmp($array[$i], $node)) {
  285. $match = $node;
  286. } else {
  287. array_push($tmp_array, $array[$i]);
  288. }
  289. }
  290. $array = $tmp_array;
  291. return $match;
  292. }
  293. /**
  294. * Searches an image name into an array.
  295. *
  296. * @param array $imgparams Reference to an array to search
  297. * @param string $string String to look for
  298. *
  299. * @return mixed String given if found, false otherwise
  300. *
  301. * @uses \myarraysearch This function is just an additional layer on the myarraysearch() function
  302. */
  303. function CheckImageName(&$imgparams, $string)
  304. {
  305. $checked = myarraysearch($imgparams, $string);
  306. return $checked;
  307. }
  308. /**
  309. * Replaces an image tag by ???
  310. *
  311. * @param string $content The content to replace
  312. *
  313. * @return string The modified content
  314. */
  315. function ReplaceImgTag($content)
  316. {
  317. $newcontent = $content;
  318. $matches = [];
  319. preg_match_all('(<img .*>)', $content, $matches);
  320. foreach ($matches as $match) {
  321. foreach ($match as $imageTag) {
  322. $imgname = GetSrcName($imageTag);
  323. if ($imgname != '') {
  324. $prehref = $imgname;
  325. $posthref = basename($imgname);
  326. $newcontent = str_replace($prehref, $posthref, $newcontent);
  327. }
  328. }
  329. }
  330. return $newcontent;
  331. }
  332. /**
  333. * Fills the folder name up to a certain length with "0".
  334. *
  335. * @param string $name Original folder name
  336. * @param int $nsize Length to reach
  337. *
  338. * @return string Modified folder name
  339. */
  340. function FillFolderName($name, $nsize)
  341. {
  342. $str = '';
  343. for ($i = 0; $i < $nsize - strlen($name); $i++) {
  344. $str .= '0';
  345. }
  346. $str .= $name;
  347. return $str;
  348. }
  349. /**
  350. * Generates the HotPotato folder tree.
  351. *
  352. * @param string $folder Folder path
  353. *
  354. * @return string Folder name (modified)
  355. */
  356. function GenerateHpFolder($folder)
  357. {
  358. $filelist = [];
  359. if ($dir = @opendir($folder)) {
  360. while (($file = readdir($dir)) !== false) {
  361. if ($file != '.') {
  362. if ($file != '..') {
  363. $full_name = $folder.'/'.$file;
  364. if (is_dir($full_name)) {
  365. $filelist[] = $file;
  366. }
  367. }
  368. }
  369. }
  370. }
  371. $name = '';
  372. $w = true;
  373. while ($w == true) {
  374. $name = FillFolderName(mt_rand(1, 99999), 6);
  375. $checked = myarraysearch($filelist, $name);
  376. // As long as we find the name in the array, continue looping. As soon as we have a new element, quit.
  377. if (!$checked) {
  378. $w = false;
  379. }
  380. }
  381. return $name;
  382. }
  383. /**
  384. * Gets the folder name (strips down path).
  385. *
  386. * @param string $fname Path
  387. *
  388. * @return string Folder name stripped down
  389. */
  390. function GetFolderName($fname)
  391. {
  392. $name = explode('/', $fname);
  393. $name = $name[sizeof($name) - 2];
  394. return $name;
  395. }
  396. /**
  397. * Gets the folder path (with out the name of the folder itself) ?
  398. *
  399. * @param string $fname Path
  400. *
  401. * @return string Path stripped down
  402. */
  403. function GetFolderPath($fname)
  404. {
  405. $str = '';
  406. $name = explode('/', $fname);
  407. for ($i = 0; $i < sizeof($name) - 1; $i++) {
  408. $str = $str.$name[$i].'/';
  409. }
  410. return $str;
  411. }
  412. /**
  413. * Checks if there are subfolders.
  414. *
  415. * @param string $path Path
  416. *
  417. * @return int 1 if a subfolder was found, 0 otherwise
  418. */
  419. function CheckSubFolder($path)
  420. {
  421. $folder = GetFolderPath($path);
  422. $dflag = 0;
  423. if ($dir = @opendir($folder)) {
  424. while (($file = readdir($dir)) !== false) {
  425. if ($file != '.') {
  426. if ($file != '..') {
  427. $full_name = $folder.'/'.$file;
  428. if (is_dir($full_name)) {
  429. $dflag = 1; // first directory
  430. }
  431. }
  432. }
  433. }
  434. }
  435. return $dflag;
  436. }
  437. /**
  438. * Hotpotato Garbage Collector.
  439. *
  440. * @param string $folder Path
  441. * @param int $flag Flag
  442. * @param int $user_id User id
  443. */
  444. function HotPotGCt($folder, $flag, $user_id)
  445. {
  446. // Garbage Collector
  447. $filelist = [];
  448. if ($dir = @opendir($folder)) {
  449. while (($file = readdir($dir)) !== false) {
  450. if ($file != '.') {
  451. if ($file != '..') {
  452. $full_name = $folder.'/'.$file;
  453. if (is_dir($full_name)) {
  454. HotPotGCt($folder.'/'.$file, $flag, $user_id);
  455. } else {
  456. $filelist[] = $file;
  457. }
  458. }
  459. }
  460. }
  461. closedir($dir);
  462. }
  463. foreach ($filelist as $val) {
  464. if (stristr($val, $user_id.'.t.html')) {
  465. if ($flag == 1) {
  466. my_delete($folder.'/'.$val);
  467. } else {
  468. echo $folder.'/'.$val.'<br />';
  469. }
  470. }
  471. }
  472. }
  473. /**
  474. * Deletes an attempt from TABLE_STATISTIC_TRACK_E_HOTPOTATOES.
  475. *
  476. * @param int $id
  477. */
  478. function deleteAttempt($id)
  479. {
  480. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
  481. $id = intval($id);
  482. $sql = "DELETE FROM $table WHERE id = $id";
  483. Database::query($sql);
  484. }