dropbox_functions.inc.php 51 KB

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