hotpotatoes.lib.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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 Doctrine\DBAL\Driver\Statement|null Result of the database operation (Database::query will output some message directly on error anyway)
  90. */
  91. function SetComment($path, $comment)
  92. {
  93. $dbTable = Database::get_course_table(TABLE_DOCUMENT);
  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. * @param string $full_file_path
  106. * @return string The file contents or false on security error
  107. */
  108. function ReadFileCont($full_file_path)
  109. {
  110. if (empty($full_file_path)) {
  111. return false;
  112. }
  113. if (Security::check_abs_path(dirname($full_file_path).'/', api_get_path(SYS_COURSE_PATH))) {
  114. if (is_file($full_file_path)) {
  115. if (!($fp = fopen(urldecode($full_file_path), 'r'))) {
  116. return '';
  117. }
  118. $contents = fread($fp, filesize($full_file_path));
  119. fclose($fp);
  120. return $contents;
  121. }
  122. }
  123. return false;
  124. }
  125. /**
  126. * Writes the file contents into the given file path.
  127. * @param string Urlencoded path
  128. * @param string The file contents
  129. * @return boolean True on success, false on security error
  130. */
  131. function WriteFileCont($full_file_path, $content)
  132. {
  133. // Check if this is not an attack, trying to get into other directories or something like that.
  134. $_course = api_get_course_info();
  135. if (Security::check_abs_path(dirname($full_file_path).'/', api_get_path(SYS_COURSE_PATH).$_course['path'].'/')) {
  136. // Check if this is not an attack, trying to upload a php file or something like that.
  137. if (basename($full_file_path) != Security::filter_filename(basename($full_file_path))) {
  138. return false;
  139. }
  140. if (!($fp = fopen(urldecode($full_file_path), 'w'))) {
  141. //die('Could not open Quiz input.');
  142. }
  143. fwrite($fp, $content);
  144. fclose($fp);
  145. return true;
  146. }
  147. return false;
  148. }
  149. /**
  150. * Gets the name of an img whose path is given (without directories or extensions).
  151. * @param string An image tag (<img src="...." ...>)
  152. * @return string The image file name or an empty string
  153. */
  154. function GetImgName($imgtag)
  155. {
  156. // Select src tag from img tag.
  157. $match = array();
  158. //preg_match('/(src=(["\'])1.*(["\'])1)/i', $imgtag, $match); //src
  159. preg_match('/src(\s)*=(\s)*[\'"]([^\'"]*)[\'"]/i', $imgtag, $match); //get the img src as contained between " or '
  160. //list($key, $srctag) = each($match);
  161. $src = $match[3];
  162. //$src = substr($srctag, 5, (strlen($srctag) - 7));
  163. if (stristr($src, 'http') === false) {
  164. // Valid or invalid image name.
  165. if ($src == '') {
  166. return '';
  167. } else {
  168. $tmp_src = basename($src) ;
  169. if ($tmp_src == '') {
  170. return $src;
  171. } else {
  172. return $tmp_src;
  173. }
  174. }
  175. } else {
  176. // The img tag contained "http", which means it is probably external. Ignore it.
  177. return '';
  178. }
  179. }
  180. /**
  181. * Gets the source path of an image tag.
  182. * @param string An image tag
  183. * @return string The image source or ""
  184. */
  185. function GetSrcName($imgtag)
  186. {
  187. // Select src tag from img tag.
  188. $match = array();
  189. preg_match("|(src=\".*\" )|U", $imgtag, $match); //src
  190. list($key, $srctag) = each($match);
  191. $src = substr($srctag, 5, (strlen($srctag) - 7));
  192. if (stristr($src, 'http') === false) {
  193. // valid or invalid image name
  194. return $src;
  195. } else {
  196. return '';
  197. }
  198. }
  199. /**
  200. * Gets the image parameters from an image path.
  201. * @param string File name
  202. * @param string File path
  203. * @param reference Reference to a list of image parameters (emptied, then used to return results)
  204. * @param reference Reference to a counter of images (emptied, then used to return results)
  205. */
  206. function GetImgParams($fname, $fpath, &$imgparams, &$imgcount)
  207. {
  208. // Select img tags from context.
  209. $imgparams = array();
  210. //phpinfo();
  211. $contents = ReadFileCont("$fpath"."$fname");
  212. $matches = array();
  213. preg_match_all('(<img .*>)', $contents, $matches);
  214. $imgcount = 0;
  215. while (list($int, $match) = each($matches)) {
  216. // Each match consists of a key and a value.
  217. while (list($key, $imgtag) = each($match)) {
  218. $imgname = GetImgName($imgtag);
  219. if ($imgname != '' && !in_array($imgname, $imgparams)) {
  220. array_push($imgparams, $imgname); // name (+ type) of the images in the html test
  221. $imgcount = $imgcount + 1; // number of images in the html test
  222. }
  223. }
  224. }
  225. }
  226. /**
  227. * Generates a list of hidden fields with the image params given as parameter to this function.
  228. * @param array List of image parameters
  229. * @return string String containing the hidden parameters built from the list given
  230. */
  231. function GenerateHiddenList($imgparams)
  232. {
  233. $list = '';
  234. if (is_array($imgparams)) {
  235. while (list($int, $string) = each($imgparams)) {
  236. $list .= "<input type=\"hidden\" name=\"imgparams[]\" value=\"$string\" />\n";
  237. }
  238. }
  239. return $list;
  240. }
  241. /**
  242. * Searches for a node in the given array.
  243. * @param reference Reference to the array to search
  244. * @param string Node we are looking for in the array
  245. * @param string $node
  246. * @return mixed Node name or false if not found
  247. */
  248. function myarraysearch(&$array, $node)
  249. {
  250. $match = false;
  251. $tmp_array = array();
  252. for ($i = 0; $i < count($array); $i++) {
  253. if (!strcmp($array[$i], $node)) {
  254. $match = $node;
  255. } else {
  256. array_push($tmp_array, $array[$i]);
  257. }
  258. }
  259. $array = $tmp_array;
  260. return $match;
  261. }
  262. /**
  263. * Searches an image name into an array.
  264. * @param reference Reference to an array to search
  265. * @param string String to look for
  266. * @return mixed String given if found, false otherwise
  267. * @uses myarraysearch This function is just an additional layer on the myarraysearch() function
  268. */
  269. function CheckImageName(&$imgparams, $string)
  270. {
  271. $checked = myarraysearch($imgparams, $string);
  272. return $checked;
  273. }
  274. /**
  275. * Replaces an image tag by ???
  276. * @param string The content to replace
  277. * @return string The modified content
  278. */
  279. function ReplaceImgTag($content)
  280. {
  281. $newcontent = $content;
  282. $matches = array();
  283. preg_match_all('(<img .*>)', $content, $matches);
  284. while (list($int, $match) = each($matches)) {
  285. while (list($key, $imgtag) = each($match)) {
  286. $imgname = GetSrcName($imgtag);
  287. if ($imgname == '') {
  288. // Valid or invalid image name.
  289. } else {
  290. $prehref = $imgname;
  291. $posthref = basename($imgname);
  292. $newcontent = str_replace($prehref, $posthref, $newcontent);
  293. }
  294. }
  295. }
  296. return $newcontent;
  297. }
  298. /**
  299. * Fills the folder name up to a certain length with "0".
  300. * @param string Original folder name
  301. * @param integer Length to reach
  302. * @param integer $name
  303. * @param integer $nsize
  304. * @return string Modified folder name
  305. */
  306. function FillFolderName($name, $nsize)
  307. {
  308. $str = '';
  309. for ($i = 0; $i < $nsize - strlen($name); $i++) {
  310. $str .= '0';
  311. }
  312. $str .= $name;
  313. return $str;
  314. }
  315. /**
  316. * Generates the HotPotato folder tree.
  317. * @param string Folder path
  318. * @return string Folder name (modified)
  319. */
  320. function GenerateHpFolder($folder)
  321. {
  322. $filelist = array();
  323. if ($dir = @opendir($folder)) {
  324. while (($file = readdir($dir)) !== false) {
  325. if ($file != '.') {
  326. if ($file != '..') {
  327. $full_name = $folder.'/'.$file;
  328. if (is_dir($full_name)) {
  329. $filelist[] = $file;
  330. }
  331. }
  332. }
  333. }
  334. }
  335. $w = 0;
  336. do {
  337. $name = FillFolderName(mt_rand(1, 99999), 6);
  338. $checked = myarraysearch($filelist, $name);
  339. // As long as we find the name in the array, continue looping. As soon as we have a new element, quit.
  340. if ($checked) {
  341. $w = 1;
  342. } else {
  343. $w = 0;
  344. }
  345. } while ($w == 1);
  346. return $name;
  347. }
  348. /**
  349. * Gets the folder name (strips down path).
  350. * @param string Path
  351. * @return string Folder name stripped down
  352. */
  353. function GetFolderName($fname)
  354. {
  355. $name = explode('/', $fname);
  356. $name = $name[sizeof($name) - 2];
  357. return $name;
  358. }
  359. /**
  360. * Gets the folder path (with out the name of the folder itself) ?
  361. * @param string Path
  362. * @return string Path stripped down
  363. */
  364. function GetFolderPath($fname)
  365. {
  366. $str = '';
  367. $name = explode('/', $fname);
  368. for ($i = 0; $i < sizeof($name) - 1; $i++) {
  369. $str = $str.$name[$i].'/';
  370. }
  371. return $str;
  372. }
  373. /**
  374. * Checks if there are subfolders.
  375. * @param string Path
  376. * @return integer 1 if a subfolder was found, 0 otherwise
  377. */
  378. function CheckSubFolder($path)
  379. {
  380. $folder = GetFolderPath($path);
  381. $dflag = 0;
  382. if ($dir = @opendir($folder)) {
  383. while (($file = readdir($dir)) !== false) {
  384. if ($file != '.') {
  385. if ($file != '..') {
  386. $full_name = $folder.'/'.$file;
  387. if (is_dir($full_name)) {
  388. $dflag = 1; // first directory
  389. }
  390. }
  391. }
  392. }
  393. }
  394. return $dflag;
  395. }
  396. /**
  397. * Hotpotato Garbage Collector
  398. * @param string Path
  399. * @param integer Flag
  400. * @param integer User id
  401. * @return void No return value, but echoes results
  402. */
  403. function HotPotGCt($folder, $flag, $user_id)
  404. {
  405. // Garbage Collector
  406. $filelist = array();
  407. if ($dir = @opendir($folder)) {
  408. while (($file = readdir($dir)) !== false) {
  409. if ($file != '.') {
  410. if ($file != '..') {
  411. $full_name = $folder.'/'.$file;
  412. if (is_dir($full_name)) {
  413. HotPotGCt($folder.'/'.$file, $flag, $user_id);
  414. } else {
  415. $filelist[] = $file;
  416. }
  417. }
  418. }
  419. }
  420. closedir($dir);
  421. }
  422. while (list($key, $val) = each($filelist)) {
  423. if (stristr($val, $user_id.'.t.html')) {
  424. if ($flag == 1) {
  425. my_delete($folder.'/'.$val);
  426. } else {
  427. echo $folder.'/'.$val.'<br />';
  428. }
  429. }
  430. }
  431. }
  432. /**
  433. * Deletes an attempt from TABLE_STATISTIC_TRACK_E_HOTPOTATOES
  434. * @param int $id
  435. */
  436. function deleteAttempt($id)
  437. {
  438. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
  439. $id = intval($id);
  440. $sql = "DELETE FROM $table WHERE id = $id";
  441. Database::query($sql);
  442. }