PageRenderTime 31ms CodeModel.GetById 37ms RepoModel.GetById 0ms app.codeStats 0ms

/course/uploadmultgrades.php

https://github.com/xiongchiamiov/IMathAS
PHP | 297 lines | 261 code | 12 blank | 24 comment | 58 complexity | a6c42de0bcd9029221abf068868a6909 MD5 | raw file
  1. <?php
  2. //IMathAS: Upload multiple grades from .csv file
  3. //(c) 2009 David Lippman
  4. /*** master php includes *******/
  5. require("../validate.php");
  6. //set some page specific variables and counters
  7. $overwriteBody = 0;
  8. $body = "";
  9. $pagetitle = "Upload Multiple Grades";
  10. //CHECK PERMISSIONS AND SET FLAGS
  11. if (!(isset($teacherid))) {
  12. $overwriteBody = 1;
  13. $body = "You need to log in as a teacher to access this page";
  14. } else { //PERMISSIONS ARE OK, PERFORM DATA MANIPULATION
  15. $cid = $_GET['cid'];
  16. $dir = rtrim(dirname(dirname(__FILE__)), '/\\').'/admin/import/';
  17. if (isset($_POST['thefile'])) {
  18. //already uploaded file, ready for official upload
  19. $filename = basename($_POST['thefile']);
  20. if (!file_exists($dir.$filename)) {
  21. echo "File is missing!";
  22. exit;
  23. }
  24. $query = "SELECT imas_users.id,imas_users.SID FROM imas_users JOIN imas_students ON imas_students.userid=imas_users.id WHERE imas_students.courseid='$cid'";
  25. $result = mysql_query($query) or die("Query failed : $query; " . mysql_error());
  26. while ($row = mysql_fetch_row($result)) {
  27. $useridarr[$row[1]] = $row[0];
  28. }
  29. $coltoadd = $_POST['addcol'];
  30. require_once("parsedatetime.php");
  31. if ($_POST['sdatetype']=='0') {
  32. $showdate = 0;
  33. } else {
  34. $showdate = parsedatetime($_POST['sdate'],$_POST['stime']);
  35. }
  36. $gradestodel = array();
  37. foreach ($coltoadd as $col) {
  38. if (trim($_POST["colname$col"])=='') {continue;}
  39. $name = trim($_POST["colname$col"]);
  40. $pts = intval($_POST["colpts$col"]);
  41. $cnt = $_POST["colcnt$col"];
  42. $gbcat = $_POST["colgbcat$col"];
  43. if ($_POST["coloverwrite$col"]>0) {
  44. //we're going to check that this id really belongs to this course. Don't want cross-course hacking :)
  45. $query = "SELECT id FROM imas_gbitems WHERE id='{$_POST["coloverwrite$col"]}' AND courseid='$cid'";
  46. $result = mysql_query($query) or die("Query failed : " . mysql_error());
  47. if (mysql_num_rows($result)>0) { //if this fails, we'll end up creating a new item
  48. $gbitemid[$col] = mysql_result($result,0,0);
  49. //delete old grades
  50. //$query = "DELETE FROM imas_grades WHERE gbitemid={$gbitemid[$col]}";
  51. //mysql_query($query) or die("Query failed : " . mysql_error());
  52. $gradestodel[$col] = array();
  53. continue;
  54. }
  55. }
  56. $query = "INSERT INTO imas_gbitems (courseid,name,points,showdate,gbcategory,cntingb,tutoredit) VALUES ";
  57. $query .= "('$cid','$name','$pts',$showdate,'$gbcat','$cnt',0) ";
  58. mysql_query($query) or die("Query failed : " . mysql_error());
  59. $gbitemid[$col] = mysql_insert_id();
  60. }
  61. $adds = array();
  62. if (count($gbitemid)>0) {
  63. $handle = fopen($dir.$filename,'r');
  64. for ($i = 0; $i<$_POST['headerrows']; $i++) {
  65. $line = fgetcsv($handle,4096);
  66. }
  67. $sidcol = $_POST['sidcol'] - 1;
  68. while ($line = fgetcsv($handle, 4096)) { //for each student
  69. if ($line[$sidcol]=='' || !isset($useridarr[$line[$sidcol]])) {
  70. //echo "breaking 1";
  71. //print_r($line);
  72. continue;
  73. }
  74. $stu = $useridarr[$line[$sidcol]];
  75. foreach ($gbitemid as $col=>$gid) { //for each gbitem we're adding
  76. $fbcol = $_POST["colfeedback$col"];
  77. $feedback = '';
  78. if (trim($fbcol)!='' && intval($fbcol)>0) {
  79. $feedback = addslashes($line[intval($fbcol)-1]);
  80. }
  81. if (trim($line[$col])=='' || $line[$col] == '-') {
  82. //echo "breaking 2";
  83. //print_r($line);
  84. if ($feedback != '') {
  85. $score = 'NULL';
  86. } else {
  87. continue;
  88. }
  89. } else {
  90. $score = floatval($line[$col]);
  91. }
  92. if (isset($gradestodel[$col])) {
  93. $gradestodel[$col][] = $stu;
  94. }
  95. $adds[] = "($gid,$stu,$score,'$feedback')";
  96. }
  97. }
  98. fclose($handle);
  99. //delete any data we're overwriting
  100. foreach ($gradestodel as $col=>$stus) {
  101. if (count($stus)>0) {
  102. $stulist = implode(',',$stus);
  103. $query = "DELETE FROM imas_grades WHERE gbitemid={$gbitemid[$col]} AND userid IN ($stulist)";
  104. mysql_query($query) or die("Query failed : " . mysql_error());
  105. }
  106. }
  107. //now we load in the data!
  108. if (count($adds)>0) {
  109. $query = "INSERT INTO imas_grades (gbitemid,userid,score,feedback) VALUES ";
  110. $query .= implode(',',$adds);
  111. mysql_query($query) or die("Query failed : " . mysql_error());
  112. //echo $query;
  113. }
  114. }
  115. unlink($dir.$filename);
  116. header("Location: http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/chgoffline.php?cid=$cid");
  117. exit;
  118. } else if (isset($_FILES['userfile']['name']) && $_FILES['userfile']['name']!='') {
  119. //upload file
  120. if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
  121. $k = 0;
  122. while (file_exists($dir . "upload$k.csv")) {
  123. $k++;
  124. }
  125. $uploadfile = "upload$k.csv";
  126. if (move_uploaded_file($_FILES['userfile']['tmp_name'], $dir.$uploadfile)) {
  127. //parse out header info
  128. $page_fileHiddenInput = '<input type="hidden" name="thefile" value="'.$uploadfile.'" />';
  129. $handle = fopen($dir.$uploadfile,'r');
  130. $hrow = fgetcsv($handle,4096);
  131. $columndata = array();
  132. $names = array();
  133. if ($_POST['headerrows']==2) {
  134. $srow = fgetcsv($handle,4096);
  135. }
  136. fclose($handle);
  137. for ($i=0; $i<count($hrow); $i++) {
  138. if ($hrow[$i]=='Username') {
  139. $usernamecol = $i;
  140. } else if ($hrow[$i]=='Name' || $hrow[$i]=='Section' || $hrow[$i]=='Code') {
  141. continue;
  142. } else if (strpos(strtolower($hrow[$i]),'comment')!==false || strpos(strtolower($hrow[$i]),'feedback')!==false) {
  143. $columndata[$i-1][2] = $i;
  144. } else {
  145. if (isset($srow[$i])) {
  146. $p = explode(':',$hrow[$i]);
  147. if (count($p)>1) {
  148. $names[$i] = strip_tags($p[0]);
  149. } else {
  150. $names[$i] = strip_tags($hrow[$i]);
  151. }
  152. $pts = intval(preg_replace('/[^\d\.]/','',$srow[$i]));
  153. //if ($pts==0) {$pts = '';}
  154. } else {
  155. $p = explode(':',$hrow[$i]);
  156. if (count($p)>1) {
  157. $pts = intval(preg_replace('/[^\d\.]/','',$p[count($p)-1]));
  158. $names[$i] = strip_tags($p[0]);
  159. } else {
  160. $pts = 0;
  161. $names[$i] = strip_tags($hrow[$i]);
  162. }
  163. //if ($pts==0) {$pts = '';}
  164. }
  165. $columndata[$i] = array($names[$i],$pts,-1,0);
  166. }
  167. }
  168. //look to see if any of these names have been used before
  169. foreach ($names as $k=>$n) {
  170. //prep for db use
  171. $names[$k] = addslashes($n);
  172. }
  173. $namelist = "'".implode("','",$names)."'";
  174. $query = "SELECT id,name FROM imas_gbitems WHERE name IN ($namelist) AND courseid='$cid'";
  175. $result = mysql_query($query) or die("Query failed : " . mysql_error());
  176. while ($row = mysql_fetch_row($result)) {
  177. $loc = array_search($row[1],$names);
  178. if ($loc===false) {continue; } //shouldn't happen
  179. $columndata[$loc][3] = $row[0]; //store existing gbitems.id
  180. }
  181. if (!isset($usernamecol)) {
  182. $usernamecol = 1;
  183. }
  184. } else {
  185. $overwriteBody = 1;
  186. $body = "<p>Error uploading file!</p>\n";
  187. }
  188. } else {
  189. $overwriteBody = 1;
  190. $body = "File Upload error";
  191. }
  192. }
  193. $curBreadcrumb ="$breadcrumbbase <a href=\"course.php?cid={$_GET['cid']}\">$coursename</a> ";
  194. $curBreadcrumb .=" &gt; <a href=\"gradebook.php?stu=0&gbmode={$_GET['gbmode']}&cid=$cid\">Gradebook</a> ";
  195. $curBreadcrumb .=" &gt; <a href=\"chgoffline.php?stu=0&cid=$cid\">Manage Offline Grades</a> &gt; Upload Multiple Grades";
  196. }
  197. /******* begin html output ********/
  198. $placeinhead = "<script type=\"text/javascript\" src=\"$imasroot/javascript/DatePicker.js\"></script>";
  199. require("../header.php");
  200. echo '<div class="breadcrumb">'.$curBreadcrumb.'</div>';
  201. echo '<div id="headeruploadmultgrades" class="pagetitle"><h2>Upload Multiple Grades</h2></div>';
  202. if ($overwriteBody==1) {
  203. echo $body;
  204. } else {
  205. echo '<form id="qform" enctype="multipart/form-data" method=post action="uploadmultgrades.php?cid='.$cid.'">';
  206. if (isset($page_fileHiddenInput)) {
  207. //file has been uploaded, need to know what to import
  208. echo $page_fileHiddenInput;
  209. echo '<input type="hidden" name="headerrows" value="'.$_POST['headerrows'].'" />';
  210. $sdate = tzdate("m/d/Y",time());
  211. $stime = tzdate("g:i a",time());
  212. ?>
  213. <span class=form>Username is in column:</span>
  214. <span class=formright><input type=text name="sidcol" size=4 value="<?php echo $usernamecol+1; ?>"></span><br class=form />
  215. <span class=form>Show grade to students after:</span><span class=formright><input type=radio name="sdatetype" value="0" <?php if ($showdate=='0') {echo "checked=1";}?>/> Always<br/>
  216. <input type=radio name="sdatetype" value="sdate" <?php if ($showdate!='0') {echo "checked=1";}?>/><input type=text size=10 name=sdate value="<?php echo $sdate;?>">
  217. <a href="#" onClick="displayDatePicker('sdate', this); return false"><img src="../img/cal.gif" alt="Calendar"/></A>
  218. at <input type=text size=10 name=stime value="<?php echo $stime;?>"></span><BR class=form>
  219. <p>Check: <a href="#" onclick="return chkAllNone('qform','addcol[]',true)">All</a> <a href="#" onclick="return chkAllNone('qform','addcol[]',false)">None</a></p>
  220. <table class="gb">
  221. <thead>
  222. <tr><th>In column</th><th>Load this?</th><th>Overwrite?</th><th>Name</th><th>Points</th><th>Count?</th><th>Gradebook Category</th><th>Feedback in column<br/>(blank for none)</th></tr>
  223. </thead>
  224. <tbody>
  225. <?php
  226. $query = "SELECT id,name FROM imas_gbcats WHERE courseid='$cid'";
  227. $result = mysql_query($query) or die("Query failed : " . mysql_error());
  228. $gbcatoptions = '<option value="0" selected=1>Default</option>';
  229. if (mysql_num_rows($result)>0) {
  230. while ($row = mysql_fetch_row($result)) {
  231. $gbcatoptions .= "<option value=\"{$row[0]}\">{$row[1]}</option>\n";
  232. }
  233. }
  234. foreach ($columndata as $col=>$data) {
  235. echo '<tr><td>'.($col+1).'</td>';
  236. echo '<td><input type="checkbox" name="addcol[]" value="'.$col.'" /></td>';
  237. echo '<td><select name="coloverwrite'.$col.'"><option value="0" ';
  238. if ($data[3]==0) {echo 'selected="selected"';}
  239. echo '>Add as new item</option>';
  240. if ($data[3]>0) {
  241. echo '<option value="'.$data[3].'" selected="selected">Overwrite existing scores</option>';
  242. }
  243. echo '</select></td>';
  244. echo '<td><input type="text" size="20" name="colname'.$col.'" value="'.htmlentities($data[0]).'" /></td>';
  245. echo '<td><input type="text" size="3" name="colpts'.$col.'" value="'.$data[1].'" /></td>';
  246. echo '<td><select name="colcnt'.$col.'">';
  247. echo '<option value="1" selected="selected">Count in gradebook</option>';
  248. echo '<option value="0">Don\'t count and hide from students</option>';
  249. echo '<option value="3">Don\'t count in grade total</option>';
  250. echo '<option value="2">Count as extra credit</option></select></td>';
  251. echo '<td><select name="colgbcat'.$col.'">'.$gbcatoptions.'</select></td>';
  252. echo '<td><input type="text" size="3" name="colfeedback'.$col.'" value="'.($data[2]>-1?$data[2]+1:'').'" /></td>';
  253. echo '</tr>';
  254. }
  255. echo '</tbody></table>';
  256. echo '<p><input type="submit" value="Upload" /></p>';
  257. echo '<p>Note: If you choose to overwrite existing scores, it will replace existing scores with any non-blank scores in your upload.</p>';
  258. } else {
  259. //need file
  260. ?>
  261. <p>The uploaded file must be in Comma Separated Values (.CSV) file format, and contain a column with
  262. the students' usernames. If you are including feedback as well as grades, upload will be much easier if the
  263. feedback is in the column immediately following the scores, and if the column header contains the word Comment or Feedback</p>
  264. <p>
  265. <span class=form>Import File: </span>
  266. <span class=formright>
  267. <input type="hidden" name="MAX_FILE_SIZE" value="300000" />
  268. <input name="userfile" type="file" />
  269. </span><br class=form />
  270. <span class=form>File contains a header row:</span>
  271. <span class=formright>
  272. <input type=radio name="headerrows" value="1" checked="checked">Yes, one<br/>
  273. <input type=radio name="headerrows" value="2">Yes, with second for points possible
  274. </span><br class=form />
  275. <div class=submit><input type=submit value="Continue"></div>
  276. </p>
  277. <?php
  278. }
  279. echo '</form>';
  280. }
  281. require("../footer.php");
  282. ?>