hotpotatoes.lib.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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 $base_work_dir 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 $fname File name
  43. * @param string $fpath 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 $path File path
  68. * @param string $courseCode (if not given, the course will be taken from the context)
  69. * @return string Comment from the database record
  70. * Added conditional to the table if is empty.
  71. */
  72. function GetComment($path, $courseCode = '')
  73. {
  74. $dbTable = Database::get_course_table(TABLE_DOCUMENT);
  75. $course_info = api_get_course_info($courseCode);
  76. $path = Database::escape_string($path);
  77. if (!empty($course_info) && !empty($path)) {
  78. $query = "SELECT comment FROM $dbTable WHERE c_id = {$course_info['real_id']}";
  79. $result = Database::query($query);
  80. while ($row = Database::fetch_array($result)) {
  81. return $row[0];
  82. }
  83. }
  84. return null;
  85. }
  86. /**
  87. * Sets the comment in the database for a particular path.
  88. * @param string $path File path
  89. * @param string $comment Comment to set
  90. * @return Doctrine\DBAL\Driver\Statement|null Result of the database operation (Database::query will output some message directly on error anyway)
  91. */
  92. function SetComment($path, $comment)
  93. {
  94. $dbTable = Database::get_course_table(TABLE_DOCUMENT);
  95. $path = Database::escape_string($path);
  96. $comment = Database::escape_string($comment);
  97. $course_id = api_get_course_int_id();
  98. $query = "UPDATE $dbTable SET comment = '$comment'
  99. WHERE $course_id AND path = '$path'";
  100. $result = Database::query($query);
  101. return $result;
  102. }
  103. /**
  104. * Reads the file contents into a string.
  105. * @param string $full_file_path Urlencoded 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 $full_file_path Urlencoded path
  128. * @param string $content 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. $fp = fopen(urldecode($full_file_path), 'w');
  144. if ($fp !== false) {
  145. fwrite($fp, $content);
  146. fclose($fp);
  147. return true;
  148. }
  149. }
  150. return false;
  151. }
  152. /**
  153. * Gets the name of an img whose path is given (without directories or extensions).
  154. * @param string $imageTag An image tag (<img src="...." ...>)
  155. * @return string The image file name or an empty string
  156. */
  157. function GetImgName($imageTag)
  158. {
  159. // Select src tag from img tag.
  160. $match = array();
  161. //preg_match('/(src=(["\'])1.*(["\'])1)/i', $imageTag, $match); //src
  162. preg_match('/src(\s)*=(\s)*[\'"]([^\'"]*)[\'"]/i', $imageTag, $match); //get the img src as contained between " or '
  163. //list($key, $srctag) = each($match);
  164. $src = $match[3];
  165. //$src = substr($srctag, 5, (strlen($srctag) - 7));
  166. if (stristr($src, 'http') === false) {
  167. // Valid or invalid image name.
  168. if ($src == '') {
  169. return '';
  170. } else {
  171. $tmp_src = basename($src);
  172. if ($tmp_src == '') {
  173. return $src;
  174. } else {
  175. return $tmp_src;
  176. }
  177. }
  178. } else {
  179. // The img tag contained "http", which means it is probably external. Ignore it.
  180. return '';
  181. }
  182. }
  183. /**
  184. * Gets the source path of an image tag.
  185. * @param string $imageTag An image tag
  186. * @return string The image source or ""
  187. */
  188. function GetSrcName($imageTag)
  189. {
  190. // Select src tag from img tag.
  191. $match = array();
  192. preg_match("|(src=\".*\" )|U", $imageTag, $match); //src
  193. list(, $srctag) = each($match);
  194. $src = substr($srctag, 5, (strlen($srctag) - 7));
  195. if (stristr($src, 'http') === false) {
  196. // valid or invalid image name
  197. return $src;
  198. } else {
  199. return '';
  200. }
  201. }
  202. /**
  203. * Gets the image parameters from an image path.
  204. * @param string $fname File name
  205. * @param string $fpath File path
  206. * @param array $imgparams Reference to a list of image parameters (emptied, then used to return results)
  207. * @param int $imgcount Reference to a counter of images (emptied, then used to return results)
  208. */
  209. function GetImgParams($fname, $fpath, &$imgparams, &$imgcount)
  210. {
  211. // Select img tags from context.
  212. $imgparams = array();
  213. //phpinfo();
  214. $contents = ReadFileCont("$fpath"."$fname");
  215. $matches = array();
  216. preg_match_all('(<img .*>)', $contents, $matches);
  217. $imgcount = 0;
  218. while (list(, $match) = each($matches)) {
  219. // Each match consists of a key and a value.
  220. while (list(, $imageTag) = each($match)) {
  221. $imgname = GetImgName($imageTag);
  222. if ($imgname != '' && !in_array($imgname, $imgparams)) {
  223. array_push($imgparams, $imgname); // name (+ type) of the images in the html test
  224. $imgcount = $imgcount + 1; // number of images in the html test
  225. }
  226. }
  227. }
  228. }
  229. /**
  230. * Generates a list of hidden fields with the image params given as parameter to this function.
  231. * @param array $imgparams List of image parameters
  232. * @return string String containing the hidden parameters built from the list given
  233. */
  234. function GenerateHiddenList($imgparams)
  235. {
  236. $list = '';
  237. if (is_array($imgparams)) {
  238. while (list(, $string) = each($imgparams)) {
  239. $list .= "<input type=\"hidden\" name=\"imgparams[]\" value=\"$string\" />\n";
  240. }
  241. }
  242. return $list;
  243. }
  244. /**
  245. * Searches for a node in the given array.
  246. * @param array $array Reference to the array to search
  247. * @param string $node Node we are looking for in the array
  248. * @return mixed Node name or false if not found
  249. */
  250. function myarraysearch(&$array, $node)
  251. {
  252. $match = false;
  253. $tmp_array = array();
  254. for ($i = 0; $i < count($array); $i++) {
  255. if (!strcmp($array[$i], $node)) {
  256. $match = $node;
  257. } else {
  258. array_push($tmp_array, $array[$i]);
  259. }
  260. }
  261. $array = $tmp_array;
  262. return $match;
  263. }
  264. /**
  265. * Searches an image name into an array.
  266. * @param array $imgparams Reference to an array to search
  267. * @param string $string String to look for
  268. * @return mixed String given if found, false otherwise
  269. * @uses myarraysearch This function is just an additional layer on the myarraysearch() function
  270. */
  271. function CheckImageName(&$imgparams, $string)
  272. {
  273. $checked = myarraysearch($imgparams, $string);
  274. return $checked;
  275. }
  276. /**
  277. * Replaces an image tag by ???
  278. * @param string $content The content to replace
  279. * @return string The modified content
  280. */
  281. function ReplaceImgTag($content)
  282. {
  283. $newcontent = $content;
  284. $matches = array();
  285. preg_match_all('(<img .*>)', $content, $matches);
  286. while (list(, $match) = each($matches)) {
  287. while (list(, $imageTag) = each($match)) {
  288. $imgname = GetSrcName($imageTag);
  289. if ($imgname != '') {
  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 $name Original folder name
  301. * @param integer $nsize Length to reach
  302. * @return string Modified folder name
  303. */
  304. function FillFolderName($name, $nsize)
  305. {
  306. $str = '';
  307. for ($i = 0; $i < $nsize - strlen($name); $i++) {
  308. $str .= '0';
  309. }
  310. $str .= $name;
  311. return $str;
  312. }
  313. /**
  314. * Generates the HotPotato folder tree.
  315. * @param string $folder Folder path
  316. * @return string Folder name (modified)
  317. */
  318. function GenerateHpFolder($folder)
  319. {
  320. $filelist = array();
  321. if ($dir = @opendir($folder)) {
  322. while (($file = readdir($dir)) !== false) {
  323. if ($file != '.') {
  324. if ($file != '..') {
  325. $full_name = $folder.'/'.$file;
  326. if (is_dir($full_name)) {
  327. $filelist[] = $file;
  328. }
  329. }
  330. }
  331. }
  332. }
  333. $name = '';
  334. $w = true;
  335. while ($w == true) {
  336. $name = FillFolderName(mt_rand(1, 99999), 6);
  337. $checked = myarraysearch($filelist, $name);
  338. // As long as we find the name in the array, continue looping. As soon as we have a new element, quit.
  339. if (!$checked) {
  340. $w = false;
  341. }
  342. }
  343. return $name;
  344. }
  345. /**
  346. * Gets the folder name (strips down path).
  347. * @param string $fname Path
  348. * @return string Folder name stripped down
  349. */
  350. function GetFolderName($fname)
  351. {
  352. $name = explode('/', $fname);
  353. $name = $name[sizeof($name) - 2];
  354. return $name;
  355. }
  356. /**
  357. * Gets the folder path (with out the name of the folder itself) ?
  358. * @param string $fname Path
  359. * @return string Path stripped down
  360. */
  361. function GetFolderPath($fname)
  362. {
  363. $str = '';
  364. $name = explode('/', $fname);
  365. for ($i = 0; $i < sizeof($name) - 1; $i++) {
  366. $str = $str.$name[$i].'/';
  367. }
  368. return $str;
  369. }
  370. /**
  371. * Checks if there are subfolders.
  372. * @param string $path Path
  373. * @return integer 1 if a subfolder was found, 0 otherwise
  374. */
  375. function CheckSubFolder($path)
  376. {
  377. $folder = GetFolderPath($path);
  378. $dflag = 0;
  379. if ($dir = @opendir($folder)) {
  380. while (($file = readdir($dir)) !== false) {
  381. if ($file != '.') {
  382. if ($file != '..') {
  383. $full_name = $folder.'/'.$file;
  384. if (is_dir($full_name)) {
  385. $dflag = 1; // first directory
  386. }
  387. }
  388. }
  389. }
  390. }
  391. return $dflag;
  392. }
  393. /**
  394. * Hotpotato Garbage Collector
  395. * @param string $folder Path
  396. * @param integer $flag Flag
  397. * @param integer $user_id User id
  398. * @return void No return value, but echoes results
  399. */
  400. function HotPotGCt($folder, $flag, $user_id)
  401. {
  402. // Garbage Collector
  403. $filelist = array();
  404. if ($dir = @opendir($folder)) {
  405. while (($file = readdir($dir)) !== false) {
  406. if ($file != '.') {
  407. if ($file != '..') {
  408. $full_name = $folder.'/'.$file;
  409. if (is_dir($full_name)) {
  410. HotPotGCt($folder.'/'.$file, $flag, $user_id);
  411. } else {
  412. $filelist[] = $file;
  413. }
  414. }
  415. }
  416. }
  417. closedir($dir);
  418. }
  419. while (list(, $val) = each($filelist)) {
  420. if (stristr($val, $user_id.'.t.html')) {
  421. if ($flag == 1) {
  422. my_delete($folder.'/'.$val);
  423. } else {
  424. echo $folder.'/'.$val.'<br />';
  425. }
  426. }
  427. }
  428. }
  429. /**
  430. * Deletes an attempt from TABLE_STATISTIC_TRACK_E_HOTPOTATOES
  431. * @param int $id
  432. */
  433. function deleteAttempt($id)
  434. {
  435. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
  436. $id = intval($id);
  437. $sql = "DELETE FROM $table WHERE id = $id";
  438. Database::query($sql);
  439. }