dropbox_submit.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /*
  4. * PREVENT RESUBMITING
  5. * This part checks if the $dropbox_unid var has the same ID
  6. * as the session var $dropbox_uniqueid that was registered as a session
  7. * var before.
  8. * The resubmit prevention only works with GET requests, because it gives some annoying
  9. * behaviours with POST requests.
  10. */
  11. /**
  12. * FORM SUBMIT
  13. * - VALIDATE POSTED DATA
  14. * - UPLOAD NEW FILE
  15. */
  16. if (isset($_POST['submitWork'])) {
  17. $error = false;
  18. $errormsg = '';
  19. /**
  20. * FORM SUBMIT : VALIDATE POSTED DATA
  21. */
  22. // the author or description field is empty
  23. if (!isset($_POST['authors']) || !isset($_POST['description'])) {
  24. $error = true;
  25. $errormsg = get_lang('BadFormData');
  26. } elseif (!isset($_POST['recipients']) || count($_POST['recipients']) <= 0) {
  27. $error = true;
  28. $errormsg = get_lang('NoUserSelected');
  29. } else {
  30. $thisIsAMailing = false;
  31. $thisIsJustUpload = false;
  32. foreach ($_POST['recipients'] as $rec) {
  33. if ($rec == 'mailing') {
  34. $thisIsAMailing = true;
  35. } elseif ($rec == 'upload') {
  36. $thisIsJustUpload = true;
  37. } elseif (strpos($rec, 'user_') === 0 && !isCourseMember(substr($rec, strlen('user_')))) {
  38. echo '401';
  39. die(get_lang('BadFormData').' (code 401)');
  40. } elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0) {
  41. echo '402';
  42. die(get_lang('BadFormData').' (code 402)');
  43. }
  44. }
  45. // we are doing a mailing but an additional recipient is selected
  46. if ($thisIsAMailing && (count($_POST['recipients']) != 1)) {
  47. $error = true;
  48. $errormsg = get_lang('MailingSelectNoOther');
  49. } // we are doing a just upload but an additional recipient is selected.
  50. elseif ($thisIsJustUpload && (count($_POST['recipients']) != 1)) {
  51. $error = true;
  52. $errormsg = get_lang('MailingJustUploadSelectNoOther');
  53. } elseif (empty($_FILES['file']['name'])) {
  54. $error = true;
  55. $errormsg = get_lang('NoFileSpecified');
  56. }
  57. }
  58. //check if $_POST['cb_overwrite'] is true or false
  59. $dropbox_overwrite = false;
  60. if (isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']) {
  61. $dropbox_overwrite = true;
  62. }
  63. /**
  64. * FORM SUBMIT : UPLOAD NEW FILE
  65. */
  66. if (!$error) {
  67. $dropbox_filename = $_FILES['file']['name'];
  68. $dropbox_filesize = $_FILES['file']['size'];
  69. $dropbox_filetype = $_FILES['file']['type'];
  70. $dropbox_filetmpname = $_FILES['file']['tmp_name'];
  71. if ($dropbox_filesize <= 0 || $dropbox_filesize > dropbox_cnf('maxFilesize')) {
  72. $errormsg = get_lang(
  73. 'TooBig'
  74. ); // TODO: The "too big" message does not fit in the case of uploading zero-sized file.
  75. $error = true;
  76. } elseif (!is_uploaded_file($dropbox_filetmpname)) { // check user fraud : no clean error msg.
  77. die(get_lang('BadFormData').' (code 403)');
  78. }
  79. if (!$error) {
  80. // Try to add an extension to the file if it hasn't got one
  81. $dropbox_filename = FileManager::add_ext_on_mime($dropbox_filename, $dropbox_filetype);
  82. // Replace dangerous characters
  83. $dropbox_filename = replace_dangerous_char($dropbox_filename);
  84. // Transform any .php file in .phps fo security
  85. $dropbox_filename = FileManager::php2phps($dropbox_filename);
  86. if (!FileManager::filter_extension($dropbox_filename)) {
  87. $error = true;
  88. $errormsg = get_lang('UplUnableToSaveFileFilteredExtension');
  89. } else {
  90. // set title
  91. $dropbox_title = $dropbox_filename;
  92. // set author
  93. if ($_POST['authors'] == '') {
  94. $_POST['authors'] = getUserNameFromId($_user['user_id']);
  95. }
  96. if ($dropbox_overwrite) {
  97. $dropbox_person = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
  98. foreach ($dropbox_person->sentWork as $w) {
  99. if ($w->title == $dropbox_filename) {
  100. if (($w->recipients[0]['id'] > dropbox_cnf('mailingIdBase')) xor $thisIsAMailing) {
  101. $error = true;
  102. $errormsg = get_lang('MailingNonMailingError');
  103. }
  104. if (($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload) {
  105. $error = true;
  106. $errormsg = get_lang('MailingJustUploadSelectNoOther');
  107. }
  108. $dropbox_filename = $w->filename;
  109. $found = true;
  110. break;
  111. }
  112. }
  113. } else {
  114. // rename file to login_filename_uniqueId format
  115. $dropbox_filename = getLoginFromId($_user['user_id']).'_'.$dropbox_filename.'_'.uniqid('');
  116. }
  117. if (!is_dir(dropbox_cnf('sysPath'))) {
  118. //The dropbox subdir doesn't exist yet so make it and create the .htaccess file
  119. mkdir(dropbox_cnf('sysPath'), api_get_permissions_for_new_directories()) or die(get_lang(
  120. 'ErrorCreatingDir'
  121. ).' (code 404)');
  122. $fp = fopen(dropbox_cnf('sysPath').'/.htaccess', 'w') or die(get_lang(
  123. 'ErrorCreatingDir'
  124. ).' (code 405)');
  125. fwrite(
  126. $fp,
  127. "AuthName AllowLocalAccess
  128. AuthType Basic
  129. order deny,allow
  130. deny from all
  131. php_flag zlib.output_compression off"
  132. ) or die(get_lang('ErrorCreatingDir').' (code 406)');
  133. }
  134. if ($error) {
  135. } elseif ($thisIsAMailing) {
  136. if (preg_match(dropbox_cnf('mailingZipRegexp'), $dropbox_title)) {
  137. $newWorkRecipients = dropbox_cnf('mailingIdBase');
  138. } else {
  139. $error = true;
  140. $errormsg = $dropbox_title.': '.get_lang('MailingWrongZipfile');
  141. }
  142. } elseif ($thisIsJustUpload) {
  143. $newWorkRecipients = array();
  144. } else {
  145. // Creating the array that contains all the users who will receive the file
  146. $newWorkRecipients = array();
  147. foreach ($_POST['recipients'] as $rec) {
  148. if (strpos($rec, 'user_') === 0) {
  149. $newWorkRecipients[] = substr($rec, strlen('user_'));
  150. } elseif (strpos($rec, 'group_') === 0) {
  151. $userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_')));
  152. foreach ($userList as $usr) {
  153. if (!in_array(
  154. $usr['user_id'],
  155. $newWorkRecipients
  156. ) && $usr['user_id'] != $_user['user_id']
  157. ) {
  158. $newWorkRecipients[] = $usr['user_id'];
  159. }
  160. }
  161. }
  162. }
  163. }
  164. // After uploading the file, create the db entries
  165. if (!$error) {
  166. @move_uploaded_file($dropbox_filetmpname, dropbox_cnf('sysPath').'/'.$dropbox_filename)
  167. or die(get_lang('UploadError').' (code 407)');
  168. new Dropbox_SentWork($_user['user_id'], $dropbox_title, $_POST['description'], strip_tags(
  169. $_POST['authors']
  170. ), $dropbox_filename, $dropbox_filesize, $newWorkRecipients);
  171. }
  172. }
  173. }
  174. } //end if(!$error)
  175. /**
  176. * SUBMIT FORM RESULTMESSAGE
  177. */
  178. if (!$error) {
  179. $return_message = get_lang('FileUploadSucces');
  180. } else {
  181. $return_message = $errormsg;
  182. }
  183. } // end if ( isset( $_POST['submitWork']))
  184. /**
  185. * EXAMINE OR SEND MAILING (NEW)
  186. * @deprecated The $_GET[mailingIndex] is never called
  187. */
  188. /*
  189. if (isset($_GET['mailingIndex'])) {
  190. // examine or send
  191. $dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
  192. if (isset($_SESSION['sentOrder'])) {
  193. $dropbox_person->orderSentWork($_SESSION['sentOrder']);
  194. }
  195. $i = $_GET['mailingIndex'];
  196. $mailing_item = $dropbox_person->sentWork[$i];
  197. $mailing_title = $mailing_item->title;
  198. $mailing_file = dropbox_cnf('sysPath') . '/' . $mailing_item->filename;
  199. $errormsg = '<b>' . $mailing_item->recipients[0]['name'] . ' ('
  200. . "<a href='dropbox_download.php?origin=$origin&id=".urlencode($mailing_item->id)."'>"
  201. . htmlspecialchars($mailing_title, ENT_QUOTES, api_get_system_encoding()) . '</a>):</b><br /><br />';
  202. if (preg_match( dropbox_cnf('mailingZipRegexp'), $mailing_title, $nameParts)) {
  203. $var = api_strtoupper($nameParts[2]); // the variable part of the name
  204. $course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  205. $sel = "SELECT u.user_id, u.lastname, u.firstname, cu.status
  206. FROM ".$_configuration['main_database'].".user u
  207. LEFT JOIN $course_user cu
  208. ON cu.user_id = u.user_id AND cu.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND cu.course_code = '".$_course['sysCode']."'";
  209. $sel .= " WHERE u.".dropbox_cnf("mailingWhere".$var)." = '";
  210. $preFix = $nameParts[1]; $postFix = $nameParts[3];
  211. $preLen = api_strlen($preFix); $postLen = api_strlen($postFix);
  212. require api_get_path(LIBRARY_PATH) . 'pclzip/pclzip.lib.php';
  213. $zipFile = new PclZip($mailing_file);
  214. $goodFiles = array();
  215. $zipContent = $zipFile->listContent();
  216. $ucaseFiles = array();
  217. if ($zipContent) {
  218. foreach( $zipFile->listContent() as $thisContent) {
  219. $thisFile = substr(strrchr('/' . $thisContent['filename'], '/'), 1);
  220. $thisFileUcase = strtoupper($thisFile);
  221. if (preg_match("~.(php.*|phtml)$~i", $thisFile)) {
  222. $error = true;
  223. $errormsg .= $thisFile . ': ' . get_lang('MailingZipPhp');
  224. break;
  225. } elseif (!$thisContent['folder']) {
  226. if ($ucaseFiles[$thisFileUcase]) {
  227. $error = true;
  228. $errormsg .= $thisFile . ': ' . get_lang('MailingZipDups');
  229. break;
  230. } else {
  231. $goodFiles[$thisFile] = findRecipient($thisFile);
  232. $ucaseFiles[$thisFileUcase] = 'yep';
  233. }
  234. }
  235. }
  236. } else {
  237. $error = true;
  238. $errormsg .= get_lang('MailingZipEmptyOrCorrupt');
  239. }
  240. if (!$error) {
  241. $students = array(); // collect all recipients in this course
  242. foreach ($goodFiles as $thisFile => $thisRecip) {
  243. $errormsg .= htmlspecialchars($thisFile, ENT_QUOTES, api_get_system_encoding()) . ': ';
  244. if (is_string($thisRecip)) { // see findRecipient
  245. $errormsg .= '<font color="#FF0000">'
  246. . htmlspecialchars($thisRecip, ENT_QUOTES, api_get_system_encoding()) . '</font><br />';
  247. } else {
  248. if ( isset( $_GET['mailingSend'])) {
  249. $errormsg .= get_lang('MailingFileSentTo');
  250. } else {
  251. $errormsg .= get_lang('MailingFileIsFor');
  252. }
  253. $errormsg .= htmlspecialchars(api_get_person_name($thisRecip[2], $thisRecip[1]), ENT_QUOTES, api_get_system_encoding());
  254. if (is_null($thisRecip[3])) {
  255. $errormsg .= get_lang('MailingFileNotRegistered');
  256. } else {
  257. $students[] = $thisRecip[0];
  258. }
  259. $errormsg .= '<br />';
  260. }
  261. }
  262. // find student course members not among the recipients
  263. $course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  264. $sql = "SELECT u.lastname, u.firstname
  265. FROM $course_user cu
  266. LEFT JOIN ".$_configuration['main_database'].".user u
  267. ON cu.user_id = u.user_id AND cu.course_code = '".$_course['sysCode']."'
  268. WHERE cu.status = 5
  269. AND u.user_id NOT IN ('" . implode("', '" , $students) . "')";
  270. $result = Database::query($sql);
  271. if (Database::num_rows($result) > 0) {
  272. $remainingUsers = '';
  273. while ($res = Database::fetch_array($result)) {
  274. $remainingUsers .= ', ' . htmlspecialchars(api_get_person_name($res[1], $res[0]), ENT_QUOTES, api_get_system_encoding());
  275. }
  276. $errormsg .= '<br />' . get_lang('MailingNothingFor') . api_substr($remainingUsers, 1) . '.<br />';
  277. }
  278. if (isset($_GET['mailingSend'])) {
  279. chdir(dropbox_cnf('sysPath'));
  280. $zipFile->extract(PCLZIP_OPT_REMOVE_ALL_PATH);
  281. $mailingPseudoId = dropbox_cnf('mailingIdBase') + $mailing_item->id;
  282. foreach ($goodFiles as $thisFile => $thisRecip) {
  283. if (is_string($thisRecip)) { // remove problem file
  284. @unlink(dropbox_cnf('sysPath') . '/' . $thisFile);
  285. } else {
  286. $newName = getLoginFromId( $_user['user_id']) . '_' . $thisFile . '_' . uniqid('');
  287. if (rename(dropbox_cnf('sysPath') . '/' . $thisFile, dropbox_cnf('sysPath') . '/' . $newName))
  288. new Dropbox_SentWork($mailingPseudoId, $thisFile, $mailing_item->description, $mailing_item->author, $newName, $thisContent['size'], array($thisRecip[0]));
  289. }
  290. }
  291. $sendDT = api_get_utc_datetime();
  292. // set filesize to zero on send, to avoid 2nd send (see index.php)
  293. $sql = "UPDATE ".dropbox_cnf("tbl_file")."
  294. SET filesize = '0' , upload_date = '".$sendDT."', last_upload_date = '".$sendDT."'
  295. WHERE id='".addslashes($mailing_item->id)."'";
  296. $result = Database::query($sql);
  297. } elseif ($mailing_item->filesize != 0) {
  298. $errormsg .= '<br />' . get_lang('MailingNotYetSent') . '<br />';
  299. }
  300. }
  301. } else {
  302. $error = true;
  303. $errormsg .= get_lang('MailingWrongZipfile');
  304. }
  305. //EXAMINE OR SEND MAILING RESULTMESSAGE
  306. if ($error) {
  307. ?>
  308. <b><font color="#FF0000"><?php echo $errormsg?></font></b><br /><br />
  309. <a href="index.php<?php echo "?origin=$origin"; ?>"><?php echo get_lang('BackList'); ?></a><br />
  310. <?php
  311. } else {
  312. ?>
  313. <?php echo $errormsg?><br /><br />
  314. <a href="index.php<?php echo "?origin=$origin"; ?>"><?php echo get_lang('BackList'); ?></a><br />
  315. <?php
  316. }
  317. }
  318. */
  319. function findRecipient($thisFile)
  320. {
  321. // string result = error message, array result = [user_id, lastname, firstname, status]
  322. global $nameParts, $preFix, $preLen, $postFix, $postLen;
  323. if (preg_match(dropbox_cnf('mailingFileRegexp'), $thisFile, $matches)) {
  324. $thisName = $matches[1];
  325. if (api_substr($thisName, 0, $preLen) == $preFix) {
  326. if ($postLen == 0 || api_substr($thisName, -$postLen) == $postFix) {
  327. $thisRecip = api_substr($thisName, $preLen, api_strlen($thisName) - $preLen - $postLen);
  328. if ($thisRecip) {
  329. return getUser($thisRecip);
  330. }
  331. return ' <'.get_lang('MailingFileNoRecip', '').'>';
  332. } else {
  333. return ' <'.get_lang('MailingFileNoPostfix', '').$postFix.'>';
  334. }
  335. } else {
  336. return ' <'.get_lang('MailingFileNoPrefix', '').$preFix.'>';
  337. }
  338. } else {
  339. return ' <'.get_lang('MailingFileFunny', '').'>';
  340. }
  341. }
  342. function getUser($thisRecip)
  343. {
  344. // string result = error message, array result = [user_id, lastname, firstname]
  345. global $var, $sel;
  346. if (isset($students)) {
  347. unset($students);
  348. }
  349. $result = Database::query($sel.$thisRecip."'");
  350. while (($res = Database::fetch_array($result))) {
  351. $students[] = $res;
  352. }
  353. Database::free_result($result);
  354. if (count($students) == 1) {
  355. return ($students[0]);
  356. } elseif (count($students) > 1) {
  357. return ' <'.get_lang('MailingFileRecipDup', '').$var."= $thisRecip>";
  358. } else {
  359. return ' <'.get_lang('MailingFileRecipNotFound', '').$var."= $thisRecip>";
  360. }
  361. }
  362. /**
  363. * DELETE RECEIVED OR SENT FILES - EDIT FEEDBACK
  364. * - DELETE ALL RECEIVED FILES
  365. * - DELETE 1 RECEIVED FILE
  366. * - DELETE ALL SENT FILES
  367. * - DELETE 1 SENT FILE
  368. * - EDIT FEEDBACK
  369. */
  370. if (isset($_GET['deleteReceived']) || isset($_GET['deleteSent'])
  371. || isset($_GET['showFeedback']) || isset($_GET['editFeedback'])
  372. ) {
  373. if ($_GET['mailing']) {
  374. getUserOwningThisMailing($_GET['mailing'], $_user['user_id'], '408');
  375. $dropbox_person = new Dropbox_Person($_GET['mailing'], $is_courseAdmin, $is_courseTutor);
  376. } else {
  377. $dropbox_person = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
  378. }
  379. if (isset($_SESSION['sentOrder'])) {
  380. $dropbox_person->orderSentWork($_SESSION['sentOrder']);
  381. }
  382. if (isset($_SESSION['receivedOrder'])) {
  383. $dropbox_person->orderReceivedWork($_SESSION['receivedOrder']);
  384. }
  385. /*if (!$dropbox_person->isCourseAdmin || ! $dropbox_person->isCourseTutor) {
  386. die(get_lang('GeneralError').' (code 408)');
  387. }*/
  388. $tellUser = get_lang('FileDeleted');
  389. if (isset($_GET['deleteReceived'])) {
  390. if ($_GET['deleteReceived'] == 'all') {
  391. $dropbox_person->deleteAllReceivedWork();
  392. } elseif (is_numeric($_GET['deleteReceived'])) {
  393. $dropbox_person->deleteReceivedWork($_GET['deleteReceived']);
  394. } else {
  395. die(get_lang('GeneralError').' (code 409)');
  396. }
  397. } elseif (isset($_GET['deleteSent'])) {
  398. if ($_GET['deleteSent'] == 'all') {
  399. $dropbox_person->deleteAllSentWork();
  400. } elseif (is_numeric($_GET['deleteSent'])) {
  401. $dropbox_person->deleteSentWork($_GET['deleteSent']);
  402. } else {
  403. die(get_lang('GeneralError').' (code 410)');
  404. }
  405. } elseif (isset($_GET['showFeedback'])) {
  406. $w = new Dropbox_SentWork($id = $_GET['showFeedback']);
  407. if ($w->uploader_id != $_user['user_id']) {
  408. getUserOwningThisMailing($w->uploader_id, $_user['user_id'], '411');
  409. }
  410. foreach ($w->recipients as $r) {
  411. if (($fb = $r['feedback'])) {
  412. $fbarray[$r['feedback_date'].$r['name']] = $r['name'].' '.get_lang(
  413. 'SentOn',
  414. ''
  415. ).' '.$r['feedback_date'].":\n".$fb;
  416. }
  417. }
  418. if ($fbarray) {
  419. krsort($fbarray);
  420. echo '<textarea class="dropbox_feedbacks">',
  421. htmlspecialchars(implode("\n\n", $fbarray), ENT_QUOTES, api_get_system_encoding()), '</textarea>', "\n";
  422. } else {
  423. echo '<textarea class="dropbox_feedbacks">&nbsp;</textarea>', "\n";
  424. }
  425. $tellUser = get_lang('ShowFeedback');
  426. } else { // if ( isset( $_GET['editFeedback'])) {
  427. $id = $_GET['editFeedback'];
  428. $found = false;
  429. foreach ($dropbox_person->receivedWork as $w) {
  430. if ($w->id == $id) {
  431. $found = true;
  432. break;
  433. }
  434. }
  435. if (!$found) {
  436. die(get_lang('GeneralError').' (code 415)');
  437. }
  438. echo '<form method="post" action="index.php">', "\n",
  439. '<input type="hidden" name="feedbackid" value="',
  440. $id, '"/>', "\n",
  441. '<textarea name="feedbacktext" class="dropbox_feedbacks">',
  442. htmlspecialchars($w->feedback, ENT_QUOTES, api_get_system_encoding()), '</textarea>', "<br />\n",
  443. '<input type="submit" name="feedbacksubmit" value="', get_lang('Ok', ''), '"/>', "\n",
  444. '</form>', "\n";
  445. $tellUser = get_lang('GiveFeedback');
  446. }
  447. /**
  448. * RESULTMESSAGE FOR DELETE FILE OR EDIT FEEDBACK
  449. */
  450. $return_message = get_lang('BackList');
  451. }