dropbox_functions.inc.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This file contains additional dropbox functions. Initially there were some
  5. * functions in the init files also but I have moved them over
  6. * to one file -- Patrick Cool <patrick.cool@UGent.be>, Ghent University
  7. */
  8. //require_once '../inc/global.inc.php';
  9. $this_section = SECTION_COURSES;
  10. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
  11. $htmlHeadXtra[] = '<script type="text/javascript">
  12. function setFocus(){
  13. $("#category_title").focus();
  14. }
  15. $(document).ready(function () {
  16. setFocus();
  17. });
  18. </script>';
  19. /**
  20. * This function is a wrapper function for the multiple actions feature.
  21. * @return Mixed If there is a problem, return a string message, otherwise nothing
  22. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  23. * @version march 2006
  24. */
  25. function handle_multiple_actions() {
  26. global $_user, $is_courseAdmin, $is_courseTutor;
  27. // STEP 1: are we performing the actions on the received or on the sent files?
  28. if ($_POST['action'] == 'delete_received' || $_POST['action'] == 'download_received') {
  29. $part = 'received';
  30. } elseif ($_POST['action'] == 'delete_sent' || $_POST['action'] == 'download_sent') {
  31. $part = 'sent';
  32. }
  33. // STEP 2: at least one file has to be selected. If not we return an error message
  34. foreach ($_POST as $key => $value) {
  35. if (strstr($value, $part.'_') AND $key != 'view_received_category' AND $key != 'view_sent_category') {
  36. $checked_files = true;
  37. $checked_file_ids[] = intval(substr($value, strrpos($value, '_')));
  38. }
  39. }
  40. $checked_file_ids = $_POST['id'];
  41. if (!is_array($checked_file_ids) || count($checked_file_ids) == 0) {
  42. return get_lang('CheckAtLeastOneFile');
  43. }
  44. // STEP 3A: deleting
  45. if ($_POST['action'] == 'delete_received' || $_POST['action'] == 'delete_sent') {
  46. $dropboxfile = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
  47. foreach ($checked_file_ids as $key => $value) {
  48. if ($_GET['view'] == 'received') {
  49. $dropboxfile->deleteReceivedWork($value);
  50. $message = get_lang('ReceivedFileDeleted');
  51. }
  52. if ($_GET['view'] == 'sent' OR empty($_GET['view'])) {
  53. $dropboxfile->deleteSentWork($value);
  54. $message = get_lang('SentFileDeleted');
  55. }
  56. }
  57. return $message;
  58. }
  59. // STEP 3B: giving comment
  60. if ($_POST['actions'] == 'comment') {
  61. // This has not been implemented.
  62. // The idea was that it would be possible to write the same feedback for the selected documents.
  63. }
  64. // STEP 3C: moving
  65. if (strstr($_POST['action'], 'move_')) {
  66. // check move_received_n or move_sent_n command
  67. if (strstr($_POST['action'], 'received')) {
  68. $part = 'received';
  69. $to_cat_id = str_replace('move_received_', '', $_POST['action']);
  70. } else {
  71. $part = 'sent';
  72. $to_cat_id = str_replace('move_sent_', '', $_POST['action']);
  73. }
  74. foreach ($checked_file_ids as $key => $value) {
  75. //var_dump($value);
  76. //var_dump($to_cat_id);
  77. //var_dump($part);
  78. store_move($value, $to_cat_id, $part);
  79. }
  80. return get_lang('FilesMoved');
  81. }
  82. // STEP 3D: downloading
  83. if ($_POST['action'] == 'download_sent' || $_POST['action'] == 'download_received') {
  84. zip_download($checked_file_ids);
  85. }
  86. }
  87. /**
  88. * This function deletes a dropbox category
  89. *
  90. * @todo give the user the possibility what needs to be done with the files in this category: move them to the root, download them as a zip, delete them
  91. *
  92. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  93. * @version march 2006
  94. */
  95. function delete_category($action, $id) {
  96. global $dropbox_cnf;
  97. global $_user, $is_courseAdmin, $is_courseTutor;
  98. // an additional check that might not be necessary
  99. if ($action == 'deletereceivedcategory') {
  100. $sentreceived = 'received';
  101. $entries_table = $dropbox_cnf['tbl_post'];
  102. $id_field = 'file_id';
  103. $return_message = get_lang('ReceivedCatgoryDeleted');
  104. } elseif ($action == 'deletesentcategory') {
  105. $sentreceived = 'sent';
  106. $entries_table = $dropbox_cnf['tbl_file'];
  107. $id_field = 'id';
  108. $return_message = get_lang('SentCatgoryDeleted');
  109. } else {
  110. return get_lang('Error');
  111. }
  112. // step 1: delete the category
  113. $sql = "DELETE FROM ".$dropbox_cnf['tbl_category']." WHERE cat_id='".Database::escape_string($id)."' AND $sentreceived='1'";
  114. $result = Database::query($sql);
  115. // step 2: delete all the documents in this category
  116. $sql = "SELECT * FROM ".$entries_table." WHERE cat_id='".Database::escape_string($id)."'";
  117. $result = Database::query($sql);
  118. while($row = Database::fetch_array($result)) {
  119. $dropboxfile = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
  120. if ($action == 'deletereceivedcategory') {
  121. $dropboxfile->deleteReceivedWork($row[$id_field]);
  122. }
  123. if ($action == 'deletesentcategory') {
  124. $dropboxfile->deleteSentWork($row[$id_field]);
  125. }
  126. }
  127. return $return_message;
  128. }
  129. /**
  130. * Displays the form to move one individual file to a category
  131. *
  132. * @return html code of the form that appears in a message box.
  133. *
  134. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  135. * @version march 2006
  136. */
  137. function display_move_form($part, $id, $target = array()) {
  138. echo '<div class="row"><div class="form_header">'.get_lang('MoveFileTo').'</div></div>';
  139. echo '<form name="form1" method="post" action="'.api_get_self().'?view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&view='.Security::remove_XSS($_GET['view']).'">';
  140. echo '<input type="hidden" name="id" value="'.Security::remove_XSS($id).'">';
  141. echo '<input type="hidden" name="part" value="'.Security::remove_XSS($part).'">';
  142. echo '
  143. <div class="row">
  144. <div class="label">
  145. <span class="form_required">*</span> '.get_lang('MoveFileTo').'
  146. </div>
  147. <div class="formw">';
  148. echo '<select name="move_target">';
  149. echo '<option value="0">'.get_lang('Root').'</option>';
  150. foreach ($target as $key => $category) {
  151. echo '<option value="'.$category['cat_id'].'">'.$category['cat_name'].'</option>';
  152. }
  153. echo '</select>';
  154. echo ' </div>
  155. </div>';
  156. echo '<div class="row">
  157. <div class="label">
  158. </div>
  159. <div class="formw">
  160. <button class="next" type="submit" name="do_move" value="'.get_lang('Ok').'">'.get_lang('MoveFile').'</button>
  161. </div>
  162. </div>';
  163. echo '</form>';
  164. echo '<div style="clear: both;"></div>';
  165. }
  166. /**
  167. * This function moves a file to a different category
  168. *
  169. * @param $id the id of the file we are moving
  170. * @param $target the id of the folder we are moving to
  171. * @param $part are we moving a received file or a sent file?
  172. *
  173. * @return language string
  174. *
  175. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  176. * @version march 2006
  177. */
  178. function store_move($id, $target, $part)
  179. {
  180. global $_user;
  181. global $dropbox_cnf;
  182. if ((isset($id) AND $id != '') AND (isset($target) AND $target != '') AND (isset($part) AND $part != '')) {
  183. if ($part == 'received') {
  184. $sql = "UPDATE ".$dropbox_cnf["tbl_post"]." SET cat_id='".Database::escape_string($target)."'
  185. WHERE dest_user_id='".Database::escape_string($_user['user_id'])."'
  186. AND file_id='".Database::escape_string($id)."'";
  187. Database::query($sql);
  188. $return_message = get_lang('ReceivedFileMoved');
  189. }
  190. if ($part == 'sent') {
  191. $sql = "UPDATE ".$dropbox_cnf["tbl_file"]." SET cat_id='".Database::escape_string($target)."'
  192. WHERE uploader_id='".Database::escape_string($_user['user_id'])."'
  193. AND id='".Database::escape_string($id)."'";
  194. Database::query($sql);
  195. $return_message = get_lang('SentFileMoved');
  196. }
  197. } else {
  198. $return_message = get_lang('NotMovedError');
  199. }
  200. return $return_message;
  201. }
  202. /**
  203. * This functions displays all teh possible actions that can be performed on multiple files. This is the dropdown list that
  204. * appears below the sortable table of the sent / or received files.
  205. *
  206. * @return html value for the dropdown list
  207. *
  208. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  209. * @version march 2006
  210. */
  211. function display_action_options($part, $categories, $current_category = 0) {
  212. echo '<select name="actions">';
  213. echo '<option value="download">'.get_lang('Download').'</option>';
  214. echo '<option value="delete">'.get_lang('Delete').'</option>';
  215. if (is_array($categories)) {
  216. echo '<optgroup label="'.get_lang('MoveTo').'">';
  217. if ($current_category != 0) {
  218. echo '<option value="move_0">'.get_lang('Root').'</a>';
  219. }
  220. foreach ($categories as $key => $value) {
  221. if ($current_category != $value['cat_id']) {
  222. echo '<option value="move_'.$value['cat_id'].'">'.$value['cat_name'].'</option>';
  223. }
  224. }
  225. echo '</optgroup>';
  226. }
  227. echo '</select>';
  228. echo '<input type="submit" name="do_actions_'.Security::remove_XSS($part).'" value="'.get_lang('Ok').'" />';
  229. }
  230. /**
  231. * this function returns the html code that displays the checkboxes next to the files so that
  232. * multiple actions on one file are possible.
  233. *
  234. * @param $id the unique id of the file
  235. * @param $part are we dealing with a sent or with a received file?
  236. *
  237. * @return html code
  238. *
  239. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  240. * @version march 2006
  241. */
  242. function display_file_checkbox($id, $part) {
  243. if (isset($_GET['selectall'])) {
  244. $checked = 'checked';
  245. }
  246. $return_value = '<input type="checkbox" name="'.Security::remove_XSS($part).'_'.Security::remove_XSS($id).'" value="'.Security::remove_XSS($id).'" '.$checked.' />';
  247. return $return_value;
  248. }
  249. /**
  250. * This function retrieves all the dropbox categories and returns them as an array
  251. *
  252. * @param $filter default '', when we need only the categories of the sent or the received part.
  253. *
  254. * @return array
  255. *
  256. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  257. * @version march 2006
  258. */
  259. function get_dropbox_categories($filter = '') {
  260. global $_user;
  261. global $dropbox_cnf;
  262. $return_array = array();
  263. $session_id = api_get_session_id();
  264. $condition_session = api_get_session_condition($session_id);
  265. $sql = "SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE user_id='".$_user['user_id']."' $condition_session";
  266. $result = Database::query($sql);
  267. while ($row = Database::fetch_array($result)) {
  268. if (($filter == 'sent' AND $row['sent'] == 1) OR ($filter == 'received' AND $row['received'] == 1) OR $filter == '') {
  269. $return_array[$row['cat_id']] = $row;
  270. }
  271. }
  272. return $return_array;
  273. }
  274. /**
  275. * This functions stores a new dropboxcategory
  276. *
  277. * @var it might not seem very elegant if you create a category in sent and in received with the same name that you get two entries in the
  278. * dropbox_category table but it is the easiest solution. You get
  279. * cat_name | received | sent | user_id
  280. * test | 1 | 0 | 237
  281. * test | 0 | 1 | 237
  282. * more elegant would be
  283. * test | 1 | 1 | 237
  284. *
  285. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  286. * @version march 2006
  287. */
  288. function store_addcategory() {
  289. global $_user;
  290. global $dropbox_cnf;
  291. // check if the target is valid
  292. if ($_POST['target'] == 'sent') {
  293. $sent = 1;
  294. $received = 0;
  295. } elseif ($_POST['target'] == 'received') {
  296. $sent = 0;
  297. $received = 1;
  298. } else {
  299. return get_lang('Error');
  300. }
  301. // check if the category name is valid
  302. if ($_POST['category_name'] == '') {
  303. return array('type' => 'error', 'message' => get_lang('ErrorPleaseGiveCategoryName'));
  304. }
  305. if (!$_POST['edit_id']) {
  306. $session_id = api_get_session_id();
  307. // step 3a, we check if the category doesn't already exist
  308. $sql = "SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE user_id='".$_user['user_id']."' AND cat_name='".Database::escape_string(Security::remove_XSS($_POST['category_name']))."' AND received='".$received."' AND sent='$sent' AND session_id='$session_id'";
  309. $result = Database::query($sql);
  310. // step 3b, we add the category if it does not exist yet.
  311. if (Database::num_rows($result) == 0) {
  312. $sql = "INSERT INTO ".$dropbox_cnf['tbl_category']." (cat_name, received, sent, user_id, session_id)
  313. VALUES ('".Database::escape_string(Security::remove_XSS($_POST['category_name']))."', '".Database::escape_string($received)."', '".Database::escape_string($sent)."', '".Database::escape_string($_user['user_id'])."',$session_id)";
  314. Database::query($sql);
  315. return array('type' => 'confirmation', 'message' => get_lang('CategoryStored'));
  316. } else {
  317. return array('type' => 'error', 'message' => get_lang('CategoryAlreadyExistsEditIt'));
  318. }
  319. } else {
  320. $sql = "UPDATE ".$dropbox_cnf['tbl_category']." SET cat_name='".Database::escape_string(Security::remove_XSS($_POST['category_name']))."', received='".Database::escape_string($received)."' , sent='".Database::escape_string($sent)."'
  321. WHERE user_id='".Database::escape_string($_user['user_id'])."'
  322. AND cat_id='".Database::escape_string(Security::remove_XSS($_POST['edit_id']))."'";
  323. Database::query($sql);
  324. return array('type' => 'confirmation', 'message' => get_lang('CategoryModified'));
  325. }
  326. }
  327. /**
  328. * This function displays the form to add a new category.
  329. *
  330. * @param $category_name this parameter is the name of the category (used when no section is selected)
  331. * @param $id this is the id of the category we are editing.
  332. *
  333. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  334. * @version march 2006
  335. */
  336. function display_addcategory_form($category_name = '', $id = '', $action) {
  337. global $dropbox_cnf;
  338. $title = get_lang('AddNewCategory');
  339. if (isset($id) AND $id != '') {
  340. // retrieve the category we are editing
  341. $sql = "SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE cat_id='".Database::escape_string($id)."'";
  342. $result = Database::query($sql);
  343. $row = Database::fetch_array($result);
  344. if (empty($category_name)) { // after an edit with an error we do not want to return to the original name but the name we already modified. (happens when createinrecievedfiles AND createinsentfiles are not checked)
  345. $category_name = $row['cat_name'];
  346. }
  347. if ($row['received'] == '1') {
  348. $target = 'received';
  349. }
  350. if ($row['sent'] == '1') {
  351. $target = 'sent';
  352. }
  353. $title = get_lang('EditCategory');
  354. }
  355. if ($action == 'addreceivedcategory') {
  356. $target = 'received';
  357. }
  358. if ($action == 'addsentcategory') {
  359. $target = 'sent';
  360. }
  361. if ($action == 'editcategory') {
  362. $text = get_lang('ModifyCategory');
  363. $class = 'save';
  364. } elseif ($action == 'addreceivedcategory' or $action == 'addsentcategory') {
  365. $text = get_lang('CreateCategory');
  366. $class = 'add';
  367. }
  368. echo '<form name="add_new_category" method="post" action="'.api_get_self().'?view="'.Security::remove_XSS($_GET['view']).'">'."\n";
  369. if (isset($id) AND $id != '') {
  370. echo '<input name="edit_id" type="hidden" value="'.Security::remove_XSS($id).'">';
  371. }
  372. echo '<input name="action" type="hidden" value="'.Security::remove_XSS($action).'">';
  373. echo '<input name="target" type="hidden" value="'.$target.'">';
  374. echo '<div class="row"><div class="form_header">'.$title.'</div></div>';
  375. echo ' <div class="row">
  376. <div class="label">
  377. <span class="form_required">*</span> '.get_lang('CategoryName').'
  378. </div>
  379. <div class="formw">';
  380. if ($_POST AND empty($_POST['category_name'])) {
  381. echo '<span class="form_error">'.get_lang('ThisFieldIsRequired').'. '.get_lang('ErrorPleaseGiveCategoryName').'<span><br />';
  382. }
  383. if ($_POST AND !empty($_POST['category_name'])) {
  384. echo '<span class="form_error">'.get_lang('CategoryAlreadyExistsEditIt').'<span><br />';
  385. }
  386. echo ' <input type="text" id="category_title" name="category_name" value="'.Security::remove_XSS($category_name).'" />
  387. </div>
  388. </div>';
  389. echo ' <div class="row">
  390. <div class="label">
  391. </div>
  392. <div class="formw">
  393. <button class="'.$class.'" type="submit" name="StoreCategory">'.$text.'</button>
  394. </div>
  395. </div>';
  396. echo ' <div class="row">
  397. <div class="label">
  398. </div>
  399. <div class="formw">
  400. <span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>
  401. </div>
  402. </div>';
  403. echo '</form>';
  404. echo '<div style="clear: both;"></div>';
  405. }
  406. /**
  407. * this function displays the form to upload a new item to the dropbox.
  408. *
  409. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  410. * @version march 2006
  411. */
  412. function display_add_form() {
  413. global $_user, $is_courseAdmin, $is_courseTutor, $course_info, $origin, $dropbox_unid;
  414. $token = Security::get_token();
  415. $dropbox_person = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
  416. ?>
  417. <form method="post" action="index.php?view_received_category=<?php echo Security::remove_XSS($_GET['view_received_category']); ?>&view_sent_category=<?php echo Security::remove_XSS($_GET['view_sent_category']); ?>&view=<?php echo Security::remove_XSS($_GET['view']); ?>&<?php echo "origin=$origin"."&".api_get_cidreq(); ?>" enctype="multipart/form-data" onsubmit="javascript: return checkForm(this);">
  418. <div class="row"><div class="form_header"><?php echo get_lang('UploadNewFile'); ?></div></div>
  419. <div class="row">
  420. <div class="label">
  421. <span class="form_required">*</span><?php echo get_lang('UploadFile'); ?>:
  422. </div>
  423. <div class="formw">
  424. <input type="hidden" name="MAX_FILE_SIZE" value='<?php echo dropbox_cnf('maxFilesize'); ?>' />
  425. <input type="file" name="file" size="20" <?php if (dropbox_cnf('allowOverwrite')) echo 'onChange="javascript: checkfile(this.value);"'; ?> />
  426. <input type="hidden" name="dropbox_unid" value="<?php echo $dropbox_unid; ?>" />
  427. <input type="hidden" name="sec_token" value="<?php echo $token; ?>" />
  428. <?php
  429. if ($origin == 'learnpath') {
  430. echo '<input type="hidden" name="origin" value="learnpath" />';
  431. }
  432. ?>
  433. </div>
  434. </div>
  435. <?php
  436. if (dropbox_cnf('allowOverwrite')) {
  437. ?>
  438. <div class="row">
  439. <div class="label">
  440. </div>
  441. <div class="formw">
  442. <input type="checkbox" name="cb_overwrite" id="cb_overwrite" value="true" /><?php echo get_lang('OverwriteFile'); ?>
  443. </div>
  444. </div>
  445. <?php
  446. }
  447. ?>
  448. <div class="row">
  449. <div class="label">
  450. <?php echo get_lang('SendTo'); ?>
  451. </div>
  452. <div class="formw">
  453. <?php
  454. //list of all users in this course and all virtual courses combined with it
  455. if (isset($_SESSION['id_session'])){
  456. $complete_user_list_for_dropbox = array();
  457. if (api_get_setting('dropbox_allow_student_to_student')=='true' || $_user['status'] != STUDENT) {
  458. $complete_user_list_for_dropbox = CourseManager :: get_user_list_from_course_code($course_info['code'], true, $_SESSION['id_session']);
  459. }
  460. $complete_user_list2 = CourseManager :: get_coach_list_from_course_code($course_info['code'], $_SESSION['id_session']);
  461. $complete_user_list_for_dropbox = array_merge($complete_user_list_for_dropbox, $complete_user_list2);
  462. } else {
  463. if(api_get_setting('dropbox_allow_student_to_student')=='true' || $_user['status'] != STUDENT) {
  464. $complete_user_list_for_dropbox = CourseManager :: get_user_list_from_course_code($course_info['code'], true, $_SESSION['id_session']);
  465. } else {
  466. $complete_user_list_for_dropbox = CourseManager :: get_teacher_list_from_course_code($course_info['code']);
  467. }
  468. }
  469. foreach ($complete_user_list_for_dropbox as $k => $e) {
  470. $complete_user_list_for_dropbox[$k] = $e + array('lastcommafirst' => api_get_person_name($e['firstname'], $e['lastname']));
  471. }
  472. $complete_user_list_for_dropbox = TableSort::sort_table($complete_user_list_for_dropbox, 'lastcommafirst');
  473. ?>
  474. <select name="recipients[]" size="
  475. <?php
  476. if ($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin) {
  477. echo 10;
  478. } else {
  479. echo 6;
  480. }
  481. ?>" multiple style="width: 350px;">
  482. <?php
  483. /*
  484. Create the options inside the select box:
  485. List all selected users their user id as value and a name string as display
  486. */
  487. $current_user_id = '';
  488. foreach ($complete_user_list_for_dropbox as $current_user) {
  489. if (($dropbox_person -> isCourseTutor
  490. || $dropbox_person -> isCourseAdmin
  491. || dropbox_cnf('allowStudentToStudent')
  492. || $current_user['status'] != 5 // Always allow teachers.
  493. || $current_user['tutor_id'] == 1 // Always allow tutors.
  494. ) && $current_user['user_id'] != $_user['user_id']) { // Don't include yourself.
  495. if ($current_user['user_id'] == $current_user_id) {
  496. continue;
  497. }
  498. $full_name = $current_user['lastcommafirst'];
  499. $current_user_id = $current_user['user_id'];
  500. echo '<option value="user_' . $current_user_id . '">' . $full_name . '</option>';
  501. }
  502. }
  503. /*
  504. * Show groups
  505. */
  506. if (($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin)
  507. && dropbox_cnf('allowGroup') || dropbox_cnf('allowStudentToStudent')) {
  508. $complete_group_list_for_dropbox = GroupManager::get_group_list(null, dropbox_cnf('courseId'));
  509. if (count($complete_group_list_for_dropbox) > 0) {
  510. foreach ($complete_group_list_for_dropbox as $current_group) {
  511. if ($current_group['number_of_members'] > 0) {
  512. echo '<option value="group_'.$current_group['id'].'">G: '.$current_group['name'].' - '.$current_group['number_of_members'].' '.get_lang('Users').'</option>';
  513. }
  514. }
  515. }
  516. }
  517. if (($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin) && dropbox_cnf('allowMailing')) {
  518. // echo '<option value="mailing">'.get_lang('MailingInSelect').'</option>';
  519. }
  520. if (dropbox_cnf('allowJustUpload')) {
  521. //echo '<option value="upload">'.get_lang('JustUploadInSelect').'</option>';
  522. echo '<option value="user_'.$_user['user_id'].'">'.get_lang('JustUploadInSelect').'</option>';
  523. }
  524. echo '
  525. </select>
  526. </div>
  527. </div>';
  528. echo '
  529. <div class="row">
  530. <div class="label">
  531. </div>
  532. <div class="formw">
  533. <button type="Submit" class="upload" name="submitWork">'.get_lang('Upload', '').'</button>
  534. </div>
  535. </div>
  536. ';
  537. echo '</form>';
  538. }
  539. /**
  540. * returns username or false if user isn't registered anymore
  541. * @todo check if this function is still necessary. There might be a library function for this.
  542. */
  543. function getUserNameFromId($id) {
  544. global $dropbox_cnf;
  545. $mailingId = $id - dropbox_cnf('mailingIdBase');
  546. if ($mailingId > 0) {
  547. return get_lang('MailingAsUsername', '') . $mailingId;
  548. }
  549. $id = intval($id);
  550. $sql = "SELECT ".(api_is_western_name_order() ? "CONCAT(firstname,' ', lastname)" : "CONCAT(lastname,' ', firstname)")." AS name
  551. FROM " . $dropbox_cnf['tbl_user'] . "
  552. WHERE user_id='$id'";
  553. $result = Database::query($sql);
  554. $res = Database::fetch_array( $result);
  555. if ( $res == false) return false;
  556. return stripslashes($res['name']);
  557. }
  558. /**
  559. * returns loginname or false if user isn't registered anymore
  560. * @todo check if this function is still necessary. There might be a library function for this.
  561. */
  562. function getLoginFromId($id) {
  563. $id = intval($id);
  564. $sql = "SELECT username
  565. FROM " . dropbox_cnf('tbl_user') . "
  566. WHERE user_id='$id'";
  567. $result = Database::query($sql);
  568. $res = Database::fetch_array($result);
  569. if (!$res) return false;
  570. return stripslashes($res['username']);
  571. }
  572. /**
  573. * @return boolean indicating if user with user_id=$user_id is a course member
  574. * @todo eliminate global
  575. * @todo check if this function is still necessary. There might be a library function for this.
  576. */
  577. function isCourseMember($user_id) {
  578. global $_course;
  579. $course_code = $_course['sysCode'];
  580. $is_course_member = CourseManager::is_user_subscribed_in_course($user_id, $course_code, true);
  581. return $is_course_member;
  582. }
  583. /**
  584. * Checks if there are files in the dropbox_file table that aren't used anymore in dropbox_person table.
  585. * If there are, all entries concerning the file are deleted from the db + the file is deleted from the server
  586. */
  587. function removeUnusedFiles() {
  588. // select all files that aren't referenced anymore
  589. $sql = "SELECT DISTINCT f.id, f.filename
  590. FROM " . dropbox_cnf('tbl_file') . " f
  591. LEFT JOIN " . dropbox_cnf('tbl_person') . " p ON f.id = p.file_id
  592. WHERE p.user_id IS NULL";
  593. $result = Database::query($sql);
  594. while ($res = Database::fetch_array($result)) {
  595. //delete the selected files from the post and file tables
  596. $sql = "DELETE FROM " . dropbox_cnf('tbl_post') . " WHERE file_id='" . $res['id'] . "'";
  597. $result1 = Database::query($sql);
  598. $sql = "DELETE FROM " . dropbox_cnf('tbl_file') . " WHERE id='" . $res['id'] . "'";
  599. $result1 = Database::query($sql);
  600. //delete file from server
  601. @unlink( dropbox_cnf('sysPath') . '/' . $res['filename']);
  602. }
  603. }
  604. /**
  605. *
  606. * Mailing zip-file is posted to (dest_user_id = ) mailing pseudo_id
  607. * and is only visible to its uploader (user_id).
  608. *
  609. * Mailing content files have uploader_id == mailing pseudo_id, a normal recipient,
  610. * and are visible initially to recipient and pseudo_id.
  611. *
  612. * @author René Haentjens, Ghent University
  613. *
  614. * @todo check if this function is still necessary.
  615. */
  616. function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '') {
  617. global $dropbox_cnf;
  618. $mailingPseudoId = intval($mailingPseudoId);
  619. $sql = "SELECT f.uploader_id
  620. FROM " . $dropbox_cnf['tbl_file'] . " f
  621. LEFT JOIN " . $dropbox_cnf['tbl_post'] . " p ON f.id = p.file_id
  622. WHERE p.dest_user_id = '" . $mailingPseudoId . "'";
  623. $result = Database::query($sql);
  624. if (!($res = Database::fetch_array($result)))
  625. die(get_lang('GeneralError').' (code 901)');
  626. if ($owner == 0) return $res['uploader_id'];
  627. if ($res['uploader_id'] == $owner) return true;
  628. die(get_lang('GeneralError').' (code '.$or_die.')');
  629. }
  630. /**
  631. * @author René Haentjens, Ghent University
  632. * @todo check if this function is still necessary.
  633. */
  634. function removeMoreIfMailing($file_id) {
  635. global $dropbox_cnf;
  636. // when deleting a mailing zip-file (posted to mailingPseudoId):
  637. // 1. the detail window is no longer reachable, so
  638. // for all content files, delete mailingPseudoId from person-table
  639. // 2. finding the owner (getUserOwningThisMailing) is no longer possible, so
  640. // for all content files, replace mailingPseudoId by owner as uploader
  641. $file_id = intval($file_id);
  642. $sql = "SELECT p.dest_user_id
  643. FROM " . $dropbox_cnf['tbl_post'] . " p
  644. WHERE p.file_id = '" . $file_id . "'";
  645. $result = Database::query($sql);
  646. if ($res = Database::fetch_array($result)) {
  647. $mailingPseudoId = $res['dest_user_id'];
  648. if ($mailingPseudoId > dropbox_cnf('mailingIdBase')) {
  649. $sql = "DELETE FROM " . dropbox_cnf('tbl_person') . " WHERE user_id='" . $mailingPseudoId . "'";
  650. $result1 = Database::query($sql);
  651. $sql = "UPDATE " . dropbox_cnf('tbl_file') .
  652. " SET uploader_id='" . api_get_user_id() . "' WHERE uploader_id='" . $mailingPseudoId . "'";
  653. $result1 = Database::query($sql);
  654. }
  655. }
  656. }
  657. /**
  658. * Function that finds a given config setting
  659. *
  660. * @author René Haentjens, Ghent University
  661. */
  662. function dropbox_cnf($variable) {
  663. return $GLOBALS['dropbox_cnf'][$variable];
  664. }
  665. /**
  666. *
  667. */
  668. function store_add_dropbox() {
  669. global $dropbox_cnf;
  670. global $_user;
  671. global $_course;
  672. // Validating the form data
  673. // the author is
  674. /*
  675. if (!isset($_POST['authors'])) {
  676. return get_lang('AuthorFieldCannotBeEmpty');
  677. }
  678. */
  679. // there are no recipients selected
  680. if (!isset($_POST['recipients']) || count( $_POST['recipients']) <= 0) {
  681. return get_lang('YouMustSelectAtLeastOneDestinee');
  682. }
  683. // Check if all the recipients are valid
  684. else {
  685. $thisIsAMailing = false;
  686. $thisIsJustUpload = false;
  687. foreach ($_POST['recipients'] as $rec) {
  688. if ($rec == 'mailing') {
  689. $thisIsAMailing = true;
  690. } elseif ($rec == 'upload') {
  691. $thisIsJustUpload = true;
  692. } elseif (strpos($rec, 'user_') === 0 && !isCourseMember(substr($rec, strlen('user_')))) {
  693. return get_lang('InvalideUserDetected');
  694. } elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0) {
  695. return get_lang('InvalideGroupDetected');
  696. }
  697. }
  698. }
  699. // we are doing a mailing but an additional recipient is selected
  700. if ($thisIsAMailing && (count($_POST['recipients']) != 1)) {
  701. return get_lang('MailingSelectNoOther');
  702. }
  703. // we are doing a just upload but an additional recipient is selected.
  704. // note: why can't this be valid? It is like sending a document to yourself AND to a different person (I do this quite often with my e-mails)
  705. if ($thisIsJustUpload && (count($_POST['recipients']) != 1)) {
  706. return get_lang('mailingJustUploadSelectNoOther');
  707. }
  708. if (empty($_FILES['file']['name'])) {
  709. $error = true;
  710. return get_lang('NoFileSpecified');
  711. }
  712. // are we overwriting a previous file or sending a new one
  713. $dropbox_overwrite = false;
  714. if (isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']) {
  715. $dropbox_overwrite = true;
  716. }
  717. // doing the upload
  718. $dropbox_filename = $_FILES['file']['name'];
  719. $dropbox_filesize = $_FILES['file']['size'];
  720. $dropbox_filetype = $_FILES['file']['type'];
  721. $dropbox_filetmpname = $_FILES['file']['tmp_name'];
  722. // check if the filesize does not exceed the allowed size.
  723. if ($dropbox_filesize <= 0 || $dropbox_filesize > $dropbox_cnf['maxFilesize']) {
  724. return get_lang('DropboxFileTooBig'); // TODO: The "too big" message does not fit in the case of uploading zero-sized file.
  725. }
  726. // check if the file is actually uploaded
  727. if (!is_uploaded_file($dropbox_filetmpname)) { // check user fraud : no clean error msg.
  728. return get_lang('TheFileIsNotUploaded');
  729. }
  730. // Try to add an extension to the file if it hasn't got one
  731. $dropbox_filename = add_ext_on_mime($dropbox_filename, $dropbox_filetype);
  732. // Replace dangerous characters
  733. $dropbox_filename = replace_dangerous_char($dropbox_filename);
  734. // Transform any .php file in .phps fo security
  735. $dropbox_filename = php2phps($dropbox_filename);
  736. //filter extension
  737. if (!filter_extension($dropbox_filename)) {
  738. return get_lang('UplUnableToSaveFileFilteredExtension');
  739. }
  740. // set title
  741. $dropbox_title = $dropbox_filename;
  742. // set author
  743. if ($_POST['authors'] == '') {
  744. $_POST['authors'] = getUserNameFromId($_user['user_id']);
  745. }
  746. // note: I think we could better migrate everything from here on to separate functions: store_new_dropbox, store_new_mailing, store_just_upload
  747. if ($dropbox_overwrite) {
  748. $dropbox_person = new Dropbox_Person($_user['user_id'], api_is_course_admin(), api_is_course_tutor());
  749. foreach ($dropbox_person->sentWork as $w) {
  750. if ($w->title == $dropbox_filename) {
  751. if (($w->recipients[0]['id'] > dropbox_cnf('mailingIdBase')) xor $thisIsAMailing) {
  752. return get_lang('MailingNonMailingError');
  753. }
  754. if (($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload) {
  755. return get_lang('MailingJustUploadSelectNoOther');
  756. }
  757. $dropbox_filename = $w->filename;
  758. $found = true; // note: do we still need this?
  759. break;
  760. }
  761. }
  762. } else { // rename file to login_filename_uniqueId format
  763. $dropbox_filename = getLoginFromId($_user['user_id']) . "_" . $dropbox_filename . "_".uniqid('');
  764. }
  765. // creating the array that contains all the users who will receive the file
  766. $new_work_recipients = array();
  767. foreach ($_POST['recipients'] as $rec) {
  768. if (strpos($rec, 'user_') === 0) {
  769. $new_work_recipients[] = substr($rec, strlen('user_') );
  770. } elseif (strpos($rec, 'group_') === 0) {
  771. $userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_')));
  772. foreach ($userList as $usr) {
  773. if (!in_array($usr['user_id'], $new_work_recipients) && $usr['user_id'] != $_user['user_id']) {
  774. $new_work_recipients[] = $usr['user_id'];
  775. }
  776. }
  777. }
  778. }
  779. @move_uploaded_file($dropbox_filetmpname, dropbox_cnf('sysPath') . '/' . $dropbox_filename);
  780. $b_send_mail = api_get_course_setting('email_alert_on_new_doc_dropbox');
  781. if ($b_send_mail) {
  782. foreach ($new_work_recipients as $recipient_id) {
  783. require_once api_get_path(LIBRARY_PATH) . 'usermanager.lib.php' ;
  784. $recipent_temp = UserManager :: get_user_info_by_id($recipient_id);
  785. @api_mail(api_get_person_name($recipent_temp['firstname'].' '.$recipent_temp['lastname'], null, PERSON_NAME_EMAIL_ADDRESS), $recipent_temp['email'],
  786. get_lang('NewDropboxFileUploaded'),
  787. get_lang('NewDropboxFileUploadedContent').' '.api_get_path(WEB_CODE_PATH).'dropbox/index.php?cidReq='.$_course['sysCode']."\n\n".api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS)."\n". get_lang('Email') ." : ".$_user['mail'], api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS), $_user['mail']);
  788. }
  789. }
  790. new Dropbox_SentWork( $_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $new_work_recipients);
  791. Security::clear_token();
  792. return get_lang('FileUploadSucces');
  793. }
  794. /**
  795. * This function displays the firstname and lastname of the user as a link to the user tool.
  796. *
  797. * @see this is the same function as in the new forum, so this probably has to move to a user library.
  798. *
  799. * @todo move this function to the user library
  800. *
  801. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  802. * @version march 2006
  803. */
  804. function display_user_link_work($user_id, $name = '') {
  805. if ($user_id != 0) {
  806. if (empty($name)) {
  807. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  808. $sql = "SELECT * FROM $table_user WHERE user_id='".Database::escape_string($user_id)."'";
  809. $result = Database::query($sql);
  810. $row = Database::fetch_array($result);
  811. return '<a href="../user/userInfo.php?uInfo='.$row['user_id'].'">'.api_get_person_name($row['firstname'], $row['lastname']).'</a>';
  812. } else {
  813. $user_id = intval($user_id);
  814. return '<a href="../user/userInfo.php?uInfo='.$user_id.'">'.Security::remove_XSS($name).'</a>';
  815. }
  816. } else {
  817. return $name.' ('.get_lang('Anonymous').')';
  818. }
  819. }
  820. /**
  821. * this function transforms the array containing all the feedback into something visually attractive.
  822. *
  823. * @param an array containing all the feedback about the given message.
  824. *
  825. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  826. * @version march 2006
  827. */
  828. function feedback($array) {
  829. foreach ($array as $key => $value) {
  830. $output .= format_feedback($value);
  831. }
  832. $output .= feedback_form();
  833. return $output;
  834. }
  835. /**
  836. * This function returns the html code to display the feedback messages on a given dropbox file
  837. * @param $feedback_array an array that contains all the feedback messages about the given document.
  838. * @return html code
  839. * @todo add the form for adding new comment (if the other party has not deleted it yet).
  840. *
  841. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  842. * @version march 2006
  843. */
  844. function format_feedback($feedback) {
  845. $output .= display_user_link_work($feedback['author_user_id']);
  846. $output .= '&nbsp;&nbsp;['.$feedback['feedback_date'].']<br />';
  847. $output .= '<div style="padding-top:6px">'.nl2br($feedback['feedback']).'</div><hr size="1" noshade/><br />';
  848. return $output;
  849. }
  850. /**
  851. * this function returns the code for the form for adding a new feedback message to a dropbox file.
  852. * @return html code
  853. *
  854. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  855. * @version march 2006
  856. */
  857. function feedback_form() {
  858. global $dropbox_cnf;
  859. $return = get_lang('AddNewFeedback').'<br />';
  860. // we now check if the other users have not delete this document yet. If this is the case then it is useless to see the
  861. // add feedback since the other users will never get to see the feedback.
  862. $sql = "SELECT * FROM ".$dropbox_cnf['tbl_person']." WHERE file_id='".Database::escape_string($_GET['id'])."'";
  863. $result = Database::query($sql);
  864. $number_users_who_see_file = Database::num_rows($result);
  865. if ($number_users_who_see_file > 1) {
  866. $token = Security::get_token();
  867. $return .= '<textarea name="feedback" style="width: 80%; height: 80px;"></textarea>';
  868. $return .= '<input type="hidden" name="sec_token" value="'.$token.'"/>';
  869. $return .= '<br /><button type="submit" class="add" name="store_feedback" value="'.get_lang('Ok').'"
  870. onclick="javascript: document.form_tablename.attributes.action.value = document.location;">'.get_lang('AddComment').'</button>';
  871. } else {
  872. $return .= get_lang('AllUsersHaveDeletedTheFileAndWillNotSeeFeedback');
  873. }
  874. return $return;
  875. }
  876. /**
  877. * @return a language string (depending on the success or failure.
  878. *
  879. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  880. * @version march 2006
  881. */
  882. function store_feedback()
  883. {
  884. global $dropbox_cnf;
  885. global $_user;
  886. if (!is_numeric($_GET['id'])) {
  887. return get_lang('FeedbackError');
  888. }
  889. if ($_POST['feedback'] == '') {
  890. return get_lang('PleaseTypeText');
  891. } else {
  892. $sql="INSERT INTO ".$dropbox_cnf['tbl_feedback']." (file_id, author_user_id, feedback, feedback_date) VALUES
  893. ('".Database::escape_string($_GET['id'])."','".Database::escape_string($_user['user_id'])."','".Database::escape_string($_POST['feedback'])."',NOW())";
  894. Database::query($sql);
  895. return get_lang('DropboxFeedbackStored');
  896. }
  897. }
  898. /**
  899. * This function downloads all the files of the inputarray into one zip
  900. * @param $array an array containing all the ids of the files that have to be downloaded.
  901. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  902. * @todo consider removing the check if the user has received or sent this file (zip download of a folder already sufficiently checks for this).
  903. * @todo integrate some cleanup function that removes zip files that are older than 2 days
  904. *
  905. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  906. * @version march 2006
  907. */
  908. function zip_download($array) {
  909. global $_course;
  910. global $dropbox_cnf;
  911. global $_user;
  912. global $files;
  913. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  914. // zip library for creation of the zipfile
  915. require api_get_path(LIBRARY_PATH).'/pclzip/pclzip.lib.php';
  916. // place to temporarily stash the zipfiles
  917. $temp_zip_dir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp/';
  918. // create the directory if it does not exist yet.
  919. if (!is_dir($temp_zip_dir)) {
  920. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  921. }
  922. cleanup_temp_dropbox();
  923. $files = '';
  924. // note: we also have to add the check if the user has received or sent this file.
  925. $sql = "SELECT distinct file.filename, file.title, file.author, file.description
  926. FROM ".$dropbox_cnf['tbl_file']." file, ".$dropbox_cnf['tbl_person']." person
  927. WHERE file.id IN (".implode(', ',$array).")
  928. AND file.id=person.file_id
  929. AND person.user_id='".$_user['user_id']."'";
  930. $result = Database::query($sql);
  931. while ($row = Database::fetch_array($result)) {
  932. $files[$row['filename']] = array('filename' => $row['filename'],'title' => $row['title'], 'author' => $row['author'], 'description' => $row['description']);
  933. }
  934. //$alternative is a variable that uses an alternative method to create the zip
  935. // because the renaming of the files inside the zip causes error on php5 (unexpected end of archive)
  936. $alternative = true;
  937. if ($alternative) {
  938. zip_download_alternative($files);
  939. exit;
  940. }
  941. // create the zip file
  942. $name = 'dropboxdownload-'.$_user['user_id'].'-'.mktime().'.zip';
  943. $temp_zip_file = $temp_zip_dir.'/'.$name;
  944. $zip_folder = new PclZip($temp_zip_file);
  945. foreach ($files as $key => $value) {
  946. // met hernoemen van de files in de zip
  947. $zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox/'.$value['filename'], PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox', PCLZIP_CB_PRE_ADD, 'my_pre_add_callback');
  948. // zonder hernoemen van de files in de zip
  949. //$zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox/'.$value['filename'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox');
  950. }
  951. // create the overview file
  952. $overview_file_content = generate_html_overview($files, array('filename'), array('title'));
  953. $overview_file = $temp_zip_dir.'/overview.html';
  954. $handle = fopen($overview_file, 'w');
  955. fwrite($handle, $overview_file_content);
  956. // send the zip file
  957. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  958. exit;
  959. }
  960. /**
  961. * This is a callback function to decrypt the files in the zip file to their normal filename (as stored in the database)
  962. * @param $p_event a variable of PCLZip
  963. * @param $p_header a variable of PCLZip
  964. *
  965. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  966. * @version march 2006
  967. */
  968. function my_pre_add_callback($p_event, &$p_header) {
  969. global $files;
  970. $p_header['stored_filename'] = $files[$p_header['stored_filename']]['title'];
  971. return 1;
  972. }
  973. /**
  974. * This function is an alternative zip download. It was added because PCLZip causes problems on PHP5 when using PCLZIP_CB_PRE_ADD and a callback function to rename
  975. * the files inside the zip file (dropbox scrambles the files to prevent
  976. * @todo consider using a htaccess that denies direct access to the file but only allows the php file to access it. This would remove the scrambling requirement
  977. * but it would require additional checks to see if the filename of the uploaded file is not used yet.
  978. * @param $files is an associative array that contains the files that the user wants to download (check to see if the user is allowed to download these files already
  979. * happened so the array is clean!!. The key is the filename on the filesystem. The value is an array that contains both the filename on the filesystem and
  980. * the original filename (that will be used in the zip file)
  981. * @todo when we copy the files there might be two files with the same name. We need a function that (recursively) checks this and changes the name
  982. *
  983. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  984. * @version march 2006
  985. */
  986. function zip_download_alternative($files)
  987. {
  988. global $_course;
  989. global $_user;
  990. $temp_zip_dir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp/';
  991. // Step 2: we copy all the original dropbox files to the temp folder and change their name into the original name
  992. foreach ($files as $key => $value) {
  993. $value['title'] = check_file_name(api_strtolower($value['title']));
  994. $files[$value['filename']]['title'] = $value['title'];
  995. copy(api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox/'.$value['filename'], api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp/'.$value['title']);
  996. }
  997. // Step 3: create the zip file and add all the files to it
  998. $temp_zip_file = $temp_zip_dir.'/dropboxdownload-'.$_user['user_id'].'-'.mktime().'.zip';
  999. $zip_folder = new PclZip($temp_zip_file);
  1000. foreach ($files as $key => $value) {
  1001. $zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp/'.$value['title'], PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp');
  1002. }
  1003. // Step 1: create the overview file and add it to the zip
  1004. $overview_file_content = generate_html_overview($files, array('filename'), array('title'));
  1005. $overview_file = $temp_zip_dir.'overview'.replace_dangerous_char(api_is_western_name_order() ? $_user['firstname'].' '.$_user['lastname'] : $_user['lastname'].' '.$_user['firstname'], 'strict').'.html';
  1006. $handle = fopen($overview_file, 'w');
  1007. fwrite($handle, $overview_file_content);
  1008. // todo: find a different solution for this because even 2 seconds is no guarantee.
  1009. sleep(2);
  1010. // Step 4: we add the overview file
  1011. $zip_folder->add($overview_file, PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp');
  1012. // Step 5: send the file for download;
  1013. DocumentManager::file_send_for_download($temp_zip_file, true);
  1014. // Step 6: remove the files in the temp dir
  1015. foreach ($files as $key => $value) {
  1016. unlink(api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp/'.$value['title']);
  1017. }
  1018. //unlink($overview_file);
  1019. exit;
  1020. }
  1021. /**
  1022. * @desc This function checks if the real filename of the dropbox files doesn't already exist in the temp folder. If this is the case then
  1023. * it will generate a different filename;
  1024. *
  1025. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1026. * @version march 2006
  1027. */
  1028. function check_file_name($file_name_2_check, $counter = 0) {
  1029. global $_course;
  1030. $new_file_name = $file_name_2_check;
  1031. if ($counter != 0) {
  1032. $new_file_name = $counter.$new_file_name;
  1033. }
  1034. if (!file_exists(api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp/'.$new_file_name)) {
  1035. return $new_file_name;
  1036. } else {
  1037. $counter++;
  1038. $new_file_name = check_file_name($file_name_2_check, $counter);
  1039. return $new_file_name;
  1040. }
  1041. }
  1042. /**
  1043. * @desc Cleans the temp zip files that were created when users download several files or a whole folder at once.
  1044. * T
  1045. * @return true
  1046. * @todo
  1047. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1048. * @version march 2006
  1049. */
  1050. function cleanup_temp_dropbox() {
  1051. global $_course;
  1052. $handle = opendir(api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp');
  1053. while (false !== ($file = readdir($handle))) {
  1054. if ($file != '.' OR $file != '..') {
  1055. $name = str_replace('.zip', '', $file);
  1056. $name_part = explode('-', $name);
  1057. $timestamp_of_file = $name_part[count($name_part) - 1];
  1058. // if it is a dropboxdownloadfile and the file is older than one day then we delete it
  1059. if (strstr($file, 'dropboxdownload') AND $timestamp_of_file < (mktime() - 86400)) {
  1060. unlink(api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp/'.$file);
  1061. }
  1062. }
  1063. }
  1064. closedir($handle);
  1065. return true;
  1066. }
  1067. /**
  1068. * @desc Generates the contents of a html file that gives an overview of all the files in the zip file.
  1069. * This is to know the information of the files that are inside the zip file (who send it, the comment, ...)
  1070. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, March 2006
  1071. * @author Ivan Tcholakov, 2010, code for html metadata has been added.
  1072. */
  1073. function generate_html_overview($files, $dont_show_columns = array(), $make_link = array()) {
  1074. $return = '<!DOCTYPE html'."\n";
  1075. $return .= "\t".'PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'."\n";
  1076. $return .= "\t".'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n";
  1077. $return .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.api_get_language_isocode().'" lang="'.api_get_language_isocode().'">'."\n";
  1078. $return .= "<head>\n\t<title>".get_lang('OverviewOfFilesInThisZip')."</title>\n";
  1079. $return .= "\t".'<meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />'."\n";
  1080. $return .= "</head>\n\n";
  1081. $return .= '<body dir="'.api_get_text_direction().'">'."\n\n";
  1082. $return .= "<table border=\"1px\">\n";
  1083. $counter = 0;
  1084. foreach ($files as $key => $value) {
  1085. // Adding the header.
  1086. if ($counter == 0) {
  1087. $columns_array = array_keys($value);
  1088. $return .= "\n<tr>";
  1089. foreach ($columns_array as $columns_array_key => $columns_array_value) {
  1090. if (!in_array($columns_array_value, $dont_show_columns)) {
  1091. $return .= "\n\t<th>".$columns_array_value."</th>";
  1092. }
  1093. $column[] = $columns_array_value;
  1094. }
  1095. $return .= "\n</tr>\n";
  1096. }
  1097. $counter++;
  1098. // Adding the content.
  1099. $return .= "\n<tr>";
  1100. foreach ($column as $column_key => $column_value) {
  1101. if (!in_array($column_value,$dont_show_columns)) {
  1102. $return .= "\n\t<td>";
  1103. if (in_array($column_value, $make_link)) {
  1104. $return .= '<a href="'.$value[$column_value].'">'.$value[$column_value].'</a>';
  1105. } else {
  1106. $return .= $value[$column_value];
  1107. }
  1108. $return .= "</td>";
  1109. }
  1110. }
  1111. $return .= "\n</tr>\n";
  1112. }
  1113. $return .= "\n</table>\n\n</body>";
  1114. $return .= "\n</html>";
  1115. return $return;
  1116. }
  1117. /**
  1118. * @desc This function retrieves the number of feedback messages on every document. This function might become obsolete when
  1119. * the feedback becomes user individual.
  1120. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1121. * @version march 2006
  1122. */
  1123. function get_total_number_feedback($file_id = '') {
  1124. global $dropbox_cnf;
  1125. $sql = "SELECT COUNT(feedback_id) AS total, file_id FROM ".$dropbox_cnf['tbl_feedback']." GROUP BY file_id";
  1126. $result=Database::query($sql);
  1127. while ($row=Database::fetch_array($result)) {
  1128. $return[$row['file_id']] = $row['total'];
  1129. }
  1130. return $return;
  1131. }
  1132. /**
  1133. * @desc this function checks if the key exists. If this is the case it returns the value, if not it returns 0
  1134. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1135. * @version march 2006
  1136. */
  1137. function check_number_feedback($key, $array) {
  1138. if (is_array($array)) {
  1139. if (key_exists($key, $array)) {
  1140. return $array[$key];
  1141. } else {
  1142. return 0;
  1143. }
  1144. } else {
  1145. return 0;
  1146. }
  1147. }
  1148. /**
  1149. * Get the last access to a given tool of a given user
  1150. * @param $tool string the tool constant
  1151. * @param $course_code the course_id
  1152. * @param $user_id the id of the user
  1153. * @return string last tool access date
  1154. *
  1155. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1156. * @version march 2006
  1157. *
  1158. * @todo consider moving this function to a more appropriate place.
  1159. */
  1160. function get_last_tool_access($tool, $course_code='', $user_id='') {
  1161. global $_course, $_user;
  1162. // The default values of the parameters
  1163. if ($course_code == '') {
  1164. $course_code = $_course['id'];
  1165. }
  1166. if ($user_id == '') {
  1167. $user_id = $_user['user_id'];
  1168. }
  1169. // the table where the last tool access is stored (=track_e_lastaccess)
  1170. $table_last_access = Database::get_statistic_table('track_e_lastaccess');
  1171. $sql = "SELECT access_date FROM $table_last_access WHERE access_user_id='".Database::escape_string($user_id)."'
  1172. AND access_cours_code='".Database::escape_string($course_code)."'
  1173. AND access_tool='".Database::escape_string($tool)."'
  1174. ORDER BY access_date DESC
  1175. LIMIT 1";
  1176. $result = Database::query($sql);
  1177. $row = Database::fetch_array($result);
  1178. return $row['access_date'];
  1179. }