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.
  15. * If a file of that name exists, remove it and create a directory.
  16. * @param string $base_work_dir Wanted path
  17. * @return boolean Always true so far
  18. */
  19. function hotpotatoes_init($base_work_dir)
  20. {
  21. //global $_course, $_user;
  22. $document_path = $base_work_dir.'/';
  23. if (!is_dir($document_path)) {
  24. if (is_file($document_path)) {
  25. @unlink($document_path);
  26. }
  27. @mkdir($document_path, api_get_permissions_for_new_directories());
  28. return true;
  29. } else {
  30. return false;
  31. }
  32. //why create a .htaccess here?
  33. //if (!is_file($document_path.".htacces"))
  34. //{
  35. // if (!($fp = fopen($document_path.".htaccess", "w"))) {
  36. // }
  37. // $str = "order deny,allow\nallow from all";
  38. // if (!fwrite($fp,$str)) { }
  39. //}
  40. }
  41. /**
  42. * Gets the title of the quiz file given as parameter.
  43. * @param string $fname File name
  44. * @param string $fpath File path
  45. * @return string The exercise title
  46. */
  47. function GetQuizName($fname, $fpath)
  48. {
  49. $title = GetComment($fname);
  50. if (trim($title) == '') {
  51. if (file_exists($fpath.$fname)) {
  52. if (!($fp = @fopen($fpath.$fname, 'r'))) {
  53. //die('Could not open Quiz input.');
  54. return basename($fname);
  55. }
  56. $contents = @fread($fp, filesize($fpath.$fname));
  57. @fclose($fp);
  58. $title = api_get_title_html($contents);
  59. }
  60. }
  61. if ($title == '') {
  62. $title = basename($fname);
  63. }
  64. return (string) $title;
  65. }
  66. /**
  67. * Gets the comment about a file from the corresponding database record.
  68. * @param string $path File path
  69. * @param string $courseCode (if not given, the course will be taken from the context)
  70. * @return string Comment from the database record
  71. * Added conditional to the table if is empty.
  72. */
  73. function GetComment($path, $courseCode = '')
  74. {
  75. $dbTable = Database::get_course_table(TABLE_DOCUMENT);
  76. $course_info = api_get_course_info($courseCode);
  77. $path = Database::escape_string($path);
  78. if (!empty($course_info) && !empty($path)) {
  79. $query = "SELECT comment FROM $dbTable WHERE c_id = {$course_info['real_id']}";
  80. $result = Database::query($query);
  81. while ($row = Database::fetch_array($result)) {
  82. return $row[0];
  83. }
  84. }
  85. return null;
  86. }
  87. /**
  88. * Sets the comment in the database for a particular path.
  89. * @param string $path File path
  90. * @param string $comment Comment to set
  91. * @return Doctrine\DBAL\Driver\Statement|null
  92. * Result of the database operation
  93. * (Database::query will output some message directly on error anyway)
  94. */
  95. function SetComment($path, $comment)
  96. {
  97. $dbTable = Database::get_course_table(TABLE_DOCUMENT);
  98. $path = Database::escape_string($path);
  99. $comment = Database::escape_string($comment);
  100. $course_id = api_get_course_int_id();
  101. $query = "UPDATE $dbTable SET comment = '$comment'
  102. WHERE $course_id AND path = '$path'";
  103. $result = Database::query($query);
  104. return $result;
  105. }
  106. /**
  107. * Reads the file contents into a string.
  108. * @param string $full_file_path Urlencoded path
  109. * @return string The file contents or false on security error
  110. */
  111. function ReadFileCont($full_file_path)
  112. {
  113. if (empty($full_file_path)) {
  114. return false;
  115. }
  116. if (Security::check_abs_path(dirname($full_file_path).'/', api_get_path(SYS_COURSE_PATH))) {
  117. if (is_file($full_file_path)) {
  118. if (!($fp = fopen(urldecode($full_file_path), 'r'))) {
  119. return '';
  120. }
  121. $contents = fread($fp, filesize($full_file_path));
  122. fclose($fp);
  123. return $contents;
  124. }
  125. }
  126. return false;
  127. }
  128. /**
  129. * Writes the file contents into the given file path.
  130. * @param string $full_file_path Urlencoded path
  131. * @param string $content The file contents
  132. * @return boolean True on success, false on security error
  133. */
  134. function WriteFileCont($full_file_path, $content)
  135. {
  136. // Check if this is not an attack, trying to get into other directories or something like that.
  137. $_course = api_get_course_info();
  138. if (Security::check_abs_path(dirname($full_file_path).'/', api_get_path(SYS_COURSE_PATH).$_course['path'].'/')) {
  139. // Check if this is not an attack, trying to upload a php file or something like that.
  140. if (basename($full_file_path) != Security::filter_filename(basename($full_file_path))) {
  141. return false;
  142. }
  143. //if (!($fp = fopen(urldecode($full_file_path), 'w'))) {
  144. //die('Could not open Quiz input.');
  145. //}
  146. $fp = fopen(urldecode($full_file_path), 'w');
  147. if ($fp !== false) {
  148. fwrite($fp, $content);
  149. fclose($fp);
  150. return true;
  151. }
  152. }
  153. return false;
  154. }
  155. /**
  156. * Gets the name of an img whose path is given (without directories or extensions).
  157. * @param string $imageTag An image tag (<img src="...." ...>)
  158. * @return string The image file name or an empty string
  159. */
  160. function GetImgName($imageTag)
  161. {
  162. // Select src tag from img tag.
  163. $match = array();
  164. //preg_match('/(src=(["\'])1.*(["\'])1)/i', $imageTag, $match); //src
  165. preg_match('/src(\s)*=(\s)*[\'"]([^\'"]*)[\'"]/i', $imageTag, $match); //get the img src as contained between " or '
  166. //list($key, $srctag) = each($match);
  167. $src = $match[3];
  168. //$src = substr($srctag, 5, (strlen($srctag) - 7));
  169. if (stristr($src, 'http') === false) {
  170. // Valid or invalid image name.
  171. if ($src == '') {
  172. return '';
  173. } else {
  174. $tmp_src = basename($src);
  175. if ($tmp_src == '') {
  176. return $src;
  177. } else {
  178. return $tmp_src;
  179. }
  180. }
  181. } else {
  182. // The img tag contained "http", which means it is probably external. Ignore it.
  183. return '';
  184. }
  185. }
  186. /**
  187. * Gets the source path of an image tag.
  188. * @param string $imageTag An image tag
  189. * @return string The image source or ""
  190. */
  191. function GetSrcName($imageTag)
  192. {
  193. // Select src tag from img tag.
  194. $match = array();
  195. preg_match("|(src=\".*\" )|U", $imageTag, $match); //src
  196. list(, $srctag) = each($match);
  197. $src = substr($srctag, 5, (strlen($srctag) - 7));
  198. if (stristr($src, 'http') === false) {
  199. // valid or invalid image name
  200. return $src;
  201. } else {
  202. return '';
  203. }
  204. }
  205. /**
  206. * Gets the image parameters from an image path.
  207. * @param string $fname File name
  208. * @param string $fpath File path
  209. * @param array $imgparams Reference to a list of image parameters (emptied, then used to return results)
  210. * @param int $imgcount Reference to a counter of images (emptied, then used to return results)
  211. */
  212. function GetImgParams($fname, $fpath, &$imgparams, &$imgcount)
  213. {
  214. // Select img tags from context.
  215. $imgparams = array();
  216. //phpinfo();
  217. $contents = ReadFileCont("$fpath"."$fname");
  218. $matches = array();
  219. preg_match_all('(<img .*>)', $contents, $matches);
  220. $imgcount = 0;
  221. while (list(, $match) = each($matches)) {
  222. // Each match consists of a key and a value.
  223. while (list(, $imageTag) = each($match)) {
  224. $imgname = GetImgName($imageTag);
  225. if ($imgname != '' && !in_array($imgname, $imgparams)) {
  226. array_push($imgparams, $imgname); // name (+ type) of the images in the html test
  227. $imgcount = $imgcount + 1; // number of images in the html test
  228. }
  229. }
  230. }
  231. }
  232. /**
  233. * Generates a list of hidden fields with the image params given as parameter to this function.
  234. * @param array $imgparams List of image parameters
  235. * @return string String containing the hidden parameters built from the list given
  236. */
  237. function GenerateHiddenList($imgparams)
  238. {
  239. $list = '';
  240. if (is_array($imgparams)) {
  241. while (list(, $string) = each($imgparams)) {
  242. $list .= "<input type=\"hidden\" name=\"imgparams[]\" value=\"$string\" />\n";
  243. }
  244. }
  245. return $list;
  246. }
  247. /**
  248. * Searches for a node in the given array.
  249. * @param array $array Reference to the array to search
  250. * @param string $node Node we are looking for in the array
  251. * @return mixed Node name or false if not found
  252. */
  253. function myarraysearch(&$array, $node)
  254. {
  255. $match = false;
  256. $tmp_array = array();
  257. for ($i = 0; $i < count($array); $i++) {
  258. if (!strcmp($array[$i], $node)) {
  259. $match = $node;
  260. } else {
  261. array_push($tmp_array, $array[$i]);
  262. }
  263. }
  264. $array = $tmp_array;
  265. return $match;
  266. }
  267. /**
  268. * Searches an image name into an array.
  269. * @param array $imgparams Reference to an array to search
  270. * @param string $string String to look for
  271. * @return mixed String given if found, false otherwise
  272. * @uses myarraysearch This function is just an additional layer on the myarraysearch() function
  273. */
  274. function CheckImageName(&$imgparams, $string)
  275. {
  276. $checked = myarraysearch($imgparams, $string);
  277. return $checked;
  278. }
  279. /**
  280. * Replaces an image tag by ???
  281. * @param string $content The content to replace
  282. * @return string The modified content
  283. */
  284. function ReplaceImgTag($content)
  285. {
  286. $newcontent = $content;
  287. $matches = array();
  288. preg_match_all('(<img .*>)', $content, $matches);
  289. while (list(, $match) = each($matches)) {
  290. while (list(, $imageTag) = each($match)) {
  291. $imgname = GetSrcName($imageTag);
  292. if ($imgname != '') {
  293. $prehref = $imgname;
  294. $posthref = basename($imgname);
  295. $newcontent = str_replace($prehref, $posthref, $newcontent);
  296. }
  297. }
  298. }
  299. return $newcontent;
  300. }
  301. /**
  302. * Fills the folder name up to a certain length with "0".
  303. * @param string $name Original folder name
  304. * @param integer $nsize Length to reach
  305. * @return string Modified folder name
  306. */
  307. function FillFolderName($name, $nsize)
  308. {
  309. $str = '';
  310. for ($i = 0; $i < $nsize - strlen($name); $i++) {
  311. $str .= '0';
  312. }
  313. $str .= $name;
  314. return $str;
  315. }
  316. /**
  317. * Generates the HotPotato folder tree.
  318. * @param string $folder Folder path
  319. * @return string Folder name (modified)
  320. */
  321. function GenerateHpFolder($folder)
  322. {
  323. $filelist = array();
  324. if ($dir = @opendir($folder)) {
  325. while (($file = readdir($dir)) !== false) {
  326. if ($file != '.') {
  327. if ($file != '..') {
  328. $full_name = $folder.'/'.$file;
  329. if (is_dir($full_name)) {
  330. $filelist[] = $file;
  331. }
  332. }
  333. }
  334. }
  335. }
  336. $name = '';
  337. $w = true;
  338. while ($w == true) {
  339. $name = FillFolderName(mt_rand(1, 99999), 6);
  340. $checked = myarraysearch($filelist, $name);
  341. // As long as we find the name in the array, continue looping. As soon as we have a new element, quit.
  342. if (!$checked) {
  343. $w = false;
  344. }
  345. }
  346. return $name;
  347. }
  348. /**
  349. * Gets the folder name (strips down path).
  350. * @param string $fname 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 $fname 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 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 $folder Path
  399. * @param integer $flag Flag
  400. * @param integer $user_id 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(, $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. }