dropbox_functions.inc.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  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 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. {
  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 $part are we moving a received file or a sent file?
  187. *
  188. * @return language 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 html 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. * @return boolean indicating if user with user_id=$user_id is a course member
  688. * @todo check if this function is still necessary. There might be a library function for this.
  689. */
  690. function isCourseMember($user_id)
  691. {
  692. $_course = api_get_course_info();
  693. $course_code = $_course['code'];
  694. $is_course_member = CourseManager::is_user_subscribed_in_course($user_id, $course_code, true);
  695. return $is_course_member;
  696. }
  697. /**
  698. * Checks if there are files in the dropbox_file table that aren't used anymore in dropbox_person table.
  699. * If there are, all entries concerning the file are deleted from the db + the file is deleted from the server
  700. */
  701. function removeUnusedFiles()
  702. {
  703. $course_id = api_get_course_int_id();
  704. // select all files that aren't referenced anymore
  705. $sql = "SELECT DISTINCT f.id, f.filename
  706. FROM " . dropbox_cnf('tbl_file') . " f
  707. LEFT JOIN " . dropbox_cnf('tbl_person') . " p
  708. ON (f.id = p.file_id)
  709. WHERE p.user_id IS NULL AND
  710. f.c_id = $course_id
  711. ";
  712. $result = Database::query($sql);
  713. while ($res = Database::fetch_array($result)) {
  714. //delete the selected files from the post and file tables
  715. $sql = "DELETE FROM " . dropbox_cnf('tbl_post') . "
  716. WHERE c_id = $course_id AND file_id = '" . $res['id'] . "'";
  717. Database::query($sql);
  718. $sql = "DELETE FROM " . dropbox_cnf('tbl_file') . "
  719. WHERE c_id = $course_id AND id ='" . $res['id'] . "'";
  720. Database::query($sql);
  721. //delete file from server
  722. @unlink( dropbox_cnf('sysPath') . '/' . $res['filename']);
  723. }
  724. }
  725. /**
  726. *
  727. * Mailing zip-file is posted to (dest_user_id = ) mailing pseudo_id
  728. * and is only visible to its uploader (user_id).
  729. *
  730. * Mailing content files have uploader_id == mailing pseudo_id, a normal recipient,
  731. * and are visible initially to recipient and pseudo_id.
  732. *
  733. * @author René Haentjens, Ghent University
  734. *
  735. * @todo check if this function is still necessary.
  736. */
  737. function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '')
  738. {
  739. $course_id = api_get_course_int_id();
  740. $dropbox_cnf = getDropboxConf();
  741. $mailingPseudoId = intval($mailingPseudoId);
  742. $sql = "SELECT f.uploader_id
  743. FROM " . $dropbox_cnf['tbl_file'] . " f
  744. LEFT JOIN " . $dropbox_cnf['tbl_post'] . " p
  745. ON (f.id = p.file_id AND f.c_id = $course_id AND p.c_id = $course_id)
  746. WHERE
  747. p.dest_user_id = '" . $mailingPseudoId . "' AND
  748. p.c_id = $course_id
  749. ";
  750. $result = Database::query($sql);
  751. if (!($res = Database::fetch_array($result)))
  752. die(get_lang('GeneralError').' (code 901)');
  753. if ($owner == 0) return $res['uploader_id'];
  754. if ($res['uploader_id'] == $owner) return true;
  755. die(get_lang('GeneralError').' (code '.$or_die.')');
  756. }
  757. /**
  758. * @author René Haentjens, Ghent University
  759. * @todo check if this function is still necessary.
  760. */
  761. function removeMoreIfMailing($file_id)
  762. {
  763. $course_id = api_get_course_int_id();
  764. $dropbox_cnf = getDropboxConf();
  765. // when deleting a mailing zip-file (posted to mailingPseudoId):
  766. // 1. the detail window is no longer reachable, so
  767. // for all content files, delete mailingPseudoId from person-table
  768. // 2. finding the owner (getUserOwningThisMailing) is no longer possible, so
  769. // for all content files, replace mailingPseudoId by owner as uploader
  770. $file_id = intval($file_id);
  771. $sql = "SELECT p.dest_user_id
  772. FROM " . $dropbox_cnf['tbl_post'] . " p
  773. WHERE c_id = $course_id AND p.file_id = '" . $file_id . "'";
  774. $result = Database::query($sql);
  775. if ($res = Database::fetch_array($result)) {
  776. $mailingPseudoId = $res['dest_user_id'];
  777. if ($mailingPseudoId > dropbox_cnf('mailingIdBase')) {
  778. $sql = "DELETE FROM " . dropbox_cnf('tbl_person') . "
  779. WHERE c_id = $course_id AND user_id='" . $mailingPseudoId . "'";
  780. Database::query($sql);
  781. $sql = "UPDATE " . dropbox_cnf('tbl_file') ."
  782. SET uploader_id='" . api_get_user_id() . "'
  783. WHERE c_id = $course_id AND uploader_id='" . $mailingPseudoId . "'";
  784. Database::query($sql);
  785. }
  786. }
  787. }
  788. /**
  789. * Function that finds a given config setting
  790. *
  791. * @author René Haentjens, Ghent University
  792. */
  793. function dropbox_cnf($variable)
  794. {
  795. $dropbox_cnf = getDropboxConf();
  796. return $dropbox_cnf[$variable];
  797. }
  798. /**
  799. * @param array $file
  800. *
  801. * @return array|null|string
  802. */
  803. function store_add_dropbox($file = [])
  804. {
  805. $_course = api_get_course_info();
  806. $_user = api_get_user_info();
  807. $dropbox_cnf = getDropboxConf();
  808. if (empty($file)) {
  809. $file = isset($_FILES['file']) ? $_FILES['file'] : null;
  810. }
  811. // Validating the form data
  812. // there are no recipients selected
  813. if (!isset($_POST['recipients']) || count($_POST['recipients']) <= 0) {
  814. return get_lang('YouMustSelectAtLeastOneDestinee');
  815. } else {
  816. // Check if all the recipients are valid
  817. $thisIsAMailing = false;
  818. $thisIsJustUpload = false;
  819. foreach ($_POST['recipients'] as $rec) {
  820. if ($rec == 'mailing') {
  821. $thisIsAMailing = true;
  822. } elseif ($rec == 'upload') {
  823. $thisIsJustUpload = true;
  824. } elseif (strpos($rec, 'user_') === 0 && !isCourseMember(substr($rec, strlen('user_')))) {
  825. Display::addFlash(Display::return_message(get_lang('InvalideUserDetected'), 'warning'));
  826. return false;
  827. } elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0) {
  828. Display::addFlash(Display::return_message(get_lang('InvalideGroupDetected'), 'warning'));
  829. return false;
  830. }
  831. }
  832. }
  833. // we are doing a mailing but an additional recipient is selected
  834. if ($thisIsAMailing && (count($_POST['recipients']) != 1)) {
  835. Display::addFlash(Display::return_message(get_lang('MailingSelectNoOther'), 'warning'));
  836. return false;
  837. }
  838. // we are doing a just upload but an additional recipient is selected.
  839. // note: why can't this be valid? It is like sending a document to
  840. // yourself AND to a different person (I do this quite often with my e-mails)
  841. if ($thisIsJustUpload && (count($_POST['recipients']) != 1)) {
  842. Display::addFlash(Display::return_message(get_lang('MailingJustUploadSelectNoOther'), 'warning'));
  843. return false;
  844. }
  845. if (empty($file['name'])) {
  846. Display::addFlash(Display::return_message(get_lang('NoFileSpecified'), 'warning'));
  847. return false;
  848. }
  849. // are we overwriting a previous file or sending a new one
  850. $dropbox_overwrite = false;
  851. if (isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']) {
  852. $dropbox_overwrite = true;
  853. }
  854. // doing the upload
  855. $dropbox_filename = $file['name'];
  856. $dropbox_filesize = $file['size'];
  857. $dropbox_filetype = $file['type'];
  858. $dropbox_filetmpname = $file['tmp_name'];
  859. // check if the filesize does not exceed the allowed size.
  860. if ($dropbox_filesize <= 0 || $dropbox_filesize > $dropbox_cnf['maxFilesize']) {
  861. Display::addFlash(Display::return_message(get_lang('DropboxFileTooBig'), 'warning'));
  862. return false;
  863. }
  864. // check if the file is actually uploaded
  865. if (!is_uploaded_file($dropbox_filetmpname)) { // check user fraud : no clean error msg.
  866. Display::addFlash(Display::return_message(get_lang('TheFileIsNotUploaded'), 'warning'));
  867. return false;
  868. }
  869. $upload_ok = process_uploaded_file($file, true);
  870. if (!$upload_ok) {
  871. return null;
  872. }
  873. // Try to add an extension to the file if it hasn't got one
  874. $dropbox_filename = add_ext_on_mime($dropbox_filename, $dropbox_filetype);
  875. // Replace dangerous characters
  876. $dropbox_filename = api_replace_dangerous_char($dropbox_filename);
  877. // Transform any .php file in .phps fo security
  878. $dropbox_filename = php2phps($dropbox_filename);
  879. //filter extension
  880. if (!filter_extension($dropbox_filename)) {
  881. Display::addFlash(Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'warning'));
  882. return false;
  883. }
  884. // set title
  885. $dropbox_title = $dropbox_filename;
  886. // set author
  887. if (!isset($_POST['authors'])) {
  888. $_POST['authors'] = getUserNameFromId($_user['user_id']);
  889. }
  890. // note: I think we could better migrate everything from here on to
  891. // separate functions: store_new_dropbox, store_new_mailing, store_just_upload
  892. if ($dropbox_overwrite) {
  893. $dropbox_person = new Dropbox_Person(
  894. $_user['user_id'],
  895. api_is_course_admin(),
  896. api_is_course_tutor()
  897. );
  898. foreach ($dropbox_person->sentWork as $w) {
  899. if ($w->title == $dropbox_filename) {
  900. if (($w->recipients[0]['id'] > dropbox_cnf('mailingIdBase')) xor $thisIsAMailing) {
  901. Display::addFlash(Display::return_message(get_lang('MailingNonMailingError'), 'warning'));
  902. return false;
  903. }
  904. if (($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload) {
  905. Display::addFlash(Display::return_message(get_lang('MailingJustUploadSelectNoOther'), 'warning'));
  906. return false;
  907. }
  908. $dropbox_filename = $w->filename;
  909. $found = true; // note: do we still need this?
  910. break;
  911. }
  912. }
  913. } else { // rename file to login_filename_uniqueId format
  914. $dropbox_filename = getLoginFromId($_user['user_id']) . "_" . $dropbox_filename . "_".uniqid('');
  915. }
  916. // creating the array that contains all the users who will receive the file
  917. $new_work_recipients = array();
  918. foreach ($_POST['recipients'] as $rec) {
  919. if (strpos($rec, 'user_') === 0) {
  920. $new_work_recipients[] = substr($rec, strlen('user_'));
  921. } elseif (strpos($rec, 'group_') === 0) {
  922. $userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_')));
  923. foreach ($userList as $usr) {
  924. if (!in_array($usr['user_id'], $new_work_recipients) && $usr['user_id'] != $_user['user_id']) {
  925. $new_work_recipients[] = $usr['user_id'];
  926. }
  927. }
  928. }
  929. }
  930. @move_uploaded_file($dropbox_filetmpname, dropbox_cnf('sysPath') . '/' . $dropbox_filename);
  931. $b_send_mail = api_get_course_setting('email_alert_on_new_doc_dropbox');
  932. if ($b_send_mail) {
  933. foreach ($new_work_recipients as $recipient_id) {
  934. $recipent_temp = api_get_user_info($recipient_id);
  935. $additionalParameters = array(
  936. 'smsType' => SmsPlugin::NEW_FILE_SHARED_COURSE_BY,
  937. 'userId' => $recipient_id,
  938. 'courseTitle' => $_course['title'],
  939. 'userUsername' => $recipent_temp['username']
  940. );
  941. api_mail_html(
  942. api_get_person_name(
  943. $recipent_temp['firstname'].' '.$recipent_temp['lastname'],
  944. null,
  945. PERSON_NAME_EMAIL_ADDRESS
  946. ),
  947. $recipent_temp['email'],
  948. get_lang('NewDropboxFileUploaded'),
  949. get_lang('NewDropboxFileUploadedContent').' <a href="'.api_get_path(WEB_CODE_PATH).'dropbox/index.php?' . api_get_cidreq() . '">'.get_lang('SeeFile').'</a>'.
  950. "\n\n".
  951. api_get_person_name(
  952. $_user['firstName'],
  953. $_user['lastName'],
  954. null,
  955. PERSON_NAME_EMAIL_ADDRESS
  956. )."\n". get_lang('Email') ." : ".$_user['mail'],
  957. api_get_person_name(
  958. $_user['firstName'],
  959. $_user['lastName'],
  960. null,
  961. PERSON_NAME_EMAIL_ADDRESS
  962. ),
  963. $_user['mail'],
  964. null,
  965. null,
  966. null,
  967. $additionalParameters
  968. );
  969. }
  970. }
  971. $result = new Dropbox_SentWork(
  972. $_user['user_id'],
  973. $dropbox_title,
  974. isset($_POST['description']) ? $_POST['description'] : '',
  975. strip_tags($_POST['authors']),
  976. $dropbox_filename,
  977. $dropbox_filesize,
  978. $new_work_recipients
  979. );
  980. Security::clear_token();
  981. Display::addFlash(Display::return_message(get_lang('FileUploadSucces')));
  982. return $result;
  983. }
  984. /**
  985. * Transforms the array containing all the feedback into something visually attractive.
  986. *
  987. * @param an array containing all the feedback about the given message.
  988. *
  989. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  990. * @version march 2006
  991. */
  992. function feedback($array) {
  993. $output = null;
  994. foreach ($array as $value) {
  995. $output .= format_feedback($value);
  996. }
  997. $output .= feedback_form();
  998. return $output;
  999. }
  1000. /**
  1001. * This function returns the html code to display the feedback messages on a given dropbox file
  1002. * @param $feedback_array an array that contains all the feedback messages about the given document.
  1003. * @return html code
  1004. * @todo add the form for adding new comment (if the other party has not deleted it yet).
  1005. *
  1006. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1007. * @version march 2006
  1008. */
  1009. function format_feedback($feedback)
  1010. {
  1011. $userInfo = api_get_user_info($feedback['author_user_id']);
  1012. $output = UserManager::getUserProfileLink($userInfo);
  1013. $output .= '&nbsp;&nbsp;'.api_convert_and_format_date($feedback['feedback_date'], DATE_TIME_FORMAT_LONG).'<br />';
  1014. $output .= '<div style="padding-top:6px">'.nl2br($feedback['feedback']).'</div><hr size="1" noshade/><br />';
  1015. return $output;
  1016. }
  1017. /**
  1018. * this function returns the code for the form for adding a new feedback message to a dropbox file.
  1019. * @return html code
  1020. *
  1021. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1022. * @version march 2006
  1023. */
  1024. function feedback_form()
  1025. {
  1026. $return = get_lang('AddNewFeedback').'<br />';
  1027. $number_users_who_see_file = check_if_file_exist($_GET['id']);
  1028. if ($number_users_who_see_file) {
  1029. $token = Security::get_token();
  1030. $return .= '<textarea name="feedback" style="width: 80%; height: 80px;"></textarea>';
  1031. $return .= '<input type="hidden" name="sec_token" value="'.$token.'"/>';
  1032. $return .= '<br /><button type="submit" class="add" name="store_feedback" value="'.get_lang('Ok').'"
  1033. onclick="javascript: document.form_dropbox.attributes.action.value = document.location;">'.get_lang('AddComment').'</button>';
  1034. } else {
  1035. $return .= get_lang('AllUsersHaveDeletedTheFileAndWillNotSeeFeedback');
  1036. }
  1037. return $return;
  1038. }
  1039. function user_can_download_file($id, $user_id)
  1040. {
  1041. $dropbox_cnf = getDropboxConf();
  1042. $course_id = api_get_course_int_id();
  1043. $id = intval($id);
  1044. $user_id = intval($user_id);
  1045. $sql = "SELECT file_id FROM ".$dropbox_cnf['tbl_person']."
  1046. WHERE c_id = $course_id AND user_id = $user_id AND file_id = ".$id;
  1047. $result = Database::query($sql);
  1048. $number_users_who_see_file = Database::num_rows($result);
  1049. $sql = "SELECT file_id FROM ".$dropbox_cnf["tbl_post"]."
  1050. WHERE c_id = $course_id AND dest_user_id = $user_id AND file_id = ".$id;
  1051. $result = Database::query($sql);
  1052. $count = Database::num_rows($result);
  1053. return $number_users_who_see_file > 0 || $count > 0;
  1054. }
  1055. // we now check if the other users have not delete this document yet.
  1056. // If this is the case then it is useless to see the
  1057. // add feedback since the other users will never get to see the feedback.
  1058. function check_if_file_exist($id)
  1059. {
  1060. $dropbox_cnf = getDropboxConf();
  1061. $id = intval($id);
  1062. $course_id = api_get_course_int_id();
  1063. $sql = "SELECT file_id FROM ".$dropbox_cnf['tbl_person']."
  1064. WHERE c_id = $course_id AND file_id = ".$id;
  1065. $result = Database::query($sql);
  1066. $number_users_who_see_file = Database::num_rows($result);
  1067. $sql = "SELECT file_id FROM ".$dropbox_cnf["tbl_post"]."
  1068. WHERE c_id = $course_id AND file_id = ".$id;
  1069. $result = Database::query($sql);
  1070. $count = Database::num_rows($result);
  1071. return $number_users_who_see_file > 0 || $count > 0;
  1072. }
  1073. /**
  1074. * @return a language string (depending on the success or failure.
  1075. *
  1076. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1077. * @version march 2006
  1078. */
  1079. function store_feedback()
  1080. {
  1081. $dropbox_cnf = getDropboxConf();
  1082. if (!is_numeric($_GET['id'])) {
  1083. return get_lang('FeedbackError');
  1084. }
  1085. $course_id = api_get_course_int_id();
  1086. if (empty($_POST['feedback'])) {
  1087. return get_lang('PleaseTypeText');
  1088. } else {
  1089. $params = [
  1090. 'c_id' => $course_id,
  1091. 'file_id' => $_GET['id'],
  1092. 'author_user_id' => api_get_user_id(),
  1093. 'feedback' => $_POST['feedback'],
  1094. 'feedback_date' => api_get_utc_datetime(),
  1095. ];
  1096. $id = Database::insert($dropbox_cnf['tbl_feedback'], $params);
  1097. if ($id) {
  1098. $sql = "UPDATE ".$dropbox_cnf['tbl_feedback']." SET feedback_id = iid WHERE iid = $id";
  1099. Database::query($sql);
  1100. }
  1101. return get_lang('DropboxFeedbackStored');
  1102. }
  1103. }
  1104. /**
  1105. * This function downloads all the files of the input array into one zip
  1106. * @param array $fileList containing all the ids of the files that have to be downloaded.
  1107. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1108. * @todo consider removing the check if the user has received or sent this file (zip download of a folder already sufficiently checks for this).
  1109. * @todo integrate some cleanup function that removes zip files that are older than 2 days
  1110. *
  1111. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1112. * @author Julio Montoya Addin c_id support
  1113. * @version march 2006
  1114. */
  1115. function zip_download($fileList)
  1116. {
  1117. $_course = api_get_course_info();
  1118. $dropbox_cnf = getDropboxConf();
  1119. $course_id = api_get_course_int_id();
  1120. $fileList = array_map('intval', $fileList);
  1121. // note: we also have to add the check if the user has received or sent this file.
  1122. $sql = "SELECT DISTINCT file.filename, file.title, file.author, file.description
  1123. FROM ".$dropbox_cnf['tbl_file']." file
  1124. INNER JOIN ".$dropbox_cnf['tbl_person']." person
  1125. ON (person.file_id=file.id AND file.c_id = $course_id AND person.c_id = $course_id)
  1126. INNER JOIN ".$dropbox_cnf['tbl_post']." post
  1127. ON (post.file_id = file.id AND post.c_id = $course_id AND file.c_id = $course_id)
  1128. WHERE
  1129. file.id IN (".implode(', ', $fileList).") AND
  1130. file.id = person.file_id AND
  1131. (
  1132. person.user_id = '".api_get_user_id()."' OR
  1133. post.dest_user_id = '".api_get_user_id()."'
  1134. ) ";
  1135. $result = Database::query($sql);
  1136. $files = array();
  1137. while ($row = Database::fetch_array($result)) {
  1138. $files[$row['filename']] = array(
  1139. 'filename' => $row['filename'],
  1140. 'title' => $row['title'],
  1141. 'author' => $row['author'],
  1142. 'description' => $row['description']
  1143. );
  1144. }
  1145. // Step 3: create the zip file and add all the files to it
  1146. $temp_zip_file = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip";
  1147. Session::write('dropbox_files_to_download', $files);
  1148. $zip = new PclZip($temp_zip_file);
  1149. foreach ($files as $value) {
  1150. $zip->add(
  1151. api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox/'.$value['filename'],
  1152. PCLZIP_OPT_REMOVE_ALL_PATH,
  1153. PCLZIP_CB_PRE_ADD,
  1154. 'my_pre_add_callback'
  1155. );
  1156. }
  1157. Session::erase('dropbox_files_to_download');
  1158. $name = 'dropbox-'.api_get_utc_datetime().'.zip';
  1159. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  1160. @unlink($temp_zip_file);
  1161. exit;
  1162. }
  1163. /**
  1164. * This is a callback function to decrypt the files in the zip file to their normal filename (as stored in the database)
  1165. * @param array $p_event a variable of PCLZip
  1166. * @param array $p_header a variable of PCLZip
  1167. *
  1168. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1169. * @version march 2006
  1170. */
  1171. function my_pre_add_callback($p_event, &$p_header)
  1172. {
  1173. $files = Session::read('dropbox_files_to_download');
  1174. $p_header['stored_filename'] = $files[$p_header['stored_filename']]['title'];
  1175. return 1;
  1176. }
  1177. /**
  1178. * @desc Generates the contents of a html file that gives an overview of all the files in the zip file.
  1179. * This is to know the information of the files that are inside the zip file (who send it, the comment, ...)
  1180. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, March 2006
  1181. * @author Ivan Tcholakov, 2010, code for html metadata has been added.
  1182. */
  1183. function generate_html_overview($files, $dont_show_columns = array(), $make_link = array())
  1184. {
  1185. $return = '<!DOCTYPE html'."\n";
  1186. $return .= "\t".'PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'."\n";
  1187. $return .= "\t".'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n";
  1188. $return .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.api_get_language_isocode().'" lang="'.api_get_language_isocode().'">'."\n";
  1189. $return .= "<head>\n\t<title>".get_lang('OverviewOfFilesInThisZip')."</title>\n";
  1190. $return .= "\t".'<meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />'."\n";
  1191. $return .= "</head>\n\n";
  1192. $return .= '<body dir="'.api_get_text_direction().'">'."\n\n";
  1193. $return .= "<table border=\"1px\">\n";
  1194. $counter = 0;
  1195. foreach ($files as $value) {
  1196. // Adding the header.
  1197. if ($counter == 0) {
  1198. $columns_array = array_keys($value);
  1199. $return .= "\n<tr>";
  1200. foreach ($columns_array as $columns_array_key => $columns_array_value) {
  1201. if (!in_array($columns_array_value, $dont_show_columns)) {
  1202. $return .= "\n\t<th>".$columns_array_value."</th>";
  1203. }
  1204. $column[] = $columns_array_value;
  1205. }
  1206. $return .= "\n</tr>\n";
  1207. }
  1208. $counter++;
  1209. // Adding the content.
  1210. $return .= "\n<tr>";
  1211. foreach ($column as $column_key => $column_value) {
  1212. if (!in_array($column_value,$dont_show_columns)) {
  1213. $return .= "\n\t<td>";
  1214. if (in_array($column_value, $make_link)) {
  1215. $return .= '<a href="'.$value[$column_value].'">'.$value[$column_value].'</a>';
  1216. } else {
  1217. $return .= $value[$column_value];
  1218. }
  1219. $return .= "</td>";
  1220. }
  1221. }
  1222. $return .= "\n</tr>\n";
  1223. }
  1224. $return .= "\n</table>\n\n</body>";
  1225. $return .= "\n</html>";
  1226. return $return;
  1227. }
  1228. /**
  1229. * @desc This function retrieves the number of feedback messages on every document. This function might become obsolete when
  1230. * the feedback becomes user individual.
  1231. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1232. * @version march 2006
  1233. */
  1234. function get_total_number_feedback($file_id = '')
  1235. {
  1236. $dropbox_cnf = getDropboxConf();
  1237. $course_id = api_get_course_int_id();
  1238. $sql = "SELECT COUNT(feedback_id) AS total, file_id
  1239. FROM ".$dropbox_cnf['tbl_feedback']."
  1240. WHERE c_id = $course_id GROUP BY file_id";
  1241. $result = Database::query($sql);
  1242. $return = array();
  1243. while ($row=Database::fetch_array($result)) {
  1244. $return[$row['file_id']] = $row['total'];
  1245. }
  1246. return $return;
  1247. }
  1248. /**
  1249. * @desc this function checks if the key exists. If this is the case it returns the value, if not it returns 0
  1250. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1251. * @version march 2006
  1252. */
  1253. function check_number_feedback($key, $array)
  1254. {
  1255. if (is_array($array)) {
  1256. if (array_key_exists($key, $array)) {
  1257. return $array[$key];
  1258. } else {
  1259. return 0;
  1260. }
  1261. } else {
  1262. return 0;
  1263. }
  1264. }
  1265. /**
  1266. * Get the last access to a given tool of a given user
  1267. * @param $tool string the tool constant
  1268. * @param $courseId the course_id
  1269. * @param $user_id the id of the user
  1270. * @return string last tool access date
  1271. *
  1272. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1273. * @version march 2006
  1274. *
  1275. * @todo consider moving this function to a more appropriate place.
  1276. */
  1277. function get_last_tool_access($tool, $courseId = null, $user_id = null)
  1278. {
  1279. // The default values of the parameters
  1280. if (empty($courseId)) {
  1281. $courseId = api_get_course_int_id();
  1282. }
  1283. if (empty($user_id)) {
  1284. $user_id = api_get_user_id();
  1285. }
  1286. // the table where the last tool access is stored (=track_e_lastaccess)
  1287. $table_last_access = Database::get_main_table('track_e_lastaccess');
  1288. $sql = "SELECT access_date FROM $table_last_access
  1289. WHERE
  1290. access_user_id = ".intval($user_id)." AND
  1291. c_id='".intval($courseId)."' AND
  1292. access_tool='".Database::escape_string($tool)."'
  1293. ORDER BY access_date DESC
  1294. LIMIT 1";
  1295. $result = Database::query($sql);
  1296. $row = Database::fetch_array($result);
  1297. return $row['access_date'];
  1298. }