hotpotatoes.lib.php 13 KB

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