hotpotatoes.lib.php 13 KB

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