work.lib.php 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * @package chamilo.work
  5. * @author Thomas, Hugues, Christophe - original version
  6. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University - ability for course admins to specify wether uploaded documents are visible or invisible by default.
  7. * @author Roan Embrechts, code refactoring and virtual course support
  8. * @author Frederic Vauthier, directories management
  9. * @author Julio Montoya <gugli100@gmail.com> BeezNest 2011 LOTS of bug fixes
  10. * @todo this lib should be convert in a static class and moved to magein/inc/lib
  11. */
  12. /**
  13. * Initialization
  14. */
  15. require_once api_get_path(SYS_CODE_PATH).'document/document.inc.php';
  16. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
  17. if (isset($_configuration['add_document_to_work'])) {
  18. define('ADD_DOCUMENT_TO_WORK', $_configuration['add_document_to_work']);
  19. } else {
  20. define('ADD_DOCUMENT_TO_WORK', false);
  21. }
  22. /**
  23. * Displays action links (for admins, authorized groups members and authorized students)
  24. * @param string Current dir
  25. * @param integer Whether to show tool options
  26. * @param integer Whether to show upload form option
  27. * @return void
  28. */
  29. function display_action_links($id, $cur_dir_path, $action)
  30. {
  31. global $gradebook;
  32. $id = $my_back_id = intval($id);
  33. if ($action == 'list') {
  34. $my_back_id = 0;
  35. }
  36. $display_output = '';
  37. $origin = isset($_GET['origin']) ? Security::remove_XSS($_GET['origin']) : '';
  38. if (!empty($id)) {
  39. $display_output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&origin='.$origin.'&gradebook='.$gradebook.'&id='.$my_back_id.'">'.Display::return_icon('back.png', get_lang('BackToWorksList'),'',ICON_SIZE_MEDIUM).'</a>';
  40. }
  41. if (api_is_allowed_to_edit(null, true) && $origin != 'learnpath') {
  42. // Create dir
  43. if (empty($id)) {
  44. $display_output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;action=create_dir&origin='.$origin.'&gradebook='.$gradebook.'">';
  45. $display_output .= Display::return_icon('new_work.png', get_lang('CreateAssignment'),'',ICON_SIZE_MEDIUM).'</a>';
  46. }
  47. if (empty($id)) {
  48. // Options
  49. $display_output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;action=settings&amp;origin='.$origin.'&amp;gradebook='.$gradebook.'">';
  50. $display_output .= Display::return_icon('settings.png', get_lang('EditToolOptions'),'',ICON_SIZE_MEDIUM).'</a>';
  51. }
  52. }
  53. if (api_is_allowed_to_edit(null, true) && $origin != 'learnpath' && api_is_allowed_to_session_edit(false, true)) {
  54. // Delete all files
  55. if (api_get_setting('permanently_remove_deleted_files') == 'true'){
  56. $message = get_lang('ConfirmYourChoiceDeleteAllfiles');
  57. } else {
  58. $message = get_lang('ConfirmYourChoice');
  59. }
  60. }
  61. if ($display_output != '') {
  62. echo '<div class="actions">';
  63. echo $display_output;
  64. echo '</div>';
  65. }
  66. }
  67. /**
  68. * Displays all options for this tool.
  69. * These are
  70. * - make all files visible / invisible
  71. * - set the default visibility of uploaded files
  72. *
  73. * @param $uploadvisibledisabled
  74. * @param $origin
  75. */
  76. function display_tool_options($uploadvisibledisabled, $origin) {
  77. global $gradebook;
  78. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  79. if (!$is_allowed_to_edit) {
  80. return;
  81. }
  82. echo '<form class="form-horizontal" method="post" action="'.api_get_self().'?origin='.$origin.'&gradebook='.$gradebook.'&action=settings">';
  83. echo '<legend>'.get_lang('EditToolOptions').'</legend>';
  84. display_default_visibility_form($uploadvisibledisabled);
  85. display_studentsdelete_form();
  86. echo '<div class="row">
  87. <div class="formw">
  88. <button type="submit" class="save" name="changeProperties" value="'.get_lang('Ok').'">'.get_lang('Ok').'</button>
  89. </div>
  90. </div>';
  91. echo '</form>';
  92. }
  93. /**
  94. * Displays the form where course admins can specify wether uploaded documents
  95. * are visible or invisible by default.
  96. *
  97. * @param $uploadvisibledisabled
  98. * @param $origin
  99. */
  100. function display_default_visibility_form($uploadvisibledisabled) {
  101. ?>
  102. <div class="control-group">
  103. <label class="control-label">
  104. <?php echo get_lang('DefaultUpload'); ?>
  105. </label>
  106. <div class="controls">
  107. <label class="radio" for="uploadvisibledisabled_1">
  108. <input id="uploadvisibledisabled_1" class="checkbox" type="radio" name="uploadvisibledisabled" value="0" <?php if ($uploadvisibledisabled == 0) echo 'checked'; ?> />
  109. <?php echo get_lang('NewVisible'); ?>
  110. </label>
  111. <label class="radio" for="uploadvisibledisabled_2">
  112. <input id="uploadvisibledisabled_2" class="checkbox" type="radio" name="uploadvisibledisabled" value="1" <?php if ($uploadvisibledisabled == 1) echo 'checked'; ?> />
  113. <?php echo get_lang('NewUnvisible'); ?>
  114. </label>
  115. </div>
  116. </div>
  117. <?php
  118. }
  119. /**
  120. * Display a part of the form to edit the settings of the tool
  121. * In this case weither the students are allowed to delete their own publication or not (by default not)
  122. *
  123. * @return html code
  124. * @since Dokeos 1.8.6.2
  125. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  126. */
  127. function display_studentsdelete_form() {
  128. // by default api_get_course_setting returns -1 and the code only expects 0 or 1 so anything tha
  129. // is different than 1 will be converted into 0
  130. $current_course_setting_value = api_get_course_setting('student_delete_own_publication');
  131. if ($current_course_setting_value != 1) {
  132. $current_course_setting_value = 0;
  133. }
  134. ?>
  135. <div class="control-group">
  136. <label class="control-label"><?php echo get_lang('StudentAllowedToDeleteOwnPublication'); ?></label>
  137. <div class="controls">
  138. <label class="radio" for="student_delete_own_publication_2">
  139. <input id="student_delete_own_publication_2" class="checkbox" type="radio" name="student_delete_own_publication" value="1" <?php if ($current_course_setting_value == 1) echo 'checked'; ?> />
  140. <?php echo get_lang('Yes'); ?>
  141. </label>
  142. <label class="radio" for="student_delete_own_publication_1">
  143. <input id="student_delete_own_publication_1" class="checkbox" type="radio" name="student_delete_own_publication" value="0"
  144. <?php if ($current_course_setting_value == 0) echo 'checked'; ?> />
  145. <?php echo get_lang('No'); ?>
  146. </label>
  147. </div>
  148. </div>
  149. <?php
  150. }
  151. /**
  152. * converts 2008-10-06 12:45:00 to timestamp
  153. * @deprecated any calls found
  154. */
  155. function convert_date_to_number($default) {
  156. // 2008-10-12 00:00:00 ---to--> 12345672218 (timestamp)
  157. $parts = split(' ', $default);
  158. list($d_year, $d_month, $d_day) = split('-', $parts[0]);
  159. list($d_hour, $d_minute, $d_second) = split(':', $parts[1]);
  160. return mktime((int)$d_hour, (int)$d_minute, (int)$d_second, (int)$d_month, (int)$d_day, (int)$d_year);
  161. }
  162. /**
  163. * converts 1-9 to 01-09
  164. */
  165. function two_digits($number) {
  166. $number = (int)$number;
  167. return ($number < 10) ? '0'.$number : $number;
  168. }
  169. /**
  170. * converts 2008-10-06 12:45:00 to -> array($data'year'=>2008,$data'month'=>10 etc...)
  171. */
  172. function convert_date_to_array($date, $group) {
  173. $parts = split(' ', $date);
  174. $date_parts = split('-', $parts[0]);
  175. $date_parts_tmp = array();
  176. foreach ($date_parts as $item) {
  177. $date_parts_tmp[] = intval($item);
  178. }
  179. $time_parts = split(':', $parts[1]);
  180. $time_parts_tmp = array();
  181. foreach ($time_parts as $item) {
  182. $time_parts_tmp[] = intval($item);
  183. }
  184. list($data[$group.'[year]'], $data[$group.'[month]'], $data[$group.'[day]']) = $date_parts_tmp;
  185. list($data[$group.'[hour]'], $data[$group.'[minute]']) = $time_parts_tmp;
  186. return $data;
  187. }
  188. /**
  189. * get date from a group of date
  190. */
  191. function get_date_from_group($group) {
  192. return $_POST[$group]['year'].'-'.two_digits($_POST[$group]['month']).'-'.two_digits($_POST[$group]['day']).' '.two_digits($_POST[$group]['hour']).':'.two_digits($_POST[$group]['minute']).':00';
  193. }
  194. /**
  195. * create a group of select from a date
  196. */
  197. function create_group_date_select($prefix = '') {
  198. $minute = range(10, 59);
  199. $d_year = date('Y');
  200. array_unshift($minute, '00', '01', '02', '03', '04', '05', '06', '07', '08', '09');
  201. $group_name[] = FormValidator :: createElement('select', $prefix.'day', '', array_combine(range(1, 31), range(1, 31)));
  202. $group_name[] = FormValidator :: createElement('select', $prefix.'month', '', array_combine(range(1, 12), api_get_months_long()));
  203. $group_name[] = FormValidator :: createElement('select', $prefix.'year', '', array($d_year => $d_year, $d_year + 1 => $d_year + 1));
  204. $group_name[] = FormValidator :: createElement('select', $prefix.'hour', '', array_combine(range(0, 23), range(0, 23)));
  205. $group_name[] = FormValidator :: createElement('select', $prefix.'minute', '', $minute);
  206. return $group_name;
  207. }
  208. function get_work_data_by_path($path) {
  209. $path = Database::escape_string($path);
  210. $course_id = api_get_course_int_id();
  211. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  212. $sql = "SELECT * FROM ".$work_table." WHERE url = '$path' AND c_id = $course_id ";
  213. $result = Database::query($sql);
  214. $return = array();
  215. if (Database::num_rows($result)) {
  216. $return = Database::fetch_array($result,'ASSOC');
  217. }
  218. return $return;
  219. }
  220. function get_work_data_by_id($id) {
  221. $id = intval($id);
  222. $course_id = api_get_course_int_id();
  223. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  224. $sql = "SELECT * FROM $work_table WHERE id = $id AND c_id = $course_id";
  225. $result = Database::query($sql);
  226. $return = array();
  227. if (Database::num_rows($result)) {
  228. $return = Database::fetch_array($result, 'ASSOC');
  229. }
  230. return $return;
  231. }
  232. /**
  233. * @param int $user_id
  234. * @param int $work_id
  235. * @return int
  236. */
  237. function get_work_count_by_student($user_id, $work_id) {
  238. $user_id = intval($user_id);
  239. $work_id = intval($work_id);
  240. $course_id = api_get_course_int_id();
  241. $session_id = api_get_session_id();
  242. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  243. $sql = "SELECT COUNT(*) as count FROM $work_table
  244. WHERE c_id = $course_id AND parent_id = $work_id AND user_id = $user_id AND active = 1 AND session_id = $session_id ";
  245. $result = Database::query($sql);
  246. $return = 0;
  247. if (Database::num_rows($result)) {
  248. $return = Database::fetch_row($result,'ASSOC');
  249. $return = intval($return[0]);
  250. }
  251. return $return;
  252. }
  253. /**
  254. * @param int $id
  255. * @return array
  256. */
  257. function get_work_assignment_by_id($id) {
  258. $id = intval($id);
  259. $course_id = api_get_course_int_id();
  260. $table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  261. $sql = "SELECT * FROM $table WHERE c_id = $course_id AND publication_id = $id";
  262. $result = Database::query($sql);
  263. $return = array();
  264. if (Database::num_rows($result)) {
  265. $return = Database::fetch_array($result,'ASSOC');
  266. }
  267. return $return;
  268. }
  269. /**
  270. * @param int $id
  271. * @param array $my_folder_data
  272. * @param string $add_in_where_query
  273. * @return array
  274. */
  275. function getWorkList($id, $my_folder_data, $add_in_where_query)
  276. {
  277. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  278. $course_id = api_get_course_int_id();
  279. $session_id = api_get_session_id();
  280. $condition_session = api_get_session_condition($session_id);
  281. $group_id = api_get_group_id();
  282. $link_info = is_resource_in_course_gradebook(api_get_course_id(), 3 , $id, api_get_session_id());
  283. $work_in_gradebook_link_id = $link_info['id'];
  284. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  285. if ($work_in_gradebook_link_id) {
  286. if ($is_allowed_to_edit)
  287. if (intval($my_folder_data['qualification']) == 0) {
  288. Display::display_warning_message(get_lang('MaxWeightNeedToBeProvided'));
  289. }
  290. }
  291. $contains_file_query = '';
  292. //Get list from database
  293. if ($is_allowed_to_edit) {
  294. $active_condition = ' active IN (0, 1)';
  295. $sql_get_publications_list = "SELECT * FROM $work_table
  296. WHERE c_id = $course_id $add_in_where_query $condition_session AND $active_condition AND (parent_id = 0) $contains_file_query ";
  297. if (!empty($group_id)) {
  298. $sql_get_publications_list .= " AND post_group_id = '".$group_id."' ";
  299. }
  300. $sql_get_publications_list .= " ORDER BY sent_date DESC";
  301. } else {
  302. if (!empty($group_id)) {
  303. $group_query = " WHERE c_id = $course_id AND post_group_id = '".$group_id."' "; // set to select only messages posted by the user's group
  304. $subdirs_query = "AND parent_id = 0";
  305. } else {
  306. $group_query = " WHERE c_id = $course_id AND post_group_id = '0' ";
  307. $subdirs_query = "AND parent_id = 0";
  308. }
  309. //@todo how we can active or not an assignment?
  310. $active_condition = ' AND active IN (1,0)';
  311. $sql_get_publications_list = "SELECT * FROM $work_table $group_query $subdirs_query $add_in_where_query $active_condition $condition_session ORDER BY title";
  312. }
  313. $work_parents = array();
  314. $sql_result = Database::query($sql_get_publications_list);
  315. if (Database::num_rows($sql_result)) {
  316. while ($work = Database::fetch_object($sql_result)) {
  317. if ($work->parent_id == 0) {
  318. $work_parents[] = $work;
  319. }
  320. }
  321. }
  322. return $work_parents;
  323. }
  324. /**
  325. * @param int $userId
  326. * @return array
  327. */
  328. function getWorkPerUser($userId)
  329. {
  330. $works = getWorkList(null, null, null);
  331. $result = array();
  332. if (!empty($works)) {
  333. foreach ($works as $workData) {
  334. $workId = $workData->id;
  335. $result[$workId]['work'] = $workData;
  336. $result[$workId]['work']->user_results = get_work_user_list(0, 100, null, null, $workId, null, $userId);
  337. }
  338. }
  339. return $result;
  340. }
  341. /**
  342. * @param int $workId
  343. * @param int $course_id
  344. * @param int $sessionId
  345. * @param int $userId user id to filter
  346. * @param array $onlyUserList only parse this user list
  347. * @return mixed
  348. */
  349. function getUniqueStudentAttempts($workId, $groupId, $course_id, $sessionId, $userId = null, $onlyUserList = array())
  350. {
  351. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  352. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  353. $course_id = intval($course_id);
  354. $workId = intval($workId);
  355. $sessionId = intval($sessionId);
  356. $groupId = intval($groupId);
  357. $studentCondition = null;
  358. if (!empty($onlyUserList)) {
  359. $studentCondition = "AND u.user_id IN ('".implode("', '", $onlyUserList)."') ";
  360. } else {
  361. if (empty($userId)) {
  362. return 0;
  363. }
  364. }
  365. $sql_document = "SELECT count(*) FROM (
  366. SELECT count(*)
  367. FROM $work_table w INNER JOIN $user_table u ON w.user_id = u.user_id
  368. WHERE w.c_id = $course_id AND
  369. w.session_id = $sessionId AND
  370. w.parent_id = ".$workId." AND
  371. w.post_group_id = ".$groupId." AND
  372. w.active IN (0, 1) $studentCondition
  373. ";
  374. if (!empty($userId)) {
  375. $userId = intval($userId);
  376. $sql_document .= " AND u.user_id = ".$userId;
  377. }
  378. $sql_document .= " GROUP BY u.user_id) as t";
  379. $res_document = Database::query($sql_document);
  380. $rowCount = Database::fetch_row($res_document);
  381. return $rowCount[0];
  382. }
  383. /**
  384. * Display the list of student publications, taking into account the user status
  385. *
  386. * @param $origin - typically empty or 'learnpath'
  387. */
  388. function display_student_publications_list($id, $my_folder_data, $work_parents, $origin, $add_in_where_query = '', $userList = array())
  389. {
  390. global $gradebook;
  391. $_course = api_get_course_info();
  392. // Database table names
  393. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  394. $iprop_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  395. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  396. $work_assigment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  397. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  398. $session_id = api_get_session_id();
  399. $condition_session = api_get_session_condition($session_id);
  400. $course_id = api_get_course_int_id();
  401. $course_info = api_get_course_info(api_get_course_id());
  402. $sort_params = array();
  403. if (isset($_GET['column'])) {
  404. $sort_params[] = 'column='.Security::remove_XSS($_GET['column']);
  405. }
  406. if (isset($_GET['page_nr'])) {
  407. $sort_params[] = 'page_nr='.Security::remove_XSS($_GET['page_nr']);
  408. }
  409. if (isset($_GET['per_page'])) {
  410. $sort_params[] = 'per_page='.Security::remove_XSS($_GET['per_page']);
  411. }
  412. if (isset($_GET['direction'])) {
  413. $sort_params[] = 'direction='.Security::remove_XSS($_GET['direction']);
  414. }
  415. $sort_params = implode('&amp;', $sort_params);
  416. $my_params = $sort_params;
  417. $origin = Security::remove_XSS($origin);
  418. $qualification_exists = false;
  419. if (!empty($my_folder_data['qualification']) && intval($my_folder_data['qualification']) > 0) {
  420. $qualification_exists = true;
  421. }
  422. $edit_dir = isset($_GET['edit_dir']) ? intval($_GET['edit_dir']) : '';
  423. $table_header = array();
  424. $table_has_actions_column = false;
  425. $table_header[] = array(get_lang('Type'), false, 'style="width:40px"');
  426. $table_header[] = array(get_lang('Title'), true);
  427. if (!empty($id)) {
  428. $table_header[] = array(get_lang('FirstName'), true);
  429. $table_header[] = array(get_lang('LastName'), true);
  430. }
  431. $table_header[] = array(get_lang('HandOutDateLimit'), true, 'style="width:200px"');
  432. if ($is_allowed_to_edit) {
  433. $table_header[] = array(get_lang('HandedOut'), false);
  434. $table_header[] = array(get_lang('Actions'), false, 'style="width:90px"', array('class'=>'td_actions'));
  435. $table_has_actions_column = true;
  436. if ($qualification_exists) {
  437. $table_header[] = array(get_lang('Qualification'), true);
  438. }
  439. } else {
  440. // All users
  441. if ($course_info['show_score'] == 0) {
  442. $table_header[] = array(get_lang('Others'), false);
  443. }
  444. }
  445. $table_data = array();
  446. // List of all folders if no id was provided
  447. $group_id = api_get_group_id();
  448. if (is_array($work_parents)) {
  449. foreach ($work_parents as $work_parent) {
  450. $sql_select_directory = "SELECT
  451. title,
  452. url,
  453. prop.insert_date,
  454. prop.lastedit_date,
  455. work.id, author,
  456. has_properties,
  457. view_properties,
  458. description,
  459. qualification,
  460. weight,
  461. allow_text_assignment
  462. FROM ".$iprop_table." prop INNER JOIN ".$work_table." work ON (prop.ref=work.id AND prop.c_id = $course_id)
  463. WHERE active IN (0, 1) AND ";
  464. if (!empty($group_id)) {
  465. $sql_select_directory .= " work.post_group_id = '".$group_id."' "; // set to select only messages posted by the user's group
  466. } else {
  467. $sql_select_directory .= " work.post_group_id = '0' ";
  468. }
  469. $sql_select_directory .= " AND ".
  470. " work.c_id = $course_id AND ".
  471. " work.id = ".$work_parent->id." AND ".
  472. " work.filetype = 'folder' AND ".
  473. " prop.tool='work' $condition_session";
  474. $result = Database::query($sql_select_directory);
  475. $row = Database::fetch_array($result, 'ASSOC');
  476. if (!$row) {
  477. // the folder belongs to another session
  478. continue;
  479. }
  480. $direc_date = $row['lastedit_date']; //directory's date
  481. $author = $row['author']; //directory's author
  482. $view_properties = $row['view_properties'];
  483. $is_assignment = $row['has_properties'];
  484. $id2 = $row['id']; //work id
  485. $locked = api_resource_is_locked_by_gradebook($id2, LINK_STUDENTPUBLICATION);
  486. // form edit directory
  487. if (!empty($row['has_properties'])) {
  488. $sql = Database::query('SELECT * FROM '.$work_assigment.' WHERE c_id = '.$course_id.' AND id = "'.$row['has_properties'].'" LIMIT 1');
  489. $homework = Database::fetch_array($sql);
  490. }
  491. // save original value for later
  492. $utc_expiry_time = $homework['expires_on'];
  493. if ($is_allowed_to_edit && $locked == false) {
  494. if (!empty($edit_dir) && $edit_dir == $id2) {
  495. $form_folder = new FormValidator('edit_dir', 'post', api_get_self().'?origin='.$origin.'&gradebook='.$gradebook.'&edit_dir='.$id2);
  496. $form_folder->addElement('text', 'dir_name', get_lang('Title'));
  497. $form_folder->addElement('hidden', 'work_id', $id2);
  498. $form_folder -> addRule('dir_name', get_lang('ThisFieldIsRequired'), 'required');
  499. $my_title = !empty($row['title']) ? $row['title'] : basename($row['url']);
  500. $defaults = array('dir_name' => Security::remove_XSS($my_title), 'description' => Security::remove_XSS($row['description']));
  501. $form_folder->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'work', 'Width' => '80%', 'Height' => '200'));
  502. $there_is_a_end_date = false;
  503. $form_folder->addElement('advanced_settings', 'work', get_lang('AdvancedParameters'));
  504. $form_folder->addElement('html', '<div id="work_options" style="display: none;">');
  505. if (empty($default)) {
  506. $default = api_get_local_time();
  507. }
  508. $parts = explode(' ', $default);
  509. list($d_year, $d_month, $d_day) = explode('-', $parts[0]);
  510. list($d_hour, $d_minute) = explode(':', $parts[1]);
  511. $qualification_input[] = $form_folder->createElement('text', 'qualification');
  512. $form_folder -> addGroup($qualification_input, 'qualification', get_lang('QualificationNumeric'));
  513. if (Gradebook::is_active()) {
  514. $link_info = is_resource_in_course_gradebook(api_get_course_id(), LINK_STUDENTPUBLICATION, $id2);
  515. $form_folder -> addElement('checkbox', 'make_calification', null, get_lang('MakeQualifiable'), 'onclick="javascript: if(this.checked){document.getElementById(\'option3\').style.display = \'block\';}else{document.getElementById(\'option3\').style.display = \'none\';}"');
  516. if (!empty($link_info)) {
  517. $form_folder -> addElement('html', '<div id=\'option3\' style="display:block">');
  518. } else {
  519. $form_folder -> addElement('html', '<div id=\'option3\' style="display:none">');
  520. }
  521. //Loading gradebook select
  522. load_gradebook_select_in_tool($form_folder);
  523. $weight_input2[] = $form_folder->createElement('text', 'weight');
  524. $form_folder -> addGroup($weight_input2, 'weight', get_lang('WeightInTheGradebook'), 'size="10"');
  525. $form_folder -> addElement('html', '</div>');
  526. $defaults['weight[weight]'] = $link_info['weight'];
  527. if (!empty($link_info)) {
  528. $defaults['category_id'] = $link_info['category_id'];
  529. $defaults['make_calification'] = 1;
  530. }
  531. } else {
  532. $defaults['category_id'] = '';
  533. }
  534. if ($homework['expires_on'] != '0000-00-00 00:00:00') {
  535. $homework['expires_on'] = api_get_local_time($homework['expires_on']);
  536. $there_is_a_expire_date = true;
  537. $defaults['enableExpiryDate'] = true;
  538. $form_folder -> addElement('checkbox', 'enableExpiryDate',null,get_lang('EnableExpiryDate'), 'onclick="javascript: if(this.checked){document.getElementById(\'option1\').style.display = \'block\';}else{document.getElementById(\'option1\').style.display = \'none\';}"');
  539. $form_folder -> addElement('html', '<div id=\'option1\' style="display:block">');
  540. $form_folder -> addGroup(create_group_date_select(), 'expires', get_lang('ExpiresAt'));
  541. $form_folder -> addElement('html', '</div>');
  542. } else {
  543. $homework['expires_on'] = api_get_local_time();
  544. $expires_date_array = convert_date_to_array(api_get_local_time(), 'expires');
  545. $defaults = array_merge($defaults, $expires_date_array);
  546. $there_is_a_expire_date = false;
  547. $form_folder -> addElement('checkbox', 'enableExpiryDate',null,get_lang('EnableExpiryDate'), 'onclick="javascript: if(this.checked){document.getElementById(\'option1\').style.display = \'block\';}else{document.getElementById(\'option1\').style.display = \'none\';}"');
  548. $form_folder -> addElement('html', '<div id=\'option1\' style="display:none">');
  549. $form_folder -> addGroup(create_group_date_select(), 'expires', get_lang('ExpiresAt'));
  550. $form_folder -> addElement('html', '</div>');
  551. }
  552. if ($homework['ends_on'] != '0000-00-00 00:00:00') {
  553. $homework['ends_on'] = api_get_local_time($homework['ends_on']);
  554. $there_is_a_end_date = true;
  555. $defaults['enableEndDate'] = true;
  556. $form_folder -> addElement('checkbox', 'enableEndDate', null, get_lang('EnableEndDate'), 'onclick="javascript: if(this.checked){document.getElementById(\'option2\').style.display = \'block\';}else{document.getElementById(\'option2\').style.display = \'none\';}"');
  557. $form_folder -> addElement('html', '<div id=\'option2\' style="display:block">');
  558. $form_folder -> addGroup(create_group_date_select(), 'ends', get_lang('EndsAt'));
  559. $form_folder -> addElement('html', '</div>');
  560. $form_folder -> addRule(array('expires', 'ends'), get_lang('DateExpiredNotBeLessDeadLine'), 'comparedate');
  561. } else {
  562. $homework['ends_on'] = api_get_local_time();
  563. $expires_date_array = convert_date_to_array(api_get_local_time(), 'ends');
  564. $defaults = array_merge($defaults, $expires_date_array);
  565. $there_is_a_end_date = false;
  566. $form_folder -> addElement('checkbox', 'enableEndDate', null, get_lang('EnableEndDate'), 'onclick="javascript: if(this.checked){document.getElementById(\'option2\').style.display = \'block\';}else{document.getElementById(\'option2\').style.display = \'none\';}"');
  567. $form_folder -> addElement('html', '<div id=\'option2\' style="display:none">');
  568. $form_folder -> addGroup(create_group_date_select(), 'ends', get_lang('EndsAt'));
  569. $form_folder -> addElement('html', '</div>');
  570. $form_folder -> addRule(array('expires', 'ends'), get_lang('DateExpiredNotBeLessDeadLine'), 'comparedate');
  571. }
  572. if ($there_is_a_expire_date && $there_is_a_end_date) {
  573. $form_folder -> addRule(array('expires', 'ends'), get_lang('DateExpiredNotBeLessDeadLine'), 'comparedate');
  574. }
  575. $form_folder -> addElement('checkbox', 'allow_text_assignment', null, get_lang('AllowTextAssignments'));
  576. $form_folder -> addElement('html', '</div>');
  577. $form_folder -> addElement('style_submit_button', 'submit', get_lang('ModifyDirectory'), 'class="save"');
  578. if ($there_is_a_end_date) {
  579. $end_date_array = convert_date_to_array($homework['ends_on'], 'ends');
  580. $defaults = array_merge($defaults, $end_date_array);
  581. }
  582. if ($there_is_a_expire_date) {
  583. $expires_date_array = convert_date_to_array($homework['expires_on'], 'expires');
  584. $defaults = array_merge($defaults, $expires_date_array);
  585. }
  586. if (!empty($row['qualification'])) {
  587. $defaults = array_merge($defaults, array('qualification[qualification]' => $row['qualification']));
  588. }
  589. $defaults['allow_text_assignment'] = $row['allow_text_assignment'];
  590. $form_folder -> setDefaults($defaults);
  591. $display_edit_form = true;
  592. if ($form_folder->validate()) {
  593. if ($_POST['enableExpiryDate'] == '1') {
  594. $there_is_a_expire_date = true;
  595. } else {
  596. $there_is_a_expire_date = false;
  597. }
  598. if ($_POST['enableEndDate'] == '1') {
  599. $there_is_a_end_date = true;
  600. } else {
  601. $there_is_a_end_date = false;
  602. }
  603. $values = $form_folder->exportValues();
  604. $work_id = $values['work_id'];
  605. $dir_name = replace_dangerous_char($values['dir_name']);
  606. $dir_name = disable_dangerous_file($dir_name);
  607. $edit_check = false;
  608. $work_data = get_work_data_by_id($work_id);
  609. if (!empty($work_data)) {
  610. $edit_check = true;
  611. } else {
  612. $edit_check = true;
  613. }
  614. if ($edit_check) {
  615. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  616. $expires_query = ' SET expires_on = '."'".($there_is_a_expire_date ? api_get_utc_datetime(get_date_from_group('expires')) : '0000-00-00 00:00:00')."'";
  617. Database::query('UPDATE '.$work_assigment.$expires_query.' WHERE c_id = '.$course_id.' AND id = '."'".$row['has_properties']."'");
  618. $sql_add_publication = "UPDATE ".$work_table." SET has_properties = '".$row['has_properties']. "', view_properties=1 WHERE c_id = $course_id AND id ='".$row['id']."'";
  619. Database::query($sql_add_publication);
  620. $ends_query = ' SET ends_on = '."'".($there_is_a_end_date ? api_get_utc_datetime(get_date_from_group('ends')) : '0000-00-00 00:00:00')."'";
  621. Database::query('UPDATE '.$work_assigment.$ends_query.' WHERE c_id = '.$course_id.' AND id = '."'".$row['has_properties']."'");
  622. $sql_add_publication = "UPDATE ".$work_table." SET has_properties = '".$row['has_properties']. "', view_properties=1 WHERE c_id = $course_id AND id ='".$row['id']."'";
  623. Database::query($sql_add_publication);
  624. $qualification_value = isset($_POST['qualification']['qualification']) && !empty($_POST['qualification']['qualification']) ? intval($_POST['qualification']['qualification']) : 0;
  625. $enable_qualification = !empty($qualification_value) ? 1 : 0;
  626. $sql_add_publication = "UPDATE ".$work_assigment." SET enable_qualification = '".$enable_qualification. "' WHERE c_id = $course_id AND publication_id ='".$row['id']."'";
  627. Database::query($sql_add_publication);
  628. $sql = 'UPDATE '.$work_table.' SET
  629. allow_text_assignment = '."'".intval($_POST['allow_text_assignment'])."'".' ,
  630. title = '."'".Database::escape_string($_POST['dir_name'])."'".',
  631. description = '."'".Database::escape_string($_POST['description'])."'".',
  632. qualification = '."'".Database::escape_string($_POST['qualification']['qualification'])."'".',
  633. weight = '."'".Database::escape_string($_POST['weight']['weight'])."'".'
  634. WHERE c_id = '.$course_id.' AND id = '.$row['id'];
  635. Database::query($sql);
  636. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
  637. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/gradebookitem.class.php';
  638. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/evaluation.class.php';
  639. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/abstractlink.class.php';
  640. $link_info = is_resource_in_course_gradebook(api_get_course_id(), LINK_STUDENTPUBLICATION, $row['id'], api_get_session_id());
  641. $link_id = null;
  642. if (!empty($link_info)) {
  643. $link_id = $link_info['id'];
  644. }
  645. if (isset($_POST['make_calification']) && $_POST['make_calification'] == 1 && !empty($_POST['category_id'])) {
  646. if (empty($link_id)) {
  647. add_resource_to_course_gradebook($_POST['category_id'], api_get_course_id(), LINK_STUDENTPUBLICATION, $row['id'], $_POST['dir_name'], (float)$_POST['weight']['weight'], (float)$_POST['qualification']['qualification'], $_POST['description'], 1, api_get_session_id(), $link_id);
  648. } else {
  649. update_resource_from_course_gradebook($link_id, api_get_course_id(), $_POST['weight']['weight']);
  650. }
  651. } else {
  652. //Delete everything of the gradebook
  653. remove_resource_from_course_gradebook($link_id);
  654. }
  655. update_dir_name($work_data, $dir_name, $values['dir_name']);
  656. $dir = $dir_name;
  657. $display_edit_form = false;
  658. // gets calendar_id from student_publication_assigment
  659. $sql = "SELECT add_to_calendar FROM $work_assigment WHERE c_id = $course_id AND publication_id ='".$row['id']."'";
  660. $res = Database::query($sql);
  661. $calendar_id = Database::fetch_row($res);
  662. $dir_name = sprintf(get_lang('HandingOverOfTaskX'), $dir_name);
  663. $end_date = $row['insert_date'];
  664. if ($_POST['enableExpiryDate'] == '1') {
  665. $end_date = Database::escape_string(api_get_utc_datetime(get_date_from_group('expires')));
  666. }
  667. // update from agenda if it exists
  668. if (!empty($calendar_id[0])) {
  669. $sql = "UPDATE ".$TABLEAGENDA."
  670. SET title='".$values['dir_name']."',
  671. content = '".Database::escape_string($_POST['description'])."',
  672. start_date = '".$end_date."',
  673. end_date = '".$end_date."'
  674. WHERE c_id = $course_id AND id='".$calendar_id[0]."'";
  675. Database::query($sql);
  676. }
  677. Display::display_confirmation_message(get_lang('FolderEdited'));
  678. } else {
  679. Display::display_warning_message(get_lang('FileExists'));
  680. }
  681. }
  682. }
  683. }
  684. $work_data = get_work_data_by_id($work_parent->id);
  685. $action = '';
  686. $row = array();
  687. $class = '';
  688. $course_id = api_get_course_int_id();
  689. $session_id = api_get_session_id();
  690. if (api_is_allowed_to_edit()) {
  691. $cant_files = get_count_work($work_data['id']);
  692. } else {
  693. $isSubscribed = userIsSubscribedToWork(api_get_user_id(), $work_data['id'], $course_id);
  694. if ($isSubscribed == false) {
  695. continue;
  696. }
  697. $cant_files = get_count_work($work_data['id'], api_get_user_id());
  698. }
  699. $text_file = get_lang('FilesUpload');
  700. if ($cant_files == 1) {
  701. $text_file = api_strtolower(get_lang('FileUpload'));
  702. }
  703. $icon = Display::return_icon('work.png', get_lang('Assignment'), array(), ICON_SIZE_SMALL);
  704. if (!empty($display_edit_form) && !empty($edit_dir) && $edit_dir == $id2) {
  705. $row[] = $icon;
  706. $row[] = '<span class="invisible" style="display:none">'.$dir.'</span>'.$form_folder->toHtml(); // form to edit the directory's name
  707. } else {
  708. $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq().'&origin='.$origin.'&gradebook='.$gradebook.'">'.$icon.'</a>';
  709. $add_to_name = '';
  710. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
  711. $link_info = is_resource_in_course_gradebook(api_get_course_id(), 3 , $id2 , api_get_session_id());
  712. $link_id = $link_info['id'];
  713. $count = 0;
  714. if ($link_info !== false) {
  715. $gradebook_data = get_resource_from_course_gradebook($link_id);
  716. $count = $gradebook_data['weight'];
  717. }
  718. if ($count > 0) {
  719. $add_to_name = Display::label(get_lang('IncludedInEvaluation'), 'info');
  720. } else {
  721. $add_to_name = '';
  722. }
  723. $work_title = !empty($work_data['title']) ? $work_data['title'] : basename($work_data['url']);
  724. // Work name
  725. if ($cant_files > 0 ) {
  726. $zip = '<a href="downloadfolder.inc.php?id='.$work_data['id'].'">'.Display::return_icon('save_pack.png', get_lang('Save'), array('style' => 'float:right;'), ICON_SIZE_SMALL).'</a>';
  727. }
  728. $link = 'work_list.php';
  729. if (api_is_allowed_to_edit()) {
  730. $link = 'work_list_all.php';
  731. }
  732. $url = $zip.'<a href="'.api_get_path(WEB_CODE_PATH).'work/'.$link.'?'.api_get_cidreq().'&origin='.$origin.'&gradebook='.Security::remove_XSS($_GET['gradebook']).'&id='.$work_data['id'].'"'.$class.'>'.
  733. $work_title.'</a> '.$add_to_name.'<br />'.$cant_files.' '.$text_file.$dirtext;
  734. $row[] = $url;
  735. }
  736. if ($count_files != 0) {
  737. $row[] = '';
  738. }
  739. if (!empty($homework)) {
  740. // use original utc value saved previously to avoid doubling the utc-to-local conversion ($homework['expires_on'] might have been tainted)
  741. $row[] = !empty($utc_expiry_time) && $utc_expiry_time != '0000-00-00 00:00:00' ? api_get_local_time($utc_expiry_time): '-';
  742. } else {
  743. $row[] = '-';
  744. }
  745. if (!$is_allowed_to_edit) {
  746. if ($course_info['show_score'] == 0) {
  747. $url = api_get_path(WEB_CODE_PATH).'work/work_list_others.php?'.api_get_cidreq().'&id='.$work_parent->id;
  748. $row[] = Display::url(Display::return_icon('group.png', get_lang('Others')), $url);
  749. }
  750. }
  751. if ($origin != 'learnpath') {
  752. if ($is_allowed_to_edit) {
  753. $cant_files_per_user = getUniqueStudentAttempts($work_data['id'], $group_id, $course_id, api_get_session_id(), null, $userList);
  754. $row[] = $cant_files_per_user.'/'.count($userList);
  755. if (api_resource_is_locked_by_gradebook($id2, LINK_STUDENTPUBLICATION)) {
  756. $action .= Display::return_icon('edit_na.png', get_lang('Edit'), array(), ICON_SIZE_SMALL);
  757. $action .= Display::return_icon('delete_na.png', get_lang('Delete'), array(), ICON_SIZE_SMALL);
  758. } else {
  759. $action .= '<a href="'.api_get_self().'?cidReq='.api_get_course_id().'&origin='.$origin.'&gradebook='.$gradebook.'&edit_dir='.$id2.'">'.Display::return_icon('edit.png', get_lang('Modify'), array(), ICON_SIZE_SMALL).'</a>';
  760. $action .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&origin='.$origin.'&gradebook='.$gradebook.'&delete_dir='.$id2.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('DirDelete').'" >'.Display::return_icon('delete.png',get_lang('DirDelete'),'',ICON_SIZE_SMALL).'</a>';
  761. }
  762. $row[] = $action;
  763. } else {
  764. $row[] = '';
  765. }
  766. }
  767. //$row[] = $direc_date_local;
  768. $row[] = $work_data['title'];
  769. $table_data[] = $row;
  770. }
  771. }
  772. $sorting_options = array();
  773. $sorting_options['column'] = 1;
  774. // Here we change the way how the columns are going to be sorted
  775. // in this case the the column of LastResent ( 4th element in $column_header) we will be order like the column RealDate
  776. // because in the column RealDate we have the days in a correct format "2008-03-12 10:35:48"
  777. $column_order = array();
  778. $i=0;
  779. foreach($table_header as $item) {
  780. $column_order[$i] = $i;
  781. $i++;
  782. }
  783. if (empty($my_folder_data)) {
  784. $column_order[1] = 5;
  785. } else {
  786. $column_order[2] = 2;
  787. }
  788. // An array with the setting of the columns -> 1: columns that we will show, 0:columns that will be hide
  789. $column_show = array();
  790. $column_show[] = 1; // type 0
  791. $column_show[] = 1; // title 1
  792. if (!empty($my_folder_data)) {
  793. $column_show[] = 1; // 2
  794. $column_show[] = 1; // 3
  795. if ($qualification_exists) {
  796. $column_show[] = 1; // 4
  797. }
  798. }
  799. $column_show[] = 1; //date
  800. if ($table_has_actions_column) {
  801. $column_show[] = 1; // modify
  802. }
  803. $column_show[] = 1; //real date in correct format
  804. $column_show[] = 0; //real date in correct format
  805. $paging_options = array();
  806. if (isset($_GET['curdirpath'])) {
  807. $my_params = array ('curdirpath' => Security::remove_XSS($_GET['curdirpath']));
  808. }
  809. $my_params = array ('id' => isset($_GET['id']) ? $_GET['id'] : null);
  810. if (isset($_GET['edit_dir'])) {
  811. $my_params = array ('edit_dir' => intval($_GET['edit_dir']));
  812. }
  813. $my_params['origin'] = $origin;
  814. Display::display_sortable_config_table('work', $table_header, $table_data, $sorting_options, $paging_options, $my_params, $column_show, $column_order);
  815. }
  816. /**
  817. * Returns a list of subdirectories found in the given directory.
  818. *
  819. * The list return starts from the given base directory.
  820. * If you require the subdirs of /var/www/ (or /var/www), you will get 'abc/', 'def/', but not '/var/www/abc/'...
  821. * @param string Base dir
  822. * @param integer 0 if we only want dirs from this level, 1 if we want to recurse into subdirs
  823. * @return strings_array The list of subdirs in 'abc/' form, -1 on error, and 0 if none found
  824. * @todo Add a session check to see if subdirs_list doesn't exist yet (cached copy)
  825. */
  826. function get_subdirs_list($basedir = '', $recurse = 0) {
  827. //echo "Looking for subdirs of $basedir";
  828. if (empty($basedir) or !is_dir($basedir)) {
  829. return -1;
  830. }
  831. if (substr($basedir, -1, 1) != '/') {
  832. $basedir = $basedir.'/';
  833. }
  834. $dirs_list = array();
  835. $dh = opendir($basedir);
  836. while ($entry = readdir($dh)) {
  837. $entry = replace_dangerous_char($entry);
  838. $entry = disable_dangerous_file($entry);
  839. if (is_dir($basedir.$entry) && $entry != '..' && $entry != '.') {
  840. $dirs_list[] = $entry;
  841. if ($recurse == 1) {
  842. foreach (get_subdirs_list($basedir.$entry) as $subdir) {
  843. $dirs_list[] = $entry.'/'.$subdir;
  844. }
  845. }
  846. }
  847. }
  848. closedir($dh);
  849. return $dirs_list;
  850. }
  851. /**
  852. * Builds the form thats enables the user to
  853. * select a directory to browse/upload in
  854. * This function has been copied from the document/document.inc.php library
  855. *
  856. * @param array $folders
  857. * @param string $curdirpath
  858. * @param string $group_dir
  859. * @return string html form
  860. */
  861. // TODO: This function is a candidate for removal, it is not used anywhere.
  862. function build_work_directory_selector($folders, $curdirpath, $group_dir = '') {
  863. $form = '<form name="selector" action="'.api_get_self().'?'.api_get_cidreq().'" method="POST">'."\n";
  864. $form .= get_lang('CurrentDirectory').' <select name="curdirpath" onchange="javascript: document.selector.submit();">'."\n";
  865. //group documents cannot be uploaded in the root
  866. if ($group_dir == '') {
  867. $form .= '<option value="/">/ ('.get_lang('Root').')</option>';
  868. if (is_array($folders)) {
  869. foreach ($folders as $folder) {
  870. $selected = ($curdirpath == $folder) ? ' selected="selected"' : '';
  871. $form .= '<option'.$selected.' value="'.$folder.'">'.$folder.'</option>'."\n";
  872. }
  873. }
  874. } else {
  875. foreach ($folders as $folder) {
  876. $selected = ($curdirpath == $folder) ? ' selected="selected"' : '';
  877. $display_folder = substr($folder, strlen($group_dir));
  878. $display_folder = ($display_folder == '') ? '/ ('.get_lang('Root').')' : $display_folder;
  879. $form .= '<option'.$selected.' value="'.$folder.'">'.$display_folder.'</option>'."\n";
  880. }
  881. }
  882. $form .= '</select>'."\n";
  883. $form .= '<noscript><input type="submit" name="change_path" value="'.get_lang('Ok').'" /></noscript>'."\n";
  884. $form .= '</form>';
  885. return $form;
  886. }
  887. /**
  888. * Builds the form thats enables the user to
  889. * move a document from one directory to another
  890. * This function has been copied from the document/document.inc.php library
  891. *
  892. * @param array $folders
  893. * @param string $curdirpath
  894. * @param string $move_file
  895. * @return string html form
  896. */
  897. function build_work_move_to_selector($folders, $curdirpath, $move_file, $group_dir = '') {
  898. $course_id = api_get_course_int_id();
  899. $move_file = intval($move_file);
  900. $tbl_work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  901. $sql = "SELECT title FROM $tbl_work WHERE c_id = $course_id AND id ='".$move_file."'";
  902. $result = Database::query($sql);
  903. $title = Database::fetch_row($result);
  904. global $gradebook;
  905. //@todo use formvalidator please!
  906. $form = '<form class="form-horizontal" name="move_to_form" action="'.api_get_self().'?'.api_get_cidreq().'&gradebook='.$gradebook.'&curdirpath='.Security::remove_XSS($curdirpath).'" method="POST">';
  907. $form .= '<legend>'.get_lang('MoveFile').' - '.Security::remove_XSS($title[0]).'</legend>';
  908. $form .= '<input type="hidden" name="item_id" value="'.$move_file.'" />';
  909. $form .= '<input type="hidden" name="action" value="move_to" />';
  910. $form .= '<div class="control-group">
  911. <label>
  912. <span class="form_required">*</span>'.get_lang('Select').'
  913. </label>
  914. <div class="controls">';
  915. $form .= ' <select name="move_to_id">';
  916. //group documents cannot be uploaded in the root
  917. if ($group_dir == '') {
  918. if ($curdirpath != '/') {
  919. //$form .= '<option value="0">/ ('.get_lang('Root').')</option>';
  920. }
  921. if (is_array($folders)) {
  922. foreach ($folders as $fid => $folder) {
  923. //you cannot move a file to:
  924. //1. current directory
  925. //2. inside the folder you want to move
  926. //3. inside a subfolder of the folder you want to move
  927. if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')) {
  928. $form .= '<option value="'.$fid.'">'.$folder.'</option>';
  929. }
  930. }
  931. }
  932. } else {
  933. if ($curdirpath != '/') {
  934. $form .= '<option value="0">/ ('.get_lang('Root').')</option>';
  935. }
  936. foreach ($folders as $fid => $folder) {
  937. if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')) {
  938. //cannot copy dir into his own subdir
  939. $display_folder = substr($folder, strlen($group_dir));
  940. $display_folder = ($display_folder == '') ? '/ ('.get_lang('Root').')' : $display_folder;
  941. $form .= '<option value="'.$fid.'">'.$display_folder.'</option>'."\n";
  942. }
  943. }
  944. }
  945. $form .= '</select>';
  946. $form .= ' </div>
  947. </div>';
  948. $form .= '<div class="control-group">
  949. <div class="controls">
  950. <button type="submit" class="save" name="move_file_submit">'.get_lang('MoveFile').'</button>
  951. </div>
  952. </div>';
  953. $form .= '</form>';
  954. $form .= '<div style="clear: both; margin-bottom: 10px;"></div>';
  955. return $form;
  956. }
  957. /**
  958. * Checks if the first given directory exists as a subdir of the second given directory
  959. * This function should now be deprecated by Security::check_abs_path()
  960. * @param string Subdir
  961. * @param string Base dir
  962. * @return integer -1 on error, 0 if not subdir, 1 if subdir
  963. */
  964. // TODO: This function is a candidate for removal, it is not used anywhere.
  965. function is_subdir_of($subdir, $basedir) {
  966. if (empty($subdir) or empty($basedir)) {
  967. return -1;
  968. }
  969. if (substr($basedir, -1, 1) != '/') {
  970. $basedir = $basedir.'/';
  971. }
  972. if (substr($subdir, 0, 1) == '/') {
  973. $subdir = substr($subdir, 1);
  974. }
  975. return is_dir($basedir.$subdir) ? 1 : 0;
  976. }
  977. /**
  978. * creates a new directory trying to find a directory name
  979. * that doesn't already exist
  980. * (we could use unique_name() here...)
  981. *
  982. * @author Hugues Peeters <hugues.peeters@claroline.net>
  983. * @author Bert Vanderkimpen
  984. * @author Yannick Warnier <ywarnier@beeznest.org> Adaptation for work tool
  985. * @param string Base work dir (.../work)
  986. * @param string $desiredDirName complete path of the desired name
  987. * @return string actual directory name if it succeeds, boolean false otherwise
  988. */
  989. function create_unexisting_work_directory($base_work_dir, $desired_dir_name) {
  990. $nb = '';
  991. $base_work_dir = (substr($base_work_dir, -1, 1) == '/' ? $base_work_dir : $base_work_dir.'/');
  992. while (file_exists($base_work_dir.$desired_dir_name.$nb)) {
  993. $nb += 1;
  994. }
  995. if (@mkdir($base_work_dir.$desired_dir_name.$nb, api_get_permissions_for_new_directories())) {
  996. return $desired_dir_name.$nb;
  997. } else {
  998. return false;
  999. }
  1000. }
  1001. /**
  1002. * Delete a work-tool directory
  1003. * @param string Base "work" directory for this course as /var/www/chamilo/courses/ABCD/work/
  1004. * @param string The directory name as the bit after "work/", without trailing slash
  1005. * @return integer -1 on error
  1006. */
  1007. function del_dir($id) {
  1008. global $_course;
  1009. $id = intval($id);
  1010. $work_data = get_work_data_by_id($id);
  1011. if (empty($work_data)) {
  1012. return false;
  1013. }
  1014. $base_work_dir = api_get_path(SYS_COURSE_PATH) .$_course['path'].'/work';
  1015. $work_data_url = $base_work_dir.$work_data['url'];
  1016. $check = Security::check_abs_path($work_data_url.'/', $base_work_dir.'/');
  1017. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1018. $course_id = api_get_course_int_id();
  1019. if (!empty($work_data['url'])) {
  1020. //Deleting all contents inside the folder
  1021. //@todo replace to parent_id
  1022. $sql = "UPDATE $table SET active = 2 WHERE c_id = $course_id AND filetype = 'folder' AND id = $id";
  1023. $res = Database::query($sql);
  1024. $sql = "UPDATE $table SET active = 2 WHERE c_id = $course_id AND parent_id = $id";
  1025. $res = Database::query($sql);
  1026. if ($check) {
  1027. require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
  1028. $new_dir = $work_data_url.'_DELETED_'.$id;
  1029. if (api_get_setting('permanently_remove_deleted_files') == 'true'){
  1030. my_delete($work_data_url);
  1031. } else {
  1032. if (file_exists($work_data_url)) {
  1033. rename($work_data_url, $new_dir);
  1034. }
  1035. }
  1036. }
  1037. }
  1038. }
  1039. /**
  1040. * Get the path of a document in the student_publication table (path relative to the course directory)
  1041. * @param integer Element ID
  1042. * @return string Path (or -1 on error)
  1043. */
  1044. function get_work_path($id) {
  1045. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1046. $course_id = api_get_course_int_id();
  1047. $sql = 'SELECT url FROM '.$table.' WHERE c_id = '.$course_id.' AND id='.intval($id);
  1048. $res = Database::query($sql);
  1049. if (Database::num_rows($res)) {
  1050. $row = Database::fetch_array($res);
  1051. return $row['url'];
  1052. }
  1053. return -1;
  1054. }
  1055. /**
  1056. * Update the url of a work in the student_publication table
  1057. * @param integer ID of the work to update
  1058. * @param string Destination directory where the work has been moved (must end with a '/')
  1059. * @return -1 on error, sql query result on success
  1060. */
  1061. function update_work_url($id, $new_path, $parent_id) {
  1062. if (empty($id)) return -1;
  1063. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1064. $course_id = api_get_course_int_id();
  1065. $id = intval($id);
  1066. $parent_id = intval($parent_id);
  1067. $sql = "SELECT * FROM $table WHERE c_id = $course_id AND id = $id";
  1068. $res = Database::query($sql);
  1069. if (Database::num_rows($res) != 1) {
  1070. return -1;
  1071. } else {
  1072. $row = Database::fetch_array($res);
  1073. $filename = basename($row['url']);
  1074. $new_url = $new_path .$filename;
  1075. $sql2 = "UPDATE $table SET url = '$new_url', parent_id = '$parent_id' WHERE c_id = $course_id AND id = $id";
  1076. $res2 = Database::query($sql2);
  1077. return $res2;
  1078. }
  1079. }
  1080. /**
  1081. * Update the url of a dir in the student_publication table
  1082. * @param string old path
  1083. * @param string new path
  1084. */
  1085. function update_dir_name($work_data, $new_name, $title) {
  1086. $course_id = api_get_course_int_id();
  1087. $work_id = intval($work_data['id']);
  1088. $path = $work_data['url'];
  1089. if ($work_data['title'] == $title) {
  1090. return true;
  1091. }
  1092. $title = Database::escape_string($title);
  1093. if (!empty($new_name)) {
  1094. global $base_work_dir;
  1095. $new_name = Security::remove_XSS($new_name);
  1096. $new_name = replace_dangerous_char($new_name);
  1097. $new_name = disable_dangerous_file($new_name);
  1098. my_rename($base_work_dir.'/'.$path, $new_name);
  1099. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1100. //update all the files in the other directories according with the next query
  1101. $sql = "SELECT id, url FROM $table WHERE c_id = $course_id AND parent_id = $work_id"; // like binary (Case Sensitive)
  1102. $rs = Database::query($sql);
  1103. $work_len = strlen('work/'.$path);
  1104. while ($work = Database :: fetch_array($rs)) {
  1105. $new_dir = $work['url'];
  1106. $name_with_directory = substr($new_dir, $work_len, strlen($new_dir));
  1107. $name = Database::escape_string('work/'.$new_name.'/'.$name_with_directory);
  1108. $sql = 'UPDATE '.$table.' SET url= "'.$name.'" WHERE c_id = '.$course_id.' AND id= '.$work['id'];
  1109. Database::query($sql);
  1110. }
  1111. $sql = "UPDATE $table SET url= '/".$new_name."' , title = '".$title."' WHERE c_id = $course_id AND id = $work_id";
  1112. Database::query($sql);
  1113. }
  1114. }
  1115. /**
  1116. * Return an array with all the folder's ids that are in the given path
  1117. * @param string Path of the directory
  1118. * @return array The list of ids of all the directories in the path
  1119. * @author Julio Montoya Dokeos
  1120. * @version April 2008
  1121. */
  1122. function get_parent_directories($id) {
  1123. $course_id = api_get_course_int_id();
  1124. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1125. $id = intval($id);
  1126. $sql = "SELECT id FROM $work_table WHERE c_id = $course_id AND parent_id = $id";
  1127. $result = Database::query($sql);
  1128. $list_id = array();
  1129. if (Database::num_rows($result)) {
  1130. while ($row = Database::fetch_array($result)) {
  1131. $list_id[] = $row['id'];
  1132. }
  1133. }
  1134. return $list_id;
  1135. }
  1136. /**
  1137. * Transform an all directory structure (only directories) in an array
  1138. * @param string path of the directory
  1139. * @return array the directory structure into an array
  1140. * @author Julio Montoya Dokeos
  1141. * @version April 2008
  1142. */
  1143. function directory_to_array($directory) {
  1144. $array_items = array();
  1145. if ($handle = @opendir($directory)) {
  1146. while (false !== ($file = readdir($handle))) {
  1147. if ($file != '.' && $file != '..') {
  1148. if (is_dir($directory. '/' . $file)) {
  1149. $array_items = array_merge($array_items, directory_to_array($directory. '/' . $file));
  1150. $file = $directory . '/' . $file;
  1151. $array_items[] = preg_replace("/\/\//si", '/', $file);
  1152. }
  1153. }
  1154. }
  1155. closedir($handle);
  1156. }
  1157. return $array_items;
  1158. }
  1159. /**
  1160. * Insert into the DB of the course all the directories
  1161. * @param string path of the /work directory of the course
  1162. * @return -1 on error, sql query result on success
  1163. * @author Julio Montoya Dokeos
  1164. * @version April 2008
  1165. */
  1166. function insert_all_directory_in_course_table($base_work_dir) {
  1167. $dir_to_array = directory_to_array($base_work_dir, true);
  1168. $only_dir = array();
  1169. for ($i = 0; $i < count($dir_to_array); $i++) {
  1170. $only_dir[] = substr($dir_to_array[$i], strlen($base_work_dir), strlen($dir_to_array[$i]));
  1171. }
  1172. $course_id = api_get_course_int_id();
  1173. $group_id = api_get_group_id();
  1174. for($i = 0; $i < count($only_dir); $i++) {
  1175. global $work_table;
  1176. $sql_insert_all= "INSERT INTO " . $work_table . " SET
  1177. c_id = '$course_id',
  1178. url = '" . $only_dir[$i] . "',
  1179. title = '',
  1180. description = '',
  1181. author = '',
  1182. active = '0',
  1183. accepted = '1',
  1184. filetype = 'folder',
  1185. post_group_id = '".$group_id."',
  1186. sent_date = '0000-00-00 00:00:00' ";
  1187. Database::query($sql_insert_all);
  1188. }
  1189. }
  1190. /**
  1191. * This function displays the number of files contained in a directory
  1192. *
  1193. * @param string the path of the directory
  1194. * @param boolean true if we want the total quantity of files include in others child directorys , false only files in the directory
  1195. * @return array the first element is an integer with the number of files in the folder, the second element is the number of directories
  1196. * @author Julio Montoya Dokeos
  1197. * @version April 2008
  1198. */
  1199. function count_dir($path_dir, $recurse) {
  1200. $count = 0;
  1201. $count_dir = 0;
  1202. $d = dir($path_dir);
  1203. while ($entry = $d->Read()) {
  1204. if (!(($entry == '..') || ($entry == '.'))) {
  1205. if (is_dir($path_dir.'/'.$entry)) {
  1206. $count_dir++;
  1207. if ($recurse) {
  1208. $count += count_dir($path_dir . '/' . $entry, $recurse);
  1209. }
  1210. } else {
  1211. $count++;
  1212. }
  1213. }
  1214. }
  1215. $return_array = array();
  1216. $return_array[] = $count;
  1217. $return_array[] = $count_dir;
  1218. return $return_array;
  1219. }
  1220. /**
  1221. * returns all the javascript that is required for easily
  1222. * validation when you create a work
  1223. * this goes into the $htmlHeadXtra[] array
  1224. */
  1225. function to_javascript_work() {
  1226. $origin = isset($_REQUEST['origin']) && !empty($_REQUEST['origin']) ? api_get_tools_lists($_REQUEST['origin']) : '';
  1227. $js = '<script>
  1228. function updateDocumentTitle(value) {
  1229. var temp = value.indexOf("/");
  1230. //linux path
  1231. if(temp!=-1){
  1232. var temp=value.split("/");
  1233. } else {
  1234. var temp=value.split("\\\");
  1235. }
  1236. document.getElementById("file_upload").value=temp[temp.length-1];
  1237. $("#contains_file_id").attr("value", 1);
  1238. }
  1239. function checkDate(month, day, year) {
  1240. var monthLength =
  1241. new Array(31,28,31,30,31,30,31,31,30,31,30,31);
  1242. if (!day || !month || !year)
  1243. return false;
  1244. // check for bisestile year
  1245. if (year/4 == parseInt(year/4))
  1246. monthLength[1] = 29;
  1247. if (month < 1 || month > 12)
  1248. return false;
  1249. if (day > monthLength[month-1])
  1250. return false;
  1251. return true;
  1252. }
  1253. function mktime() {
  1254. var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;
  1255. d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);
  1256. var dateManip = {
  1257. 0: function(tt){ return d.setHours(tt); },
  1258. 1: function(tt){ return d.setMinutes(tt); },
  1259. 2: function(tt){ set = d.setSeconds(tt); mb = d.getDate() - 1; return set; },
  1260. 3: function(tt){ set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },
  1261. 4: function(tt){ return d.setDate(tt+mb); },
  1262. 5: function(tt){ return d.setYear(tt+ma); }
  1263. };
  1264. for( i = 0; i < argc; i++ ){
  1265. no = parseInt(argv[i]*1);
  1266. if (isNaN(no)) {
  1267. return false;
  1268. } else {
  1269. // arg is number, lets manipulate date object
  1270. if(!dateManip[i](no)){
  1271. // failed
  1272. return false;
  1273. }
  1274. }
  1275. }
  1276. return Math.floor(d.getTime()/1000);
  1277. }
  1278. function validate() {
  1279. var expires_day = document.form1.expires_day.value;
  1280. var expires_month = document.form1.expires_month.value;
  1281. var expires_year = document.form1.expires_year.value;
  1282. var expires_hour = document.form1.expires_hour.value;
  1283. var expires_minute = document.form1.expires_minute.value;
  1284. var expires_date = mktime(expires_hour,expires_minute,0,expires_month,expires_day,expires_year)
  1285. var ends_day = document.form1.ends_day.value;
  1286. var ends_month = document.form1.ends_month.value;
  1287. var ends_year = document.form1.ends_year.value;
  1288. var ends_hour = document.form1.ends_hour.value;
  1289. var ends_minute = document.form1.ends_minute.value;
  1290. var ends_date = mktime(ends_hour,ends_minute,0,ends_month,ends_day,ends_year);
  1291. var new_dir = document.form1.new_dir.value;
  1292. msg_id1 = document.getElementById("msg_error1");
  1293. msg_id2 = document.getElementById("msg_error2");
  1294. msg_id3 = document.getElementById("msg_error3");
  1295. msg_id4 = document.getElementById("msg_error4");
  1296. msg_id5 = document.getElementById("msg_error_weight");
  1297. if(new_dir=="") {
  1298. msg_id1.style.display ="block";
  1299. msg_id1.innerHTML="'.get_lang('FieldRequired', '').'";
  1300. msg_id2.innerHTML="";msg_id3.innerHTML="";msg_id4.innerHTML="";msg_id5.innerHTML="";
  1301. } else if(document.form1.type1.checked && document.form1.type2.checked && expires_date > ends_date) {
  1302. msg_id2.style.display ="block";
  1303. msg_id2.innerHTML="'.get_lang('EndDateCannotBeBeforeTheExpireDate', '').'";
  1304. msg_id1.innerHTML="";msg_id3.innerHTML="";msg_id4.innerHTML="";msg_id5.innerHTML="";
  1305. } else if (!checkDate(expires_month,expires_day,expires_year)) {
  1306. msg_id3.style.display ="block";
  1307. msg_id3.innerHTML="'.get_lang('InvalidDate', '').'";
  1308. msg_id1.innerHTML="";msg_id2.innerHTML="";msg_id4.innerHTML="";msg_id5.innerHTML="";
  1309. } else if (!checkDate(ends_month,ends_day,ends_year)) {
  1310. msg_id4.style.display ="block";
  1311. msg_id4.innerHTML="'.get_lang('InvalidDate', '').'";
  1312. msg_id1.innerHTML="";msg_id2.innerHTML="";msg_id3.innerHTML="";msg_id5.innerHTML="";
  1313. } else {
  1314. if (document.form1.make_calification.checked) {
  1315. var weight = document.form1.weight.value;
  1316. if(weight=="") {
  1317. msg_id5.style.display ="block";
  1318. msg_id5.innerHTML="'.get_lang('WeightNecessary', '').'";
  1319. msg_id1.innerHTML="";msg_id2.innerHTML="";msg_id3.innerHTML="";msg_id4.innerHTML="";
  1320. return false;
  1321. }
  1322. }
  1323. document.form1.action = "work.php?'. api_get_cidreq().'&origin='.$origin.'&gradebook='.(empty($_GET['gradebook'])?'':'view').'";
  1324. document.form1.submit();
  1325. }
  1326. }
  1327. </script>';
  1328. return $js;
  1329. }
  1330. /**
  1331. * Gets the id of a student publication with a given path
  1332. * @param string $path
  1333. * @return true if is found / false if not found
  1334. */
  1335. // TODO: The name of this function does not fit with the kind of information it returns. Maybe check_work_id() or is_work_id()?
  1336. function get_work_id($path) {
  1337. $TBL_STUDENT_PUBLICATION = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  1338. $TBL_PROP_TABLE = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1339. $course_id = api_get_course_int_id();
  1340. if (api_is_allowed_to_edit()) {
  1341. $sql = "SELECT work.id FROM $TBL_STUDENT_PUBLICATION AS work, $TBL_PROP_TABLE AS props
  1342. WHERE props.c_id = $course_id AND work.c_id = $course_id AND props.tool='work' AND work.id=props.ref AND work.url LIKE 'work/".$path."%' AND work.filetype='file' AND props.visibility<>'2'";
  1343. } else {
  1344. $sql = "SELECT work.id FROM $TBL_STUDENT_PUBLICATION AS work,$TBL_PROP_TABLE AS props
  1345. WHERE props.c_id = $course_id AND work.c_id = $course_id AND props.tool='work' AND work.id=props.ref AND work.url LIKE 'work/".$path."%' AND work.filetype='file' AND props.visibility<>'2' AND props.lastedit_user_id='".api_get_user_id()."'";
  1346. }
  1347. $result = Database::query($sql);
  1348. $num_rows = Database::num_rows($result);
  1349. if ($result && $num_rows > 0) {
  1350. return true;
  1351. } else {
  1352. return false;
  1353. }
  1354. }
  1355. /**
  1356. * @param int $work_id
  1357. * @param int $onlyMeUserId show only my works
  1358. * @param int $notMeUserId show works from everyone except me
  1359. * @return int
  1360. */
  1361. function get_count_work($work_id, $onlyMeUserId = null, $notMeUserId = null)
  1362. {
  1363. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1364. $iprop_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1365. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1366. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  1367. $session_id = api_get_session_id();
  1368. $condition_session = api_get_session_condition($session_id);
  1369. $course_id = api_get_course_int_id();
  1370. $group_id = api_get_group_id();
  1371. $course_info = api_get_course_info(api_get_course_id());
  1372. $work_id = intval($work_id);
  1373. if (!empty($group_id)) {
  1374. $extra_conditions = " work.post_group_id = '".intval($group_id)."' "; // set to select only messages posted by the user's group
  1375. } else {
  1376. $extra_conditions = " work.post_group_id = '0' ";
  1377. }
  1378. if ($is_allowed_to_edit) {
  1379. $extra_conditions .= ' AND work.active IN (0, 1) ';
  1380. } else {
  1381. $extra_conditions .= ' AND work.active = 1 AND accepted = 1';
  1382. if (isset($course_info['show_score']) && $course_info['show_score'] == 1) {
  1383. $extra_conditions .= " AND work.user_id = ".api_get_user_id()." ";
  1384. } else {
  1385. $extra_conditions .= '';
  1386. }
  1387. }
  1388. $extra_conditions .= " AND parent_id = ".$work_id." ";
  1389. $where_condition = null;
  1390. if (!empty($notMeUserId)) {
  1391. $where_condition .= " AND u.user_id <> ".intval($notMeUserId);
  1392. }
  1393. if (!empty($onlyMeUserId)) {
  1394. $where_condition .= " AND u.user_id = ".intval($onlyMeUserId);
  1395. }
  1396. $sql = "SELECT count(*) as count ".
  1397. " FROM ".$iprop_table." prop INNER JOIN ".$work_table." work ".
  1398. " ON (prop.ref=work.id AND prop.c_id = $course_id ".
  1399. " AND prop.tool='work' AND work.active = 1 ".
  1400. " AND prop.visibility <> 2 AND work.c_id = $course_id ) ".
  1401. " INNER JOIN $user_table u ON (work.user_id = u.user_id) ".
  1402. " WHERE $extra_conditions $where_condition $condition_session ";
  1403. $result = Database::query($sql);
  1404. $users_with_work = 0;
  1405. if (Database::num_rows($result)) {
  1406. $result = Database::fetch_array($result);
  1407. $users_with_work = $result['count'];
  1408. }
  1409. return $users_with_work;
  1410. }
  1411. /**
  1412. * @param int $start
  1413. * @param int $limit
  1414. * @param int $column
  1415. * @param string $direction
  1416. * @param int $work_id
  1417. * @param array $where_condition
  1418. * @param int $studentId
  1419. * @return array
  1420. */
  1421. function get_work_user_list($start, $limit, $column, $direction, $work_id, $where_condition, $studentId = null)
  1422. {
  1423. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1424. $iprop_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1425. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1426. $session_id = api_get_session_id();
  1427. $course_id = api_get_course_int_id();
  1428. $group_id = api_get_group_id();
  1429. $course_info = api_get_course_info(api_get_course_id());
  1430. $work_id = intval($work_id);
  1431. $column = empty($column) ? : Database::escape_string($column);
  1432. $start = intval($start);
  1433. $limit = intval($limit);
  1434. if (!in_array($direction, array('asc','desc'))) {
  1435. $direction = 'desc';
  1436. }
  1437. $work_data = get_work_data_by_id($work_id);
  1438. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  1439. $condition_session = api_get_session_condition($session_id);
  1440. $locked = api_resource_is_locked_by_gradebook($work_id, LINK_STUDENTPUBLICATION);
  1441. if (!empty($work_data)) {
  1442. if (!empty($group_id)) {
  1443. $extra_conditions = " work.post_group_id = '".intval($group_id)."' "; // set to select only messages posted by the user's group
  1444. } else {
  1445. $extra_conditions = " work.post_group_id = '0' ";
  1446. }
  1447. if ($is_allowed_to_edit) {
  1448. $extra_conditions .= ' AND work.active IN (0, 1) ';
  1449. } else {
  1450. if (isset($course_info['show_score']) && $course_info['show_score'] == 1) {
  1451. $extra_conditions .= " AND (u.user_id = ".api_get_user_id()." AND work.active IN (0, 1) OR work.active = 1) ";
  1452. } else {
  1453. $extra_conditions .= ' AND work.active = 1 ';
  1454. }
  1455. }
  1456. $extra_conditions .= " AND parent_id = ".$work_id." ";
  1457. $select = 'DISTINCT u.user_id, work.id as id, title as title, description, url, sent_date, contains_file, has_properties, view_properties,
  1458. qualification, weight, allow_text_assignment, u.firstname, u.lastname, u.username, parent_id, accepted, qualificator_id';
  1459. $user_condition = "INNER JOIN $user_table u ON (work.user_id = u.user_id) ";
  1460. $work_condition = "$iprop_table prop INNER JOIN $work_table work ON (prop.ref = work.id AND prop.c_id = $course_id AND work.c_id = $course_id ) ";
  1461. $work_assignment = get_work_assignment_by_id($work_id);
  1462. if (!empty($studentId)) {
  1463. $where_condition.= " AND u.user_id = ".intval($studentId);
  1464. }
  1465. $sql = "SELECT $select
  1466. FROM $work_condition $user_condition
  1467. WHERE $extra_conditions $where_condition $condition_session ";
  1468. $sql .= " ORDER BY $column $direction ";
  1469. $sql .= " LIMIT $start, $limit";
  1470. $result = Database::query($sql);
  1471. $works = array();
  1472. while ($work = Database::fetch_array($result, 'ASSOC')) {
  1473. $item_id = $work['id'];
  1474. // Get the author ID for that document from the item_property table
  1475. $is_author = false;
  1476. $can_read = false;
  1477. $owner_id = $work['user_id'];
  1478. /* Because a bug found when saving items using the api_item_property_update()
  1479. the field $item_property_data['insert_user_id'] is not reliable. */
  1480. // $item_property_data = api_get_item_property_info(api_get_course_int_id(), 'work', $item_id, api_get_session_id());
  1481. //if (!$is_allowed_to_edit && $item_property_data['insert_user_id'] == api_get_user_id()) {
  1482. if (!$is_allowed_to_edit && $owner_id == api_get_user_id()) {
  1483. $is_author = true;
  1484. }
  1485. if ($course_info['show_score'] == 0) {
  1486. $can_read = true;
  1487. }
  1488. if ($work['accepted'] == '0') {
  1489. $class = 'invisible';
  1490. } else {
  1491. $class = '';
  1492. }
  1493. $qualification_exists = false;
  1494. if (!empty($work_data['qualification']) && intval($work_data['qualification']) > 0) {
  1495. $qualification_exists = true;
  1496. }
  1497. $qualification_string = '';
  1498. if ($qualification_exists) {
  1499. if ($work['qualification'] == '') {
  1500. $qualification_string = Display::label('-');
  1501. } else {
  1502. $qualification_string = Display::label($work['qualification'], 'info');
  1503. }
  1504. }
  1505. $add_string = '';
  1506. $time_expires = api_strtotime($work_assignment['expires_on'], 'UTC');
  1507. if (!empty($work_assignment['expires_on']) && $work_assignment['expires_on'] != '0000-00-00 00:00:00' && $time_expires && ($time_expires < api_strtotime($work['sent_date'], 'UTC'))) {
  1508. $add_string = Display::label(get_lang('Expired'), 'important');
  1509. }
  1510. if (
  1511. ($can_read && $work['accepted'] == '1') ||
  1512. ($is_author && in_array($work['accepted'], array('1','0'))) ||
  1513. $is_allowed_to_edit
  1514. ) {
  1515. // Firstname, lastname, username
  1516. $work['firstname'] = Display::div($work['firstname'], array('class' => $class));
  1517. $work['lastname'] = Display::div($work['lastname'], array('class' => $class));
  1518. if (strlen($work['title']) > 30) {
  1519. $short_title = substr($work['title'], 0, 27).'...';
  1520. $work['title'] = Display::span($short_title, array('class' => $class, 'title' => $work['title']));
  1521. } else {
  1522. $work['title'] = Display::div($work['title'], array('class' => $class));
  1523. }
  1524. // Type.
  1525. $work['type'] = build_document_icon_tag('file', $work['file']);
  1526. // File name.
  1527. $link_to_download = null;
  1528. if ($work['contains_file']) {
  1529. $link_to_download = '<a href="download.php?id='.$item_id.'">'.Display::return_icon('save.png', get_lang('Save'),array(), ICON_SIZE_SMALL).'</a> ';
  1530. } else {
  1531. //$link_to_download = '<a href="view.php?id='.$item_id.'">'.Display::return_icon('save_na.png', get_lang('Save'),array(), ICON_SIZE_SMALL).'</a> ';
  1532. }
  1533. $send_to = Portfolio::share('work', $work['id'], array('style' => 'white-space:nowrap;'));
  1534. $work['qualification'] = $qualification_string;
  1535. // Date.
  1536. $work_date = api_convert_and_format_date($work['sent_date']);
  1537. $work['sent_date'] = date_to_str_ago(api_get_local_time($work['sent_date'])).' '.$add_string.'<br />'.$work_date;
  1538. // Actions.
  1539. $url = api_get_path(WEB_CODE_PATH).'work/';
  1540. $action = '';
  1541. if ($is_allowed_to_edit) {
  1542. $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
  1543. Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a> ';
  1544. if ($locked) {
  1545. if ($qualification_exists) {
  1546. $action .= Display::return_icon('rate_work_na.png', get_lang('CorrectAndRate'),array(), ICON_SIZE_SMALL);
  1547. } else {
  1548. $action .= Display::return_icon('edit_na.png', get_lang('Comment'),array(), ICON_SIZE_SMALL);
  1549. }
  1550. } else {
  1551. if ($qualification_exists) {
  1552. $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Modify').'" >'.
  1553. Display::return_icon('rate_work.png', get_lang('CorrectAndRate'),array(), ICON_SIZE_SMALL).'</a>';
  1554. } else {
  1555. $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'&gradebook='.Security::remove_XSS($_GET['gradebook']).'" title="'.get_lang('Modify').'">'.
  1556. Display::return_icon('edit.png', get_lang('Comment'),array(), ICON_SIZE_SMALL).'</a>';
  1557. }
  1558. }
  1559. if ($work['contains_file']) {
  1560. if ($locked) {
  1561. $action .= Display::return_icon('move_na.png', get_lang('Move'),array(), ICON_SIZE_SMALL);
  1562. } else {
  1563. $action .= '<a href="'.$url.'work.php?'.api_get_cidreq().'&action=move&item_id='.$item_id.'" title="'.get_lang('Move').'">'.Display::return_icon('move.png', get_lang('Move'),array(), ICON_SIZE_SMALL).'</a>';
  1564. }
  1565. }
  1566. if ($work['accepted'] == '1') {
  1567. $action .= '<a href="'.$url.'work.php?'.api_get_cidreq().'&action=make_invisible&item_id='.$item_id.'&amp;'.$sort_params.'" title="'.get_lang('Invisible').'" >'.Display::return_icon('visible.png', get_lang('Invisible'),array(), ICON_SIZE_SMALL).'</a>';
  1568. } else {
  1569. $action .= '<a href="'.$url.'work.php?'.api_get_cidreq().'&action=make_visible&item_id='.$item_id.'&amp;'.$sort_params.'" title="'.get_lang('Visible').'" >'.Display::return_icon('invisible.png', get_lang('Visible'),array(), ICON_SIZE_SMALL).'</a> ';
  1570. }
  1571. if ($locked) {
  1572. $action .= Display::return_icon('delete_na.png', get_lang('Delete'),'',ICON_SIZE_SMALL);
  1573. } else {
  1574. $action .= '<a href="'.$url.'work.php?'.api_get_cidreq().'&action=delete&amp;item_id='.$item_id.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'" >'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
  1575. }
  1576. } elseif ($is_author && (empty($work['qualificator_id']) || $work['qualificator_id'] == 0)) {
  1577. $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a>';
  1578. if (api_get_course_setting('student_delete_own_publication') == 1) {
  1579. if (api_is_allowed_to_session_edit(false, true)) {
  1580. $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'&gradebook='.Security::remove_XSS($_GET['gradebook']).'" title="'.get_lang('Modify').'">'.
  1581. Display::return_icon('edit.png', get_lang('Comment'),array(), ICON_SIZE_SMALL).'</a>';
  1582. }
  1583. $action .= ' <a href="'.$url.'work.php?'.api_get_cidreq().'&action=delete&amp;item_id='.$item_id.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'" >'.Display::return_icon('delete.png',get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
  1584. } else {
  1585. $action .= Display::return_icon('edit_na.png', get_lang('Modify'),array(), ICON_SIZE_SMALL);
  1586. }
  1587. } else {
  1588. $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a>';
  1589. $action .= Display::return_icon('edit_na.png', get_lang('Modify'),array(), ICON_SIZE_SMALL);
  1590. }
  1591. // Status.
  1592. if (empty($work['qualificator_id'])) {
  1593. $qualificator_id = Display::label(get_lang('NotRevised'), 'warning');
  1594. } else {
  1595. $qualificator_id = Display::label(get_lang('Revised'), 'success');
  1596. }
  1597. $work['qualificator_id'] = $qualificator_id;
  1598. $work['actions'] = $send_to.$link_to_download.$action;
  1599. $works[] = $work;
  1600. }
  1601. }
  1602. return $works;
  1603. }
  1604. }
  1605. /**
  1606. * Send reminder to users who have not given the task
  1607. *
  1608. * @param int
  1609. * @return array
  1610. * @author cvargas carlos.vargas@beeznest.com cfasanando, christian.fasanado@beeznest.com
  1611. */
  1612. function send_reminder_users_without_publication($task_data)
  1613. {
  1614. global $_course;
  1615. $sender_name = api_get_person_name(api_get_setting('platform.administrator_name'), api_get_setting('platform.administrator_surname'), null, PERSON_NAME_EMAIL_ADDRESS);
  1616. $task_id = $task_data['id'];
  1617. $task_title = !empty($task_data['title']) ? $task_data['title'] : basename($task_data['url']);
  1618. $subject = '[' . api_get_setting('platform.site_name') . '] ';
  1619. // The body can be as long as you wish, and any combination of text and variables
  1620. $content = get_lang('ReminderToSubmitPendingTask')."\n".get_lang('CourseName').' : '.$_course['name']."\n";
  1621. $content .= get_lang('WorkName').' : '.$task_title."\n";
  1622. $list_users = get_list_users_without_publication($task_id);
  1623. $mails_sent_to = array();
  1624. foreach ($list_users as $user) {
  1625. $name_user = api_get_person_name($user[1], $user[0], null, PERSON_NAME_EMAIL_ADDRESS);
  1626. $dear_line = get_lang('Dear')." ".api_get_person_name($user[1], $user[0]) .", \n\n";
  1627. $body = $dear_line.$content;
  1628. MessageManager::send_message($user[3], $subject, $body);
  1629. $mails_sent_to[] = $name_user;
  1630. }
  1631. return $mails_sent_to;
  1632. }
  1633. /**
  1634. * Sends an email to the students of a course when a homework is created
  1635. *
  1636. * @param string course_id
  1637. *
  1638. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  1639. * @author Julio Montoya <gugli100@gmail.com> Adding session support - 2011
  1640. */
  1641. function send_email_on_homework_creation($course_id) {
  1642. // Get the students of the course
  1643. $session_id = api_get_session_id();
  1644. if (empty($session_id)) {
  1645. $students = CourseManager::get_student_list_from_course_code($course_id);
  1646. } else {
  1647. $students = CourseManager::get_student_list_from_course_code($course_id, true, $session_id);
  1648. }
  1649. $emailsubject = '[' . api_get_setting('platform.site_name') . '] '.get_lang('HomeworkCreated');
  1650. $currentUser = api_get_user_info(api_get_user_id());
  1651. if (!empty($students)) {
  1652. foreach($students as $student) {
  1653. $user_info = api_get_user_info($student["user_id"]);
  1654. if(!empty($user_info["mail"])) {
  1655. $name_user = api_get_person_name($user_info["firstname"], $user_info["lastname"], null, PERSON_NAME_EMAIL_ADDRESS);
  1656. $emailbody = get_lang('Dear')." ".$name_user.",\n\n";
  1657. $emailbody .= get_lang('HomeworkHasBeenCreatedForTheCourse')." ".$course_id.". "."\n\n".get_lang('PleaseCheckHomeworkPage');
  1658. $emailbody .= "\n\n".api_get_person_name($currentUser["firstname"], $currentUser["lastname"]);
  1659. @api_mail($name_user, $user_info["mail"], $emailsubject, $emailbody, api_get_person_name($currentUser["firstname"], $currentUser["lastname"], null, PERSON_NAME_EMAIL_ADDRESS), $currentUser["mail"]);
  1660. }
  1661. }
  1662. }
  1663. }
  1664. /**
  1665. * @param string $url
  1666. * @return bool
  1667. */
  1668. function is_work_exist_by_url($url) {
  1669. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1670. $url = Database::escape_string($url);
  1671. $sql = "SELECT id FROM $work_table WHERE url='$url'";
  1672. $result = Database::query($sql);
  1673. if (Database::num_rows($result)> 0) {
  1674. $row = Database::fetch_row($result);
  1675. if (empty($row)) {
  1676. return false;
  1677. } else {
  1678. return true;
  1679. }
  1680. } else {
  1681. return false;
  1682. }
  1683. }
  1684. function make_select($name, $values, $checked = '') {
  1685. $output = '<select name="'.$name.'" id="'.$name.'">';
  1686. foreach($values as $key => $value) {
  1687. $output .= '<option value="'.$key.'" '.(($checked==$key) ? 'selected="selected"' : '').'>'.$value.'</option>';
  1688. }
  1689. $output .= '</select>';
  1690. return $output;
  1691. }
  1692. function make_checkbox($name, $checked = '', $label = null) {
  1693. $check = '<input id ="'.$name.'" type="checkbox" value="1" name="'.$name.'" '.((!empty($checked))?'checked="checked"':'').'/>';
  1694. if (!empty($label)) {
  1695. $check .="<label for ='$name'>$label</label>";
  1696. }
  1697. return $check;
  1698. }
  1699. function draw_date_picker($prefix, $default = '') {
  1700. if (empty($default)) {
  1701. $default = api_get_local_time();
  1702. }
  1703. $parts = explode(' ', $default);
  1704. list($d_year, $d_month, $d_day) = explode('-', $parts[0]);
  1705. list($d_hour, $d_minute) = explode(':', $parts[1]);
  1706. $minute = range(10, 59);
  1707. array_unshift($minute, '00', '01', '02', '03', '04', '05', '06', '07', '08', '09');
  1708. $date_form = make_select($prefix.'_day', array_combine(range(1, 31), range(1, 31)), $d_day);
  1709. $date_form .= make_select($prefix.'_month', array_combine(range(1, 12), api_get_months_long()), $d_month);
  1710. $date_form .= make_select($prefix.'_year', array($d_year => $d_year, $d_year + 1 => $d_year + 1), $d_year).'&nbsp;&nbsp;&nbsp;&nbsp;';
  1711. $date_form .= make_select($prefix.'_hour', array_combine(range(0, 23), range(0, 23)), $d_hour).' : ';
  1712. $date_form .= make_select($prefix.'_minute', $minute, $d_minute);
  1713. return $date_form;
  1714. }
  1715. function get_date_from_select($prefix)
  1716. {
  1717. return $_POST[$prefix.'_year'].'-'.two_digits($_POST[$prefix.'_month']).'-'.two_digits($_POST[$prefix.'_day']).' '.two_digits($_POST[$prefix.'_hour']).':'.two_digits($_POST[$prefix.'_minute']).':00';
  1718. }
  1719. /**
  1720. * Check if a user is the author of the item
  1721. * @param int $item_id
  1722. * @param int $user_id
  1723. * @return bool
  1724. */
  1725. function user_is_author($item_id, $user_id = null)
  1726. {
  1727. if (empty($item_id)) {
  1728. return false;
  1729. }
  1730. if (empty($user_id)) {
  1731. $user_id = api_get_user_id();
  1732. }
  1733. $is_author = false;
  1734. $item_to_edit_data = api_get_item_property_info(api_get_course_int_id(), 'work', $item_id, api_get_session_id());
  1735. $is_allowed_to_edit = api_is_allowed_to_edit();
  1736. if ($is_allowed_to_edit) {
  1737. $is_author = true;
  1738. } else {
  1739. if ($item_to_edit_data['insert_user_id'] == $user_id) {
  1740. $is_author = true;
  1741. }
  1742. }
  1743. if (!$is_author) {
  1744. //api_not_allowed();
  1745. return false;
  1746. }
  1747. return $is_author;
  1748. }
  1749. /**
  1750. * Get list of users who have not given the task
  1751. * @param int
  1752. * @return array
  1753. * @author cvargas
  1754. * @author Julio Montoya <gugli100@gmail.com> Fixing query
  1755. */
  1756. function get_list_users_without_publication($task_id, $studentId = null)
  1757. {
  1758. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1759. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1760. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1761. $session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1762. //condition for the session
  1763. $session_id = api_get_session_id();
  1764. $course_id = api_get_course_int_id();
  1765. $task_id = intval($task_id);
  1766. if ($session_id == 0) {
  1767. $sql = "SELECT user_id as id FROM $work_table WHERE c_id = $course_id AND parent_id='$task_id' AND active = 1";
  1768. } else {
  1769. $sql = "SELECT user_id as id FROM $work_table WHERE c_id = $course_id AND parent_id='$task_id' and session_id='".$session_id."' AND active = 1";
  1770. }
  1771. $result = Database::query($sql);
  1772. $users_with_tasks = array();
  1773. while($row = Database::fetch_array($result)) {
  1774. $users_with_tasks[] = $row['id'];
  1775. }
  1776. if ($session_id == 0) {
  1777. $sql_users = "SELECT cu.user_id, u.lastname, u.firstname, u.email FROM $table_course_user AS cu, $table_user AS u
  1778. WHERE u.status != 1 and cu.course_code='".api_get_course_id()."' AND u.user_id = cu.user_id";
  1779. } else {
  1780. $sql_users = "SELECT cu.id_user, u.lastname, u.firstname, u.email FROM $session_course_rel_user AS cu, $table_user AS u
  1781. WHERE u.status != 1 and cu.course_code='".api_get_course_id()."' AND u.user_id = cu.id_user and cu.id_session = '".$session_id."'";
  1782. }
  1783. if (!empty($studentId)) {
  1784. $sql_users.= " AND u.user_id = ".intval($studentId);
  1785. }
  1786. $group_id = api_get_group_id();
  1787. $new_group_user_list = array();
  1788. if ($group_id) {
  1789. $group_user_list = GroupManager::get_subscribed_users($group_id);
  1790. if (!empty($group_user_list)) {
  1791. foreach($group_user_list as $group_user) {
  1792. $new_group_user_list[] = $group_user['user_id'];
  1793. }
  1794. }
  1795. }
  1796. $result_users = Database::query($sql_users);
  1797. $users_without_tasks = array();
  1798. while ($row_users = Database::fetch_row($result_users)) {
  1799. if (in_array($row_users[0], $users_with_tasks)) {
  1800. continue;
  1801. }
  1802. if ($group_id && !in_array($row_users[0], $new_group_user_list)) {
  1803. continue;
  1804. }
  1805. $userId = $row_users[0];
  1806. $row_users[0] = $row_users[1];
  1807. $row_users[1] = $row_users[2];
  1808. $row_users[2] = Display::encrypted_mailto_link($row_users[3]);
  1809. $row_users[3] = $userId;
  1810. $users_without_tasks[] = $row_users;
  1811. }
  1812. return $users_without_tasks;
  1813. }
  1814. /**
  1815. * Display list of users who have not given the task
  1816. *
  1817. * @param int task id
  1818. * @return array
  1819. * @author cvargas carlos.vargas@beeznest.com cfasanando, christian.fasanado@beeznest.com
  1820. * @author Julio Montoya <gugli100@gmail.com> Fixes
  1821. */
  1822. function display_list_users_without_publication($task_id, $studentId = null)
  1823. {
  1824. global $origin;
  1825. $table_header[] = array(get_lang('LastName'), true);
  1826. $table_header[] = array(get_lang('FirstName'), true);
  1827. $table_header[] = array(get_lang('Email'), true);
  1828. $data = get_list_users_without_publication($task_id);
  1829. $sorting_options = array();
  1830. $sorting_options['column'] = 1;
  1831. $paging_options = array();
  1832. $my_params = array();
  1833. if (isset($_GET['curdirpath'])) {
  1834. $my_params['curdirpath'] = Security::remove_XSS($_GET['curdirpath']);
  1835. }
  1836. if (isset($_GET['edit_dir'])) {
  1837. $my_params['edit_dir'] = Security::remove_XSS($_GET['edit_dir']);
  1838. }
  1839. if (isset($_GET['list'])) {
  1840. $my_params['list'] = Security::remove_XSS($_GET['list']);
  1841. }
  1842. $my_params['origin'] = $origin;
  1843. $my_params['id'] = intval($_GET['id']);
  1844. //$column_show
  1845. $column_show[] = 1;
  1846. $column_show[] = 1;
  1847. $column_show[] = 1;
  1848. Display::display_sortable_config_table('work', $table_header, $data, $sorting_options, $paging_options, $my_params, $column_show);
  1849. }
  1850. // Document to work
  1851. /**
  1852. * @param int $documentId
  1853. * @param int $workId
  1854. * @param int $courseId
  1855. */
  1856. function addDocumentToWork($documentId, $workId, $courseId)
  1857. {
  1858. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  1859. $params = array(
  1860. 'document_id' => $documentId,
  1861. 'work_id' => $workId,
  1862. 'c_id' => $courseId
  1863. );
  1864. Database::insert($table, $params);
  1865. }
  1866. /**
  1867. * @param int $documentId
  1868. * @param int $workId
  1869. * @param int $courseId
  1870. * @return array
  1871. */
  1872. function getDocumentToWork($documentId, $workId, $courseId)
  1873. {
  1874. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  1875. $params = array(
  1876. 'document_id = ? and work_id = ? and c_id = ?' => array($documentId, $workId, $courseId)
  1877. );
  1878. return Database::select('*', $table, array('where' => $params));
  1879. }
  1880. /**
  1881. * @param int $workId
  1882. * @param int $courseId
  1883. * @return array
  1884. */
  1885. function getAllDocumentToWork($workId, $courseId)
  1886. {
  1887. if (ADD_DOCUMENT_TO_WORK == false) {
  1888. return array();
  1889. }
  1890. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  1891. $params = array(
  1892. 'work_id = ? and c_id = ?' => array($workId, $courseId)
  1893. );
  1894. return Database::select('*', $table, array('where' => $params));
  1895. }
  1896. /**
  1897. * @param int $documentId
  1898. * @param int $workId
  1899. * @param int $courseId
  1900. */
  1901. function deleteDocumentToWork($documentId, $workId, $courseId)
  1902. {
  1903. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  1904. $params = array(
  1905. 'document_id = ? and work_id = ? and c_id = ?' => array($documentId, $workId, $courseId)
  1906. );
  1907. Database::delete($table, $params);
  1908. }
  1909. /**
  1910. * @param int $userId
  1911. * @param int $workId
  1912. * @param int $courseId
  1913. */
  1914. function addUserToWork($userId, $workId, $courseId)
  1915. {
  1916. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  1917. $params = array(
  1918. 'user_id' => $userId,
  1919. 'work_id' => $workId,
  1920. 'c_id' => $courseId
  1921. );
  1922. Database::insert($table, $params);
  1923. }
  1924. /**
  1925. * @param int $userId
  1926. * @param int $workId
  1927. * @param int $courseId
  1928. * @return array
  1929. */
  1930. function getUserToWork($userId, $workId, $courseId)
  1931. {
  1932. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  1933. $params = array(
  1934. 'user_id = ? and work_id = ? and c_id = ?' => array($userId, $workId, $courseId)
  1935. );
  1936. return Database::select('*', $table, array('where' => $params));
  1937. }
  1938. /**
  1939. * @param int $workId
  1940. * @param int $courseId
  1941. * @return array
  1942. */
  1943. function getAllUserToWork($workId, $courseId)
  1944. {
  1945. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  1946. $params = array(
  1947. 'work_id = ? and c_id = ?' => array($workId, $courseId)
  1948. );
  1949. return Database::select('*', $table, array('where' => $params));
  1950. }
  1951. function userAddedToWork($userId, $workId, $courseId)
  1952. {
  1953. /*$table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  1954. $params = array(
  1955. 'user_id = ? and work_id = ? and c_id = ?' => array($userId, $workId, $courseId)
  1956. );
  1957. $result = Database::select('count(*)', $table, array('where' => $params));*/
  1958. }
  1959. /**
  1960. * @param int $userId
  1961. * @param int $workId
  1962. * @param int $courseId
  1963. */
  1964. function deleteUserToWork($userId, $workId, $courseId)
  1965. {
  1966. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  1967. $params = array(
  1968. 'user_id = ? and work_id = ? and c_id = ?' => array($userId, $workId, $courseId)
  1969. );
  1970. Database::delete($table, $params);
  1971. }
  1972. /**
  1973. * @param int $userId
  1974. * @param int $workId
  1975. * @param int $courseId
  1976. * @return bool
  1977. */
  1978. function userIsSubscribedToWork($userId, $workId, $courseId)
  1979. {
  1980. if (ADD_DOCUMENT_TO_WORK == false) {
  1981. return true;
  1982. }
  1983. $subscribedUsers = getAllUserToWork($workId, $courseId);
  1984. if (empty($subscribedUsers)) {
  1985. return true;
  1986. } else {
  1987. $subscribedUsersIdList = array();
  1988. foreach ($subscribedUsers as $item) {
  1989. $subscribedUsersIdList[] = $item['user_id'];
  1990. }
  1991. if (in_array($userId, $subscribedUsersIdList)) {
  1992. return true;
  1993. }
  1994. }
  1995. return false;
  1996. }
  1997. /**
  1998. * @param int $userId
  1999. * @param int $workId
  2000. * @param int $courseId
  2001. * @return bool
  2002. */
  2003. function allowOnlySubscribedUser($userId, $workId, $courseId)
  2004. {
  2005. if (ADD_DOCUMENT_TO_WORK == false) {
  2006. return true;
  2007. }
  2008. if (api_is_platform_admin() || api_is_allowed_to_edit()) {
  2009. return true;
  2010. }
  2011. if (userIsSubscribedToWork($userId, $workId, $courseId) == false) {
  2012. api_not_allowed(true);
  2013. }
  2014. }
  2015. /**
  2016. * @param int $workId
  2017. * @param array $courseInfo
  2018. * @return array
  2019. */
  2020. function getDocumentTemplateFromWork($workId, $courseInfo)
  2021. {
  2022. $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
  2023. if (!empty($documents)) {
  2024. foreach ($documents as $doc) {
  2025. $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
  2026. $fileInfo = pathinfo($docData['path']);
  2027. if ($fileInfo['extension'] == 'html') {
  2028. if (file_exists($docData['absolute_path']) && is_file($docData['absolute_path'])) {
  2029. $docData['file_content'] = file_get_contents($docData['absolute_path']);
  2030. return $docData;
  2031. }
  2032. }
  2033. }
  2034. }
  2035. return array();
  2036. }
  2037. /**
  2038. * @param $workId
  2039. * @param $courseInfo
  2040. */
  2041. function getAllDocumentsFromWorkToString($workId, $courseInfo)
  2042. {
  2043. $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
  2044. if (!empty($documents)) {
  2045. $docContent = '<ul class="nav nav-list well">';
  2046. $docContent .= '<li class="nav-header">'.get_lang('Documents').'</li>';
  2047. foreach ($documents as $doc) {
  2048. $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
  2049. if ($docData) {
  2050. $docContent .= '<li><a target="_blank" href="'.$docData['url'].'">'.$docData['title'].'</a></li>';
  2051. }
  2052. }
  2053. $docContent .= '</ul><br />';
  2054. echo $docContent;
  2055. }
  2056. }
  2057. /**
  2058. * Returns fckeditor toolbar
  2059. * @return array
  2060. */
  2061. function getWorkDescriptionToolbar()
  2062. {
  2063. return array('ToolbarSet' => 'Work', 'Width' => '100%', 'Height' => '400');
  2064. }