hotpotatoes.lib.php 13 KB

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