Dokeos PHP Cross Reference Learning Management Systems

Source: /main/work/work.lib.php - 1614 lines - 76517 bytes - Summary - Text - Print

   1  <?php //$Id: work.lib.php 22357 2009-07-24 17:44:17Z juliomontoya $
   2  /* For licensing terms, see /dokeos_license.txt */
   3  /**
   4  *    @package dokeos.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  *     @version $Id: work.lib.php 22357 2009-07-24 17:44:17Z juliomontoya $
  10  */
  11  /**
  12   * Displays action links (for admins, authorized groups members and authorized students)
  13   * @param    string    Current dir
  14   * @param    integer    Whether to show tool options
  15   * @param    integer    Whether to show upload form option
  16   * @return    void
  17   */
  18  
  19  require_once dirname(__FILE__).'/../document/document.inc.php';
  20  require_once dirname(__FILE__).'/../inc/lib/fileDisplay.lib.php';
  21  require_once (api_get_path(LIBRARY_PATH) . 'formvalidator/FormValidator.class.php');
  22  
  23  function display_action_links($cur_dir_path, $always_show_tool_options, $always_show_upload_form)
  24  {
  25      global $gradebook;
  26      global $charset,$_course;
  27      $display_output = "";
  28      $origin = isset($_GET['origin'])?Security::remove_XSS($_GET['origin']):'';
  29      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  30  
  31      $origin = api_get_tools_lists($origin);
  32      echo '<div class="actions">';
  33      
  34      if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'correct_paper'){
  35          $sql = "SELECT parent_id FROM $work_table WHERE id = ".$_REQUEST['id'];
  36          $res = Database::query($sql,__FILE__,__LINE__);
  37          $row = Database::fetch_row($res);
  38          $display_output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=view_papers&assignment_id='.$row[0].'&origin='.$origin.'&gradebook='.$gradebook.'&curdirpath='.$parent_dir.'">'.Display::return_icon('pixel.gif',get_lang('BackToPapersList'),array('class' => 'toolactionplaceholdericon toolactionback')).get_lang('BackToPapersList').'</a>';
  39      }
  40      else if(isset($_REQUEST['action'])){
  41          $display_output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&origin='.$origin.'&gradebook='.$gradebook.'&curdirpath='.$parent_dir.'">'.Display::return_icon('pixel.gif',get_lang('BackToPapersList'),array('class' => 'toolactionplaceholdericon toolactionback')).get_lang('BackToWorksList').'</a>';
  42      }
  43      
  44      if(api_is_platform_admin() || api_is_grouptutor($_course,api_get_session_id(),api_get_user_id()) || api_is_allowed_to_edit()){
  45      $display_output .=    '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=new_assignment&toolgroup='.Security::remove_XSS($_GET['toolgroup']).'&amp;curdirpath='.$cur_dir_path.'&amp;createdir=1&origin='.$origin.'&gradebook='.$gradebook.'">'.Display::return_icon('pixel.gif',get_lang('CreateAssignment'),array('class' => 'toolactionplaceholdericon toolactionnewassignment')).get_lang('CreateAssignment').' </a>';
  46      }
  47      
  48  //    $sql = "SELECT * FROM $work_table WHERE filetype='folder' AND parent_id='0' AND session_id = ".api_get_session_id();
  49      $sql = "SELECT * FROM $work_table WHERE filetype='folder' AND parent_id='0'";
  50      $res = Database::query($sql,__FILE__,__LINE__);
  51      $no_of_assignment = Database::num_rows($res);
  52      
  53  //    if(!api_is_platform_admin()){
  54      if($_REQUEST['action'] != 'new_assignment'){
  55          if($no_of_assignment > 0){
  56          //    if(!api_is_grouptutor($_course,api_get_session_id(),api_get_user_id())){
  57              $display_output .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&curdirpath=".$cur_dir_path."&action=submit_work&amp;display_upload_form=true&amp;origin=".$origin."&amp;gradebook=".$gradebook."\">".Display::return_icon('pixel.gif',get_lang('UploadADocument'),array('class' => 'toolactionplaceholdericon toolactionupload')). get_lang("UploadADocument") .'</a>';
  58          //    }
  59          /*    else {
  60              $display_output .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&curdirpath=".$cur_dir_path."&action=submit_work&amp;display_upload_form=true&amp;origin=".$origin."&amp;gradebook=".$gradebook."\">".Display::return_icon('up.png', get_lang("UploadADocument"))." ". get_lang("UploadADocument") .'</a>';
  61              }*/
  62          }
  63      }
  64  //    }
  65  
  66      if ($display_output != "")
  67      {
  68          echo $display_output;
  69      }
  70      echo '</div>';
  71  }
  72  
  73  function create_unexisting_work_directory($base_work_dir,$desired_dir_name)
  74  {
  75      $nb = '';
  76      $base_work_dir = (substr($base_work_dir,-1,1)=='/'?$base_work_dir:$base_work_dir.'/');
  77      while ( file_exists($base_work_dir.$desired_dir_name.$nb) ) {
  78          $nb += 1;
  79      }
  80      //echo "creating ".$base_work_dir.$desired_dir_name.$nb."#...";
  81      $perm = api_get_setting('permissions_for_new_directories');
  82      $perm = octdec(!empty($perm)?$perm:'0770');
  83      if ( mkdir($base_work_dir.$desired_dir_name.$nb, $perm)) {
  84          chmod($base_work_dir.$desired_dir_name.$nb, $perm);
  85          return $desired_dir_name.$nb;
  86      } else {
  87      return false;
  88      }
  89  }
  90  
  91  function create_new_assignment($cur_dir_path, $stok, $ctok, $add_lp_param){    
  92      global $_course;
  93      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  94      $TSTDPUBASG            = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  95      
  96      if (isset ($_REQUEST['createdir']) && (api_is_allowed_to_edit() || api_is_grouptutor($_course,api_get_session_id(),api_get_user_id()))) {
  97          $form = new FormValidator('new_assignment', 'post','work.php?action=new_assignment&createdir='.$_REQUEST['createdir'].'origin='.api_get_tools_lists($_REQUEST['origin']).'&gradebook='.(empty($_GET['gradebook'])?'':'view'). $add_lp_param);
  98          $form->addElement('header', '', get_lang('CreateAssignment'));
  99          $form->addElement('hidden','curdirpath',Security :: remove_XSS($cur_dir_path));
 100          $form->addElement('hidden','sec_token',$stok);
 101          $form->addElement('text', 'new_dir', get_lang('AssignmentName'), 'class="focus";style="width:500px;"');    
 102      //    $form->addElement('textarea','description',get_lang('Description'),array ('rows' => '3', 'cols' => '62'));
 103          $form->add_html_editor('description',get_lang('Description'), false, false, array('ToolbarSet' => 'Survey', 'Width' => '600px', 'Height' => '200px'));
 104          $form->addElement('datepicker', 'deadline', get_lang('Deadline'), array('form_name'=>'new_assignment'));
 105          $form->addElement('radio', 'confidential', get_lang('Confidential'), get_lang('EachStudent'), 0);
 106          $form->addElement('radio', 'confidential', '', get_lang('AllStudent'), 1);    
 107          $option = array();
 108          for($i=0;$i<=20;$i++){
 109              $option[] = $i;
 110          }
 111          $form->addElement('select', 'score', get_lang('Score'), $option);
 112          $form->addElement('style_submit_button', 'submit', get_lang('Ok'), 'class="save"');
 113  
 114          $defaults = array();
 115          $defaults['confidential'] = 0;
 116          $defaults['score'] = 20;
 117          $defaults['deadline'] = date('Y-m-d 12:00:00');
 118          $form->setDefaults($defaults);
 119          if($form -> validate()) {            
 120              $assignment = $form->exportValues();
 121              $new_dir = $assignment['new_dir'];
 122              $description = $assignment['description'];
 123              $deadline = $assignment['deadline'];
 124              $confidential = $assignment['confidential'];
 125              $score = $assignment['score'];
 126              $new_dir = str_replace(' ','_',$new_dir);
 127              $base_work_dir = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/work';
 128              $added_slash = (substr($cur_dir_path, -1, 1) == '/') ? '' : '/';
 129              $directory = Security::remove_XSS($new_dir);
 130              $directory = replace_dangerous_char($directory);
 131              $directory = disable_dangerous_file($directory);
 132              $dir_name = $cur_dir_path . $added_slash . $directory;
 133              $created_dir = create_unexisting_work_directory($base_work_dir, $dir_name);
 134              // we insert here the directory in the table $work_table
 135              $dir_name_sql='';
 136              
 137              if ($ctok==$assignment['sec_token']) {
 138                  
 139                  if (!empty($created_dir)) {
 140                      if ($cur_dir_path=='/') {
 141                          $dir_name_sql = $created_dir;
 142                      } else {
 143                          $dir_name_sql = '/'.$created_dir;
 144                      }
 145                      
 146                      $sql_add_publication = "INSERT INTO " . $work_table . " SET " .
 147                                             "url         = '".Database::escape_string($dir_name_sql)."',
 148                                             title        = '".Database::escape_string($assignment['new_dir'])."',
 149                                             description     = '".Database::escape_string($assignment['description'])."',
 150                                             author          = '',
 151                                             active    = '0',
 152                                             accepted    = '1',
 153                                             filetype     = 'folder',                                           
 154                                             sent_date    = NOW(),                                           
 155                                             parent_id    = '',
 156                                             qualificator_id    = '',
 157                                             qualification = ".Database::escape_string($assignment['score']).",
 158                                             view_properties = ".$confidential.",
 159                                             date_of_qualification    = '0000-00-00 00:00:00',
 160                                             weight   = '".Database::escape_string($assignment['score'])."',
 161                                             session_id   = ".api_get_session_id();
 162                      
 163                      Database::query($sql_add_publication, __FILE__, __LINE__);
 164  
 165                      // add the directory
 166                      $id = Database::insert_id();
 167                      api_item_property_update($_course, 'work', $id, 'DirectoryCreated', api_get_user_id());
 168  
 169                      $sql_add_homework = "INSERT INTO $TSTDPUBASG SET " .
 170                                          "expires_on         = '".$assignment['deadline']."',
 171                                          ends_on             = '".$assignment['deadline']."',
 172                                          add_to_calendar     = '1',
 173                                          enable_qualification = '1',
 174                                          publication_id = '".$id."'";
 175                      
 176                      Database::query($sql_add_homework, __FILE__, __LINE__);
 177                      $datetime = explode(" ", $assignment['deadline']);
 178                      $dateparts = explode("-", $datetime[0]);        
 179                      $deadline = $dateparts[1].'/'.$dateparts[2].'/'.$dateparts[0];
 180                      send_mail_to_students($new_dir,$description,$deadline);
 181                      
 182                  }
 183              
 184              }            
 185          echo '<script>window.location.href = "'.api_get_self().'?'.api_get_cidReq().'"</script>';
 186          }
 187          $form->display();
 188      }    
 189  }
 190  
 191  function edit_assignment($assignment_id, $cur_dir_path, $stok, $ctok, $add_lp_param){
 192      global $_course;
 193      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
 194      $TSTDPUBASG            = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
 195      
 196      if (isset ($assignment_id) && (api_is_allowed_to_edit() || api_is_grouptutor($_course,api_get_session_id(),api_get_user_id()))) {
 197          $form = new FormValidator('edit_assignment', 'post','work.php?action=edit_assignment&edit_dir='.$_REQUEST['edit_dir'].'&assignment_id='.$assignment_id.'&origin='.api_get_tools_lists($_REQUEST['origin']).'&gradebook='.(empty($_GET['gradebook'])?'':'view'). $add_lp_param);
 198          $form->addElement('header', '', get_lang('EditAssignment'));
 199          $form->addElement('hidden','curdirpath',Security :: remove_XSS($cur_dir_path));
 200          $form->addElement('hidden','sec_token',$stok);
 201          $form->addElement('text', 'edit_dir', get_lang('AssignmentName'), 'class="focus";style="width:500px;"');    
 202      //    $form->addElement('textarea','description',get_lang('Description'),array ('rows' => '3', 'cols' => '62'));
 203          $form->add_html_editor('description',get_lang('Description'), false, false, array('ToolbarSet' => 'survey', 'Width' => '600px', 'Height' => '150px'));
 204          $form->addElement('datepicker', 'deadline', get_lang('Deadline'), array('form_name'=>'new_assignment'));
 205          $form->addElement('radio', 'confidential', get_lang('Confidential'), get_lang('EachStudent'), 0);
 206          $form->addElement('radio', 'confidential', '', get_lang('AllStudent'), 1);    
 207          $option = array();
 208          for($i=0;$i<=20;$i++){
 209              $option[] = $i;
 210          }
 211          $form->addElement('select', 'score', get_lang('Score'), $option);
 212          $form->addElement('style_submit_button', 'submit', get_lang('Ok'), 'class="save"');
 213          
 214          $sql = "SELECT work.*, workpub.ends_on AS deadline FROM $work_table work, $TSTDPUBASG workpub WHERE work.id = workpub.publication_id AND work.id = ".$assignment_id;
 215          $result = Database::query($sql, __FILE__, __LINE__);
 216          $row = Database :: fetch_array($result);
 217          
 218          $defaults = array();
 219          $defaults['edit_dir'] = $row['title'];
 220          $defaults['description'] = $row['description'];
 221          $defaults['confidential'] = $row['view_properties'];
 222          $defaults['score'] = $row['qualification'];
 223          $defaults['deadline'] = $row['deadline'];
 224          $defaults['curdirpath'] = $row['title'];
 225          $form->setDefaults($defaults);
 226          if($form -> validate()) {            
 227              $assignment = $form->exportValues();
 228              $edit_dir = $assignment['edit_dir'];
 229              $description = $assignment['description'];
 230              $deadline = $assignment['deadline'];
 231              $confidential = $assignment['confidential'];
 232              $score = $assignment['score'];
 233  
 234              $mydir = $assignment['curdirpath'];            
 235              $dir_name = replace_dangerous_char($edit_dir);
 236              $dir_name = disable_dangerous_file($dir_name);
 237              
 238              update_dir_name($mydir,$dir_name);    
 239              
 240              $sql_update_assignment = "UPDATE $work_table SET title = '".Database::escape_string($edit_dir)."',
 241                                                               description = '".Database::escape_string($description)."',
 242                                                               view_properties = ".$confidential.",
 243                                                               qualification = ".$score."
 244                                             WHERE id = ".$assignment_id;
 245              Database::query($sql_update_assignment, __FILE__, __LINE__);
 246  
 247              $sql_update_publication = "UPDATE $TSTDPUBASG SET expires_on = '".Database::escape_string($deadline)."',
 248                                                               ends_on = '".Database::escape_string($deadline)."'
 249                                              WHERE publication_id = ".$assignment_id;
 250              Database::query($sql_update_publication, __FILE__, __LINE__);
 251  
 252              echo '<script>window.location.href = "'.api_get_self().'?'.api_get_cidReq().'"</script>';
 253  
 254          }
 255          $form->display();
 256  
 257      }
 258  }
 259  
 260  function assignment_list($cur_dir_path){    
 261      global $_course;
 262      if (api_is_allowed_to_edit() || api_is_grouptutor($_course,api_get_session_id(),api_get_user_id())){
 263          $default_column = 2;
 264      }
 265      else {
 266          $default_column = 1;
 267      }
 268      $tablename = 'assignment_table';
 269      $sortable_data = get_assignment_data($cur_dir_path);
 270  
 271      $table = new SortableTableFromArrayConfig($sortable_data,$default_column,20,$tablename,$column_show,$column_order,'ASC');
 272      
 273      if (api_is_allowed_to_edit() || api_is_grouptutor($_course,api_get_session_id(),api_get_user_id())){
 274      $table->set_header(0, '', false);    
 275      $table->set_header(1, get_lang('Edit'));    
 276      $table->set_header(2, get_lang('Assignment'));    
 277      $table->set_header(3, get_lang('Summary'),'','style="width:60%;"');    
 278      $table->set_header(4, get_lang('Deadline'));
 279      }        
 280      else {
 281      $table->set_header(0, '', false);
 282      $table->set_header(1, get_lang('Assignment'));    
 283      $table->set_header(2, get_lang('Summary'),'','style="width:60%;"');    
 284      $table->set_header(3, get_lang('Deadline'));
 285      }    
 286      if (api_is_allowed_to_edit() || api_is_grouptutor($_course,api_get_session_id(),api_get_user_id())){
 287      $table->set_header(5, get_lang('Papers'));
 288      $table->set_header(6, get_lang('Corrected'));
 289      $table->set_header(7, get_lang('Average'));
 290      $table->set_header(8, get_lang('DownloadAll'));
 291      }
 292  /*    elseif(api_is_grouptutor($_course,api_get_session_id(),api_get_user_id())){
 293      $table->set_header(4, get_lang('Papers'));
 294      $table->set_header(5, get_lang('Corrected'));
 295      $table->set_header(6, get_lang('Average'));
 296      $table->set_header(7, get_lang('DownloadAll'));
 297      }*/
 298      
 299      if (api_is_allowed_to_edit() || api_is_grouptutor($_course,api_get_session_id(),api_get_user_id())){
 300          $table->set_form_actions(array ('delete_assignment' => get_lang('Delete')));
 301      } 
 302      $table->display();
 303  }
 304  
 305  function get_assignment_data($cur_dir_path) {
 306      global $_course;
 307      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
 308      $TSTDPUBASG            = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
 309      $itemproperty_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 310  
 311      //condition for the session
 312      $session_id = api_get_session_id();
 313      $condition_session = api_get_session_condition($session_id);    
 314  
 315      if (!empty($_SESSION['toolgroup'])) {
 316          $group_query = " AND post_group_id = '".$_SESSION['toolgroup']."' "; // set to select only messages posted by the user's group        
 317      } else {
 318          $group_query = " AND post_group_id = '0' ";        
 319      }
 320  
 321      /*$sql = "SELECT work.id AS assignment_id,work.title,work.description,work.url,work.parent_id,work.qualification,workassign.ends_on 
 322                  FROM $work_table work, $TSTDPUBASG workassign 
 323                  WHERE work.id = workassign.publication_id ".$group_query;*/
 324          
 325          $sql = "SELECT work.id AS assignment_id,work.title,work.filetype, work.description,work.url,work.parent_id,work.qualification,workassign.ends_on 
 326                  FROM $work_table work LEFT JOIN $TSTDPUBASG workassign ON work.id = workassign.publication_id
 327                  WHERE parent_id = 0 ".$group_query;
 328          
 329      $res = Database::query($sql, __FILE__, __LINE__);    
 330      $assignments = array ();
 331      while ($assignment = Database::fetch_array($res)) {        
 332          $assignment_id = $assignment['assignment_id'];
 333          $assignment_title = !empty($assignment['title']) ? $assignment['title'] : substr($assignment['url'], 1);
 334          $assignment_description = $assignment['description'];
 335          $assignment_url = $assignment['url'];
 336          $parent_id = $assignment['parent_id'];
 337          $qualification = $assignment['qualification'];
 338          $assignment_deadline = $assignment['ends_on'];    
 339          
 340                  if ($assignment['filetype'] == 'folder') {                
 341          $icon_link = '<center>'.Display::return_icon('pixel.gif','',array('class' => 'actionplaceholdericon actionstudentviewwork')).'</center>';
 342          
 343          $edit_link = '<center><a href="'.api_get_self().'?'.api_get_cidReq().'&action=edit_assignment&assignment_id='.$assignment_id.'&origin='.$_REQUEST['origin'].'&edit_dir='.$assignment_title.'">'.Display::return_icon('pixel.gif',get_lang('Edit'),array('class' => 'actionplaceholdericon actionedit')).'</a></center>';    
 344  
 345          $title_link = '<a href="'.api_get_self().'?'.api_get_cidReq().'&action=view_papers&curdirpath='.$assignment_title.'&assignment_id='.$assignment_id.'">'.$assignment_title.'</a>';
 346                  } else {
 347                      $icon_link = $edit_link = build_document_icon_tag('file', $assignment['url']);
 348                      $title_link = '<a href="download.php?file='.$assignment['url'].'">'.$assignment_title.'</a>';
 349                  }
 350  
 351          $datetime = explode(" ", $assignment_deadline);
 352          $dateparts = explode("-", $datetime[0]);    
 353          if(api_get_interface_language() == 'french'){
 354          $deadline = $dateparts[2].'/'.$dateparts[1].'/'.$dateparts[0];
 355          }
 356          else {
 357          $deadline = $dateparts[1].'/'.$dateparts[2].'/'.$dateparts[0];
 358          }
 359  
 360          if(api_is_grouptutor($_course,api_get_session_id(),api_get_user_id())){
 361          $users_list = get_grouptutor_users(api_get_user_id());
 362  
 363          $sql_paper = "SELECT * FROM $work_table work,$itemproperty_table ip WHERE work.id = ip.ref AND ip.insert_user_id IN (".$users_list.") AND work.parent_id = ".$assignment_id." AND work.filetype = 'file'";
 364          }
 365          else {
 366          $sql_paper = "SELECT * FROM $work_table WHERE parent_id = ".$assignment_id." AND filetype = 'file'";
 367          }
 368          
 369          $res_paper = Database::query($sql_paper, __FILE__, __LINE__);
 370          $count_papers = Database::num_rows($res_paper);
 371          $number_of_papers = '<center>'.$count_papers.'</center>';
 372          
 373          if(api_is_grouptutor($_course,api_get_session_id(),api_get_user_id())){
 374          $users_list = get_grouptutor_users(api_get_user_id());
 375          $sql_corrected = "SELECT * FROM $work_table work,$itemproperty_table ip WHERE work.id = ip.ref AND ip.insert_user_id IN (".$users_list.") AND parent_id = ".$assignment_id." AND qualificator_id = 1 AND filetype = 'file'";
 376          }
 377          else {
 378          $sql_corrected = "SELECT * FROM $work_table WHERE parent_id = ".$assignment_id." AND qualificator_id = 1 AND filetype = 'file'";
 379          }
 380          $res_corrected = Database::query($sql_corrected, __FILE__, __LINE__);
 381          $number_of_papers_corrected = '<center>'.Database::num_rows($res_corrected).'</center>';
 382          
 383          if(api_is_grouptutor($_course,api_get_session_id(),api_get_user_id())){
 384          $users_list = get_grouptutor_users(api_get_user_id());
 385          $sql_sum = "SELECT sum(qualification) AS totalmarks FROM $work_table  work,$itemproperty_table ip WHERE work.id = ip.ref AND ip.insert_user_id IN (".$users_list.") AND parent_id = ".$assignment_id." AND qualificator_id = 1 AND filetype = 'file'";
 386          }
 387          else {
 388          $sql_sum = "SELECT sum(qualification) AS totalmarks FROM $work_table WHERE parent_id = ".$assignment_id." AND qualificator_id = 1 AND filetype = 'file'";
 389          }
 390          $res_sum = Database::query($sql_sum, __FILE__, __LINE__);
 391          while($row_sum = Database::fetch_row($res_sum)){
 392              $totalmarks = $row_sum[0];
 393          }
 394          if($totalmarks <> 0){
 395              $average = $totalmarks/Database::num_rows($res_corrected);
 396          }
 397          else {
 398              $average = 0;
 399          }
 400          $average_marks = $average.'/'.round($qualification,2);
 401          
 402                  $download_link = '';
 403                  if ($assignment['filetype'] == 'folder') {
 404                      if ($count_papers >= 1) {
 405                 $download_link = '<center><a href="'.api_get_self().'?'.api_get_cidReq().'&action=downloadfolder&path='.$assignment_url.'">'.Display::return_icon('pixel.gif',get_lang('DownloadAll'),array('class' => 'actionplaceholdericon actionsavebackup')).'</a></center>';
 406                      } else {
 407                 $download_link = '<center>'.Display::return_icon('pixel.gif',get_lang('DownloadAll'),array('class' => 'actionplaceholdericon actionsavebackup')).'</center>';
 408              }
 409                  } else {
 410                      $download_link = '<center><a href="download.php?file='.$assignment['url'].'">'.Display::return_icon('pixel.gif',get_lang('Download'),array('class' => 'actionplaceholdericon actionsavebackup')).'</a>&nbsp;';
 411                      $download_link .= '<a href="'.api_get_self().'?'.api_get_cidReq().'&action=move_form&id='.$assignment['assignment_id'].'">'.Display::return_icon('pixel.gif',get_lang('Move'),array('class' => 'actionplaceholdericon actionworkmove')).'</a></center>';
 412                      $deadline = $number_of_papers = $number_of_papers_corrected = $average_marks = '';
 413                  }
 414          if (api_is_allowed_to_edit() || api_is_grouptutor($_course,api_get_session_id(),api_get_user_id())){
 415          $assignments[] = array($assignment_id,$edit_link,$title_link,strip_tags($assignment_description,'<p><a><span><br><b>'),'<center>'.$deadline.'</center>',$number_of_papers,$number_of_papers_corrected,'<center>'.$average_marks.'</center>',$download_link);
 416          }
 417          else {
 418              $assignments[] = array($icon_link,$title_link,strip_tags($assignment_description,'<p><a><span><br><b>'),'<center>'.$deadline.'</center>');
 419          }
 420      }    
 421      return $assignments;
 422  }
 423  
 424  
 425  function assignment_paper_list($cur_dir_path){
 426      global $_course;
 427      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
 428      
 429      if (isset($_REQUEST['assignment_id'])) {
 430          $my_params = array ('assignment_id' => intval($_REQUEST['assignment_id']));
 431      }
 432      if (isset($_REQUEST['action'])) {
 433          $my_params['action'] = Security::remove_XSS($_REQUEST['action']);
 434      }
 435      $sql = "SELECT title,description FROM $work_table WHERE id = ".intval($_REQUEST['assignment_id']);
 436      $res = Database::query($sql,__FILE__,__LINE__);
 437      $row = Database::fetch_array($res);
 438  
 439      echo '<table width="75%" cellpadding="3" cellspacing="3"><tr><td><span style="color:orange;text-transform:uppercase;font-weight:bold;">'.$row['title'].'</td></tr>
 440      <tr><td><span>'.$row['description'].'</td></tr></table>';
 441  
 442      $default_column = 1;
 443      $tablename = 'paperlist_table';
 444      $sortable_data = get_papers_data();
 445  
 446      $table = new SortableTableFromArrayConfig($sortable_data,$default_column,20,$tablename,$column_show,$column_order,'ASC');
 447      $table->set_additional_parameters($my_params);
 448      if(api_is_allowed_to_edit()){
 449      $table->set_header(0, get_lang('Type'), true);
 450      $table->set_header(1, get_lang('Paper'));    
 451      $table->set_header(2, get_lang('Author'));    
 452      $table->set_header(3, get_lang('GroupName'));    
 453      $table->set_header(4, get_lang('DateSent'));
 454      $table->set_header(5, get_lang('Score'));
 455      }
 456      else if(api_is_grouptutor($_course,api_get_session_id(),api_get_user_id())){
 457      $table->set_header(0, get_lang('Type'), true);
 458      $table->set_header(1, get_lang('Paper'));
 459      $table->set_header(2, get_lang('Summary'));    
 460      $table->set_header(3, get_lang('Author'));    
 461      $table->set_header(4, get_lang('GroupName'));    
 462      $table->set_header(5, get_lang('DateSent'));
 463      $table->set_header(6, get_lang('Corrected'));
 464      $table->set_header(7, get_lang('Score'));
 465      }
 466      else {
 467      $table->set_header(0, get_lang('Type'), true);
 468      $table->set_header(1, get_lang('Paper'));
 469      $table->set_header(2, get_lang('Summary'));    
 470      $table->set_header(3, get_lang('GroupName'));    
 471      $table->set_header(4, get_lang('Corrected'));    
 472      $table->set_header(5, get_lang('Remark'));    
 473      }
 474      if(api_is_allowed_to_edit()){
 475  //    $table->set_header(5, get_lang('Corrected'));
 476      $table->set_header(6, get_lang('Move'));
 477      $table->set_header(7, get_lang('Download'));    
 478      $table->set_header(8, get_lang('Delete'));    
 479      }
 480      
 481      $table->display();
 482  }
 483  
 484  function get_papers_data(){
 485      global $_course;
 486      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
 487      $TSTDPUBASG            = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
 488      $itemproperty_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 489      
 490  //    $sql = "SELECT * FROM $work_table WHERE filetype='folder' AND parent_id='0' AND id != ".$_REQUEST['assignment_id']." AND session_id = ".api_get_session_id();
 491      $sql = "SELECT * FROM $work_table WHERE filetype='folder' AND parent_id='0' AND id != ".intval($_REQUEST['assignment_id']);
 492      $res = Database::query($sql,__FILE__,__LINE__);
 493      $no_of_assignment = Database::num_rows($res);
 494  
 495      $sql = "SELECT work.weight,work.view_properties,workassign.ends_on FROM $work_table work, $TSTDPUBASG workassign WHERE work.id = workassign.publication_id AND work.id = ".intval($_REQUEST['assignment_id']);
 496      $res = Database::query($sql, __FILE__, __LINE__);    
 497      while($row = Database::fetch_row($res)){
 498          $assignment_weight = $row[0];
 499          $confidential = $row[1];
 500          $ends_on = $row[2];
 501      }
 502  
 503      //condition for the session
 504      $session_id = api_get_session_id();
 505      $condition_session = api_get_session_condition($session_id);
 506  
 507  //    $is_coach = api_is_coach($session_id,api_get_course_id());    
 508  
 509  /*    if (!empty($_SESSION['toolgroup'])) {
 510          $group_query = " AND work.post_group_id = '".$_SESSION['toolgroup']."' "; // set to select only messages posted by the user's group        
 511      } else {
 512          $group_query = " AND work.post_group_id = '0' ";        
 513      }    */
 514      
 515      if($confidential == 0){
 516          $users = get_user_grouptutor(api_get_user_id());
 517          $confidential_query = " , $itemproperty_table ip WHERE work.id = ip.ref AND ip.tool = 'work' AND ip.insert_user_id IN (".$users.") AND ";
 518      //    $confidential_query = " , $itemproperty_table ip WHERE work.id = ip.ref AND ip.tool = 'work' AND ip.insert_user_id = ".api_get_user_id()." AND ";
 519      }        
 520      
 521      $sql = "SELECT * FROM $work_table work";
 522      if(api_is_grouptutor($_course,$session_id,api_get_user_id())){
 523          $users_list = get_grouptutor_users(api_get_user_id());
 524          
 525          $sql .= "  , $itemproperty_table ip WHERE work.id = ip.ref AND ip.tool = 'work' AND ip.insert_user_id IN (".$users_list.") AND ";
 526      }
 527      else if(api_is_allowed_to_edit()){
 528          $sql .= " WHERE ";
 529      }
 530      else {
 531          if($confidential == 0){
 532              $sql .= $confidential_query;
 533          }
 534          else {
 535              $sql .= " WHERE ";
 536          }    
 537      }
 538      $sql .= "  work.parent_id = ".intval($_REQUEST['assignment_id']).$group_query;    
 539  
 540      $res = Database::query($sql, __FILE__, __LINE__);    
 541      $papers = array ();
 542      while ($paper = Database::fetch_array($res)) {            
 543          $paper_id = $paper['id'];
 544          $paper_title = $paper['title'];
 545          $paper_url = $paper['url'];
 546          $paper_description = $paper['description'];
 547          $author = $paper['author'];
 548          $sent_date = $paper['sent_date'];
 549          $qualification = $paper['qualification'];
 550          $corrected = $paper['qualificator_id'];
 551          $note = $paper['remark'];
 552  
 553          $datetime = explode(" ", $sent_date);
 554          $dateparts = explode("-", $datetime[0]);    
 555          if(api_get_interface_language() == 'french'){
 556          $date = $dateparts[2].'/'.$dateparts[1].'/'.$dateparts[0];
 557          }
 558          else {
 559          $date = $dateparts[1].'/'.$dateparts[2].'/'.$dateparts[0];
 560          }
 561  
 562          if(strtotime($sent_date) > strtotime($ends_on)){
 563              $date_str = '<span style="align:center;color:red;">'.$date.'</span>';
 564          }
 565          else {
 566              $date_str = '<span style="align:center;">'.$date.'</span>';
 567          }
 568  
 569          $group_name = '';
 570          $group_name = get_group_name($paper_id);
 571  
 572          $paper_icon =  '<center><a href="'.api_get_self().'?'.api_get_cidReq().'&action=correct_paper&id='.$paper_id.'" >'.build_document_icon_tag('file',$paper_url).'</a></center>';
 573          if(api_is_allowed_to_edit()){                    
 574                      $title_tag = '<a href="'.api_get_self().'?'.api_get_cidReq().'&action=correct_paper&id='.$paper_id.'">'.$paper_title.'<br/>'.$paper_description.'</a>';
 575          }
 576          elseif(api_is_grouptutor($_course,$session_id,api_get_user_id())){
 577                      $title_tag = '<a href="'.api_get_self().'?'.api_get_cidReq().'&action=correct_paper&id='.$paper_id.'">'.$paper_title.'</a>';
 578          }
 579          else {
 580                      $paper_icon =  '<center>'.build_document_icon_tag('file',$paper_url).'</center>';
 581                      $title_tag = '<a href="'.api_get_self().'?'.api_get_cidReq().'&action=view_paper&id='.$paper_id.'">'.$paper_title.'</a>';
 582          }
 583          
 584          if($qualification == 0){
 585              $assignment_score = '<center>/</center>';
 586          }
 587          else {
 588              $assignment_score = '<center>'.round($qualification,2).'/'.round($assignment_weight,2).'</center>';
 589          }
 590  
 591          if($corrected == 0){
 592              $corrected_img = '<center>-</center>';
 593          }
 594          else {
 595              $path_parts = pathinfo($paper_url);                                
 596              $new_file_name = $path_parts['filename'].'_corr.'.$path_parts['extension'];    
 597              $new_correct_filename = $path_parts['dirname'].'/'.$new_file_name;
 598              if(file_exists(api_get_path(SYS_COURSE_PATH.$new_correct_filename))){
 599              $corrected_img = '<center><a href="download.php?file='.$paper_url.'">'.Display::return_icon('pixel.gif','',array('class' => 'actionplaceholdericon actionworkcorrect')).'</a></center>';
 600              }
 601              else {
 602              $corrected_img = '<center><a href="download.php?file='.$new_correct_filename.'">'.Display::return_icon('pixel.gif','',array('class' => 'actionplaceholdericon actionworkcorrect')).'</a></center>';
 603              }
 604          }
 605          
 606          if($no_of_assignment > 0){
 607          $move_icon = '<center><a href="'.api_get_self().'?'.api_get_cidReq().'&action=move_paper&assignment_id='.$_REQUEST['assignment_id'].'&id='.$paper_id.'">'.Display::return_icon('pixel.gif',get_lang('Move'),array('class' => 'actionplaceholdericon actionworkmove')).'</a></center>';
 608          }
 609          else {
 610          $move_icon = '<center>'.Display::return_icon('pixel.gif',get_lang('Move'),array('class' => 'actionplaceholdericon actionworkmove')).'</center>';
 611          }
 612          $download_icon = '<center><a href="download.php?file='.$paper_url.'">'.Display::return_icon('pixel.gif',get_lang('Download'),array('class' => 'actionplaceholdericon actionsavebackup')).'</a></center>';
 613          $delete_icon = '<center><a href="'.api_get_self().'?'.api_get_cidReq().'&action=delete_paper&id='.$paper_id.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, api_get_system_encoding()))."'".')) return false;">'.Display::return_icon('pixel.gif',get_lang('Delete'),array('class' => 'actionplaceholdericon actiondelete')).'</a></center>';
 614          
 615          if(api_is_allowed_to_edit()){
 616          $papers[] = array($paper_icon,$title_tag,'<center>'.$author.'</center>','<center>'.$group_name.'</center>','<center>'.$date_str.'</center>',$assignment_score,$move_icon,$download_icon,$delete_icon);
 617          }
 618          else if(api_is_grouptutor($_course,$session_id,api_get_user_id())){
 619          $papers[] = array($paper_icon,$title_tag,'<center>'.$paper_description.'</center>','<center>'.$author.'</center>','<center>'.$group_name.'</center>','<center>'.$date_str.'</center>','<center>'.$corrected_img.'</center>',$assignment_score);
 620          }
 621          else {
 622          $papers[] = array($paper_icon,$title_tag,$paper_description,'<center>'.$group_name.'</center>','<center>'.$corrected_img.'</center>','<center>'.$note.'</center>');
 623          }
 624          
 625      }
 626  
 627      return $papers;
 628  }
 629  
 630  /**
 631   * Update the url of a dir in the student_publication table
 632   * @param    string old path
 633   * @param    string new path
 634   */
 635  function update_dir_name($path, $new_name) {
 636  
 637      if (!empty($new_name)){
 638  
 639          global $base_work_dir;
 640          include_once(api_get_path(LIBRARY_PATH) . "/fileManage.lib.php");
 641          include_once(api_get_path(LIBRARY_PATH) . "/fileUpload.lib.php");
 642          $path_to_dir = dirname($path);
 643          if($path_to_dir=='.') {
 644              $path_to_dir = '';
 645          } else {
 646              $path_to_dir .= '/';
 647          }
 648          $new_name = Security::remove_XSS($new_name);
 649          $new_name = replace_dangerous_char($new_name);
 650          $new_name = disable_dangerous_file($new_name);
 651  
 652          my_rename($base_work_dir.'/'.$path,$new_name);
 653          $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
 654  
 655          //update all the files in the other directories according with the next query
 656          $sql = 'SELECT id, url FROM '.$table.' WHERE url LIKE BINARY "work/'.Database::escape_string($path).'/%"'; // like binary (Case Sensitive)
 657  
 658          $rs = Database::query($sql, __FILE__, __LINE__);
 659          $work_len=strlen('work/'.$path);
 660  
 661          while($work = Database :: fetch_array($rs)) {
 662              $new_dir=$work['url'];
 663              $name_with_directory=substr($new_dir,$work_len,strlen($new_dir));
 664              $sql = 'UPDATE '.$table.' SET url="work/'.$path_to_dir.$new_name.$name_with_directory.'" WHERE id= '.$work['id'];
 665              Database::query($sql, __FILE__, __LINE__);
 666          }
 667  
 668          //update all the directory's children according with the next query
 669          $sql = 'SELECT id, url FROM '.$table.' WHERE url LIKE BINARY "/'.Database::escape_string($path).'%"';
 670          $rs = Database::query($sql, __FILE__, __LINE__);
 671          $work_len=strlen('/'.$path);
 672          while($work = Database :: fetch_array($rs)) {
 673              $new_dir=$work['url'];
 674              $name_with_directory=substr($new_dir,$work_len,strlen($new_dir));
 675              $url=$path_to_dir.$new_name.$name_with_directory;
 676              $sql = 'UPDATE '.$table.' SET url="/'.$url.'" WHERE id= '.$work['id'];
 677              Database::query($sql, __FILE__, __LINE__);
 678          }
 679      }
 680  }
 681  
 682  function submit_work($cur_dir_path, $origin, $stok, $ctok, $is_course_member){
 683      echo '<script>
 684  	function updateDocumentTitle(value){
 685              var temp = value.indexOf("/");
 686              //linux path
 687              if(temp!=-1){
 688                  var temp=value.split("/");
 689              }
 690              else{
 691                  var temp=value.split("\\\");
 692              }
 693              document.getElementById("file_upload").value=temp[temp.length-1];
 694          }
 695  	function getAssignmentId(id){            
 696              document.getElementById("assignment_id").value=id;
 697      }
 698      </script>';
 699      global $_course,$_user;
 700      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
 701      $TSTDPUBASG            = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
 702  
 703      $my_cur_dir_path = $cur_dir_path;
 704      if ($my_cur_dir_path == '/') {
 705          $my_cur_dir_path = '';
 706      } elseif (substr($my_cur_dir_path, -1, 1) != '/') {
 707          $my_cur_dir_path = $my_cur_dir_path . '/';
 708      }
 709  
 710      $form = new FormValidator('submit_paper', 'post',api_get_self().'?'.api_get_cidReq().'&action=submit_work&curdripath='. rtrim(Security :: remove_XSS($cur_dir_path),'/').'&origin='.$origin.'&gradebook='.Security::remove_XSS($_GET['gradebook']),'', 'enctype="multipart/form-data"');
 711      $form->addElement('header', '', get_lang('SubmitPaper'));
 712  //    $sql = "SELECT id,title FROM $work_table WHERE filetype='folder' AND parent_id='0' AND session_id = ".api_get_session_id();
 713      $sql = "SELECT id,title FROM $work_table WHERE filetype='folder' AND parent_id='0'";
 714      $res = Database::query($sql,__FILE__,__LINE__);
 715      $assignments = array();
 716      $assignments[0] = '-- '.get_lang('Root').' --';
 717      while($obj = Database::fetch_object($res))
 718      {
 719          $assignments[$obj->id] = $obj->title;
 720      }
 721          
 722      $form->addElement('select', 'assignment', get_lang('AssignmentName'), $assignments,'onchange="getAssignmentId(this.value)"');    
 723      $form->addElement('hidden','sec_token',$stok);
 724      $form->addElement('hidden','assignment_id','','id="assignment_id"');
 725      $form->addElement('file', 'file', get_lang('PaperUpload'), 'size="40" id="papper-file" onchange="updateDocumentTitle(this.value)"');
 726  
 727          $form->addElement('text', 'title', get_lang("TitleWork"), 'id="file_upload"  style="width: 350px;"');
 728      $form->addElement('textarea', 'summary', get_lang("Summary"), 'style="width: 350px; height: 60px;"');    
 729          
 730      $form->addElement('style_submit_button', 'submit', get_lang('Ok'), 'class="save" onclick="if(document.getElementById(\'papper-file\').value == \'\'){alert(\''.get_lang('ThisFieldIsRequired').'\');return false;}"');
 731                  
 732          $folder_id = get_folder_work_id($cur_dir_path);
 733          $default['assignment'] = $folder_id?$folder_id:0;        
 734          $form->setDefaults($default);                        
 735      if($form -> validate()) {
 736          $paper = $form->exportValues();
 737          $assignment_id = $paper['assignment'];        
 738          $description = $paper['summary'];
 739          $sql = "SELECT work.url,work.qualification,work.title,work.description,workassign.ends_on FROM $work_table work,$TSTDPUBASG workassign WHERE work.id = workassign.publication_id AND work.id = ".$assignment_id;
 740          $res = Database::query($sql,__FILE__,__LINE__);
 741          while($row = Database::fetch_array($res)){
 742              $url = $row['url'];
 743              $weight = $row['qualification'];
 744              $assignment_title = $row['title'];
 745              $assignment_description = $row['description'];
 746              $deadline = $row['ends_on'];
 747          }
 748          
 749          if ($ctok==$paper['sec_token']) {            
 750              if ((!empty($_FILES['file']['size']) && !empty($is_course_member)) || api_is_platform_admin()) {                        
 751                  $updir = api_get_path(SYS_COURSE_PATH) . $_course["path"] . '/work'; //directory path to upload
 752  
 753                  // Try to add an extension to the file if it has'nt one
 754                  $new_file_name = add_ext_on_mime(stripslashes($_FILES['file']['name']), $_FILES['file']['type']);
 755  
 756                  // Replace dangerous characters
 757                  $new_file_name = replace_dangerous_char($new_file_name, 'strict');
 758  
 759                  // Transform any .php file in .phps fo security
 760                  $new_file_name = php2phps($new_file_name);
 761                  //filter extension
 762                  if (!filter_extension($new_file_name)) {
 763                      Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'), false, true);
 764                      $succeed = false;
 765                  } else {                    
 766                      $title = $_FILES['file']['name'];                    
 767                      $authors = api_get_person_name($_user['firstName'], $_user['lastName']);
 768                      
 769                      // compose a unique file name to avoid any conflict
 770                      $new_file_name = uniqid('') . $new_file_name;
 771                      if (isset ($_SESSION['toolgroup'])) {
 772                          $post_group_id = $_SESSION['toolgroup'];
 773                      } else {
 774                          $post_group_id = '0';
 775                      }
 776                      
 777                      //if we come from the group tools the groupid will be saved in $work_table
 778                      @move_uploaded_file($_FILES['file']['tmp_name'], $updir . $my_cur_dir_path .$url.'/'. $new_file_name);
 779                      $url = "work" . $my_cur_dir_path .$url.'/' . $new_file_name;
 780  
 781                      $sql_add_publication = "INSERT INTO " . $work_table . " SET " .
 782                                                 "url         = '" . $url . "',
 783                                                 title       = '" . Database::escape_string($title) . "',
 784                                                 description = '" . Database::escape_string($description) . "',
 785                                                 author      = '" . Database::escape_string($authors) . "',
 786                                                 active        = '1',
 787                                                 accepted        = '1',
 788                                                 post_group_id = '" . $post_group_id . "',
 789                                                 sent_date    =  NOW(),
 790                                                 weight       = '".$weight."',
 791                                                 parent_id     =  '".$assignment_id ."' ,
 792                                                 session_id = ".api_get_session_id();
 793                      
 794                      Database::query($sql_add_publication, __FILE__, __LINE__);
 795  
 796                      $Id = Database::insert_id();
 797                      api_item_property_update($_course, 'work', $Id, 'DocumentAdded', api_get_user_id());
 798                      $succeed = true;
 799  
 800                      // display the feedback message if the newly added documents are invisible by default
 801                      if ($uploadvisibledisabled == 0){
 802                          // we cannot used the display_xxx_message functions alone because this function depends on a setting
 803                          // api_get_setting('display_feedback_messages') if the message is shown or not. In this case we ALWAYS
 804                          // want to display the messages if the newly uploaded document is automatically invisible because
 805                          // otherwise the student is NEVER notified that the document is successfully uploaded and the  
 806                          // student uploads a second and a third time. This is by consequence a useability problem that we solve here.
 807                          // We need to check the setting to prevent double messages when the setting is set to ON
 808                          if (api_get_setting('display_feedback_messages') == 'false') {
 809                              /*echo '<div class="confirmation-message">';
 810                              echo get_lang('DocumentUploadedButInvisible');
 811                              echo '</div>';*/
 812                          } else {
 813                              //Display::display_confirmation_message(get_lang('DocumentUploadedButInvisible'));
 814                          }
 815                      }
 816  
 817                      $datetime = explode(" ", $deadline);
 818                      $dateparts = explode("-", $datetime[0]);
 819                      if(api_get_interface_language() == 'french'){
 820                      $deadline = $dateparts[2].'/'.$dateparts[1].'/'.$dateparts[0];
 821                      }
 822                      else {
 823                      $deadline = $dateparts[1].'/'.$dateparts[2].'/'.$dateparts[0];
 824                      }
 825                      $user_id = api_get_user_id();
 826                      sendmail_paper_to_tutor($authors,$Id,$user_id,$title,$assignment_title,$assignment_description,$deadline);    
 827                  }
 828              }
 829          }
 830      }
 831      if($succeed) {
 832                  $href = isset($assignment_id) && intval($assignment_id) == 0?api_get_self().'?'.api_get_cidReq():api_get_self().'?'.api_get_cidReq().'&action=view_papers&curdirpath='.$cur_dir_path.'&assignment_id='.$assignment_id;
 833          echo '<script>window.location.href = "'.$href.'"</script>';
 834      }
 835      $form->display();
 836      
 837  }
 838  
 839  function correct_paper($paper_id){
 840      global $_course;
 841      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);    
 842      
 843      $sql = "SELECT * FROM $work_table WHERE id = ".$paper_id;
 844      $result = Database::query($sql, __FILE__, __LINE__);
 845      $row = Database::fetch_array($result);
 846  
 847      $datetime = explode(" ", $row['sent_date']);
 848      $dateparts = explode("-", $datetime[0]);    
 849      if(api_get_interface_language() == 'french'){
 850      $submittedon = $dateparts[2].'-'.$dateparts[1].'-'.$dateparts[0].'&nbsp;'.$datetime[1];
 851      }
 852      else {
 853      $submittedon = $dateparts[1].'-'.$dateparts[2].'-'.$dateparts[0].'&nbsp;'.$datetime[1];
 854      }
 855      
 856      $form = new FormValidator('correct_paper', 'post',api_get_self().'?'.api_get_cidReq().'&action=correct_paper&id='.$paper_id,'', 'enctype="multipart/form-data"');
 857      $form->addElement('header', '', get_lang('CorrectPaper'));    
 858      $form->addElement('static','paper',get_lang('Paper'),' :&nbsp;&nbsp;&nbsp;<span>'.$row['title'].'</span>');
 859      $form->addElement('static','summary',get_lang('Summary'),' :&nbsp;&nbsp;&nbsp;<span>'.$row['description'].'</span>');
 860      $form->addElement('static','author',get_lang('Author'),' :&nbsp;&nbsp;&nbsp;<span>'.$row['author'].'</span>');
 861      $form->addElement('static','date',get_lang('Submittedon'),' :&nbsp;&nbsp;&nbsp;<span>'.$submittedon.'</span>');
 862  //    $form->addElement('static','corrections',get_lang('PreviousCorrection'),' :&nbsp;&nbsp;&nbsp;<span class="invisible">'.$row['correction_date'].'</span>');
 863      $form->addElement('static','download',get_lang('DownloadPaper'),' :&nbsp;&nbsp;&nbsp;<a href="download.php?file='.$row['url'].'">'.Display::return_icon('pixel.gif',get_lang('Download'),array('class' => 'actionplaceholdericon actionsavebackup')).'</a>');
 864      $form->addElement('file', 'file', get_lang('CorrectionUpload'), 'size="40"');
 865      $form->addElement('textarea', 'remark', get_lang("Remark"), 'style="width: 400px; height: 80px;"');    
 866      $option = array();
 867      for($i=0;$i<=20;$i++){
 868          $option[] = $i;
 869      }
 870      $form->addElement('select', 'score', get_lang('Score'), $option);
 871      $form->addElement('style_submit_button', 'submit', get_lang('Ok'), 'class="save"');
 872      $defaults = array();
 873      $defaults['remark'] = $row['remark'];    
 874      if($row['qualificator_id'] == 1){
 875          $defaults['score'] = $row['qualification'];    
 876      }
 877      else {
 878          $defaults['score'] = $row['weight'];    
 879      }        
 880  //    $defaults['score'] = 0;
 881      $form->setDefaults($defaults);
 882      if($form -> validate()) {        
 883          $correctpaper = $form->exportValues();
 884          if (!empty($_FILES['file']['size'])){
 885              $updir = api_get_path(SYS_COURSE_PATH) . $_course["path"]; //directory path to upload
 886              $path_parts = pathinfo('/'.$row['url']);                                
 887              $new_file_name = $path_parts['filename'].'_corr.'.$path_parts['extension'];                        
 888          /*    $correction_date = '';
 889              if(!empty($row['correction_date'])){
 890                  $correction_date = $row['correction_date'].",";
 891              }*/
 892              @move_uploaded_file($_FILES['file']['tmp_name'], $updir .'/'.$path_parts['dirname'] .'/'. $new_file_name);
 893              $sql = "UPDATE $work_table SET remark = '".$correctpaper['remark']."',
 894                                             qualification = ".$correctpaper['score'].",
 895                                             qualificator_id = 1                                           
 896                                             WHERE id = ".$paper_id;
 897              
 898              Database::query($sql, __FILE__, __LINE__);            
 899              sendmail_correctpaper_tostudent($paper_id,$row['parent_id'],$row['title'],$row['sent_date']);
 900          }
 901          elseif($row['qualificator_id'] == 1){
 902              $sql = "UPDATE $work_table SET remark = '".$correctpaper['remark']."',
 903                                             qualification = ".$correctpaper['score'].",
 904                                             qualificator_id = 1                                           
 905                                             WHERE id = ".$paper_id;
 906              
 907              Database::query($sql, __FILE__, __LINE__);            
 908              sendmail_correctpaper_tostudent($paper_id,$row['parent_id'],$row['title'],$row['sent_date']);
 909          }
 910          echo '<script>window.location.href = "'.api_get_self().'?'.api_get_cidReq().'&action=view_papers&assignment_id='.$row['parent_id'].'"</script>';
 911      }
 912      $form->display();
 913  }
 914  
 915  function view_paper($paper_id){    
 916      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
 917  
 918      $sql = "SELECT * FROM $work_table WHERE id = ".intval($paper_id);
 919      $result = Database::query($sql, __FILE__, __LINE__);
 920      $row = Database::fetch_array($result);
 921  
 922      if(strlen($row['remark']) > 400){
 923          $remark = substr($row['remark'],0,400);
 924          $remark .= '...';
 925      }
 926      else {
 927          $remark = $row['remark'];
 928      }
 929      $path_parts = pathinfo('/'.$row['url']);                                
 930      $new_file_name = $path_parts['filename'].'_corr.'.$path_parts['extension'];    
 931      $corrected_url = $path_parts['dirname'] .'/'. $new_file_name;
 932  
 933      $datetime = explode(" ", $row['sent_date']);
 934      $dateparts = explode("-", $datetime[0]);    
 935      if(api_get_interface_language() == 'french'){
 936      $submittedon = $dateparts[2].'-'.$dateparts[1].'-'.$dateparts[0].'&nbsp;'.$datetime[1];
 937      }
 938      else {
 939      $submittedon = $dateparts[1].'-'.$dateparts[2].'-'.$dateparts[0].'&nbsp;'.$datetime[1];
 940      }
 941  
 942      $download_paper = '<a href="download.php?file='.$row['url'].'">'.Display::return_icon('pixel.gif',get_lang('Download'),array('class' => 'actionplaceholdericon actionsavebackup')).'</a>';
 943      $download_corrected_paper = '<a href="download.php?file='.$corrected_url.'">'.Display::return_icon('pixel.gif',get_lang('Download'),array('class' => 'actionplaceholdericon actionsavebackup')).'</a>';
 944  
 945      echo '<table width="100%" border="0" cellpadding="5" cellspacing="5"><tr><td colspan="2"><span style="color:orange;font-weight:bold;">'.get_lang('MyPaper').'</span></td></tr>
 946      <tr><td width="30" align="right">'.get_lang('Paper').' : </td><td width="70%">'.$row['title'].'</td></tr>
 947      <tr><td width="30" align="right">'.get_lang('Summary').' : </td><td width="70%">'.$row['description'].'</td></tr>
 948      <tr><td width="30" align="right">'.get_lang('Author').' : </td><td width="70%">'.$row['author'].'</td></tr>
 949      <tr><td width="30" align="right">'.get_lang('Submittedon').' : </td><td width="70%">'.$submittedon.'</td></tr>    
 950      <tr><td width="30" align="right">'.get_lang('DownloadPaper').' : </td><td width="70%">'.$download_paper.'</td></tr>
 951      <tr><td width="30" align="right" valign="top">'.get_lang('Remark').' : </td><td width="70%"><div class="quiz_content_actions" style="width:65%;height:60px;">'.$remark.'</div></td></tr>';
 952      if($row['qualificator_id'] == 1){
 953      echo '<tr><td width="30" align="right">'.get_lang('DownloadCorrectedPaper').' : </td><td width="70%">'.$download_corrected_paper.'</td></tr>';    
 954      }
 955      echo '<tr><td colspan="2" style="padding-left:220px;"><div class="quiz_content_actions" style="width:110px;">Mark &nbsp;&nbsp;&nbsp;&nbsp;'.round($row['qualification'],2).'/'.round($row['weight'],2).'</div></td></tr></table>';
 956  
 957  }
 958  
 959  function move_paper($assignment_id, $paper_id){    
 960      global $_course;
 961      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
 962  
 963      $form = new FormValidator('move_paper', 'post',api_get_self().'?'.api_get_cidReq().'&action=move_paper&assignment_id='. intval($assignment_id).'&id='.intval($paper_id));
 964      $form->addElement('header', '', get_lang('MovePaper'));
 965  //    $sql = "SELECT id,title FROM $work_table WHERE filetype='folder' AND parent_id='0' AND id != ".$assignment_id." AND session_id = ".api_get_session_id();
 966      $sql = "SELECT id,title FROM $work_table WHERE filetype='folder' AND parent_id='0' AND id != ".intval($assignment_id);
 967      $res = Database::query($sql,__FILE__,__LINE__);
 968      $assignments = array();
 969  //    $assignments[0] = '-- '.get_lang('SelectAssignment').' --';
 970      while($obj = Database::fetch_object($res))
 971      {
 972          $assignments[$obj->id] = $obj->title;
 973      }
 974  
 975      $sql = "SELECT title FROM $work_table WHERE id = ".intval($assignment_id);
 976      $result = Database::query($sql,__FILE__,__LINE__);
 977      $row = Database::fetch_array($result);
 978  
 979      $sql_paper = "SELECT title,description,url FROM $work_table WHERE parent_id = ".intval($assignment_id)." AND id = ".intval($paper_id);
 980      $result_paper = Database::query($sql_paper,__FILE__,__LINE__);
 981      $rowpaper = Database::fetch_array($result_paper);
 982  
 983      $path_parts = pathinfo('/'.$rowpaper['url']);
 984      $exist_filename = $path_parts['filename'].'.'.$path_parts['extension'];
 985  
 986      $form->addElement('static','assignment_title',get_lang('FromAssignment'),' :&nbsp;&nbsp;&nbsp;<span>'.$row['title'].'</span>');
 987      $form->addElement('static','paper_title',get_lang('PaperTitle'),' :&nbsp;&nbsp;&nbsp;<span>'.$rowpaper['title'].'</span>');
 988      $form->addElement('static','paper_description',get_lang('Summary'),' :&nbsp;&nbsp;&nbsp;<span>'.$rowpaper['description'].'</span>');
 989      $form->addElement('select', 'assignment', get_lang('MoveToAssignment'), $assignments);
 990      $form->addElement('style_submit_button', 'submit', get_lang('Ok'), 'class="save"');
 991      if($form -> validate()) {        
 992          $movepaper = $form->exportValues();
 993          $to_assignmentid = $movepaper['assignment'];    
 994  
 995          $sql_move = "SELECT url FROM $work_table WHERE id = ".$to_assignmentid;
 996          $res_move = Database::query($sql_move,__FILE__,__LINE__);
 997          $rowmove = Database::fetch_array($res_move);
 998  
 999          $path_parts = pathinfo('/'.$rowmove['url']);    
1000          $newfolder = $path_parts['basename'];
1001  
1002          $newurl = 'work/'.$newfolder.'/'.$exist_filename;
1003  
1004          move(api_get_path(SYS_COURSE_PATH) . $_course['path']. '/' . $rowpaper['url'], api_get_path(SYS_COURSE_PATH) . $_course['path'].'/work/'.$newfolder);
1005  
1006          $sql = "UPDATE $work_table SET url = '".$newurl."', parent_id = ".$to_assignmentid." WHERE id = ".intval($paper_id);        
1007          Database::query($sql,__FILE__,__LINE__);
1008  
1009          api_item_property_update($_course, 'work', $to_assignmentid, 'FileUpdated', api_get_user_id());
1010          
1011          echo '<script>window.location.href = "'.api_get_self().'?'.api_get_cidReq().'&action=view_papers&assignment_id='.$to_assignmentid.'"</script>';
1012      }
1013      $form->display();
1014  
1015  }
1016  
1017  function delete_paper($paper_id){    
1018      global $_course;
1019      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
1020      $TSTDPUBASG            = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1021  
1022      $currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH) . $_course["path"] . "/";
1023  
1024      $sql_url = "SELECT url,parent_id FROM $work_table WHERE id = ".intval($paper_id);
1025      $res_url = Database::query($sql_url,__FILE__,__LINE__);    
1026  
1027      $sql = "DELETE FROM $work_table WHERE id = ".intval($paper_id);
1028      Database::query($sql,__FILE__,__LINE__);    
1029  
1030      if($res_url){
1031          api_item_property_update($_course, 'work', $paper_id, 'DocumentDeleted', api_get_user_id());    
1032          $rowurl = Database::fetch_array($res_url);
1033          $work = $rowurl['url'];
1034          
1035          require_once(api_get_path(LIBRARY_PATH).'/fileManage.lib.php');
1036          $extension = pathinfo($work, PATHINFO_EXTENSION);
1037          $basename_file = basename($work, '.'.$extension);        
1038          $new_dir = $work.'_DELETED_'.$delete.'.'.$extension;
1039          
1040          if (api_get_setting('permanently_remove_deleted_files') == 'true'){
1041              my_delete($currentCourseRepositorySys.'/'.$work);    
1042          } else {
1043              rename($currentCourseRepositorySys."/".$work, $currentCourseRepositorySys."/".$new_dir);
1044          }
1045      }
1046      echo '<script>window.location.href = "'.api_get_self().'?'.api_get_cidReq().'&action=view_papers&assignment_id='.$rowurl['parent_id'].'"</script>';
1047  }
1048  
1049  function delete_assignment($delete_assignment_id) {    
1050      global $_course;
1051      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
1052      $TSTDPUBASG        = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1053  
1054      $currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH) . $_course["path"] . "/";
1055  
1056      foreach ($delete_assignment_id as $index => $assignment_id) {
1057          $sql_url = "SELECT url FROM $work_table WHERE id = ".$assignment_id;
1058          $res_url = Database::query($sql_url,__FILE__,__LINE__);    
1059  
1060          $sql = "DELETE FROM $TSTDPUBASG WHERE publication_id = ".$assignment_id;
1061          Database::query($sql,__FILE__,__LINE__);
1062  
1063          $sql = "DELETE FROM $work_table WHERE id = ".$assignment_id;
1064          Database::query($sql,__FILE__,__LINE__);
1065          
1066          $sql = "DELETE FROM $work_table WHERE parent_id = ".$assignment_id;
1067          Database::query($sql,__FILE__,__LINE__);
1068  
1069          if ($res_url) {
1070              api_item_property_update($_course, 'work', $paper_id, 'FolderDeleted', api_get_user_id());    
1071              $rowurl = Database::fetch_array($res_url);
1072              $work = $rowurl['url'];        
1073              
1074              $path = $currentCourseRepositorySys."work/".basename($work)."/";
1075              $path_dir = $currentCourseRepositorySys."work/";
1076                          if (is_dir($path)) {
1077                              $d = dir($path);                        
1078                              if (api_get_setting('permanently_remove_deleted_files') == 'true'){                
1079                                      while (false !== $entry = $d->read()) {
1080                                              if ($entry == '.' || $entry == '..') continue;
1081                                              rmdirr($path.$entry);
1082                                      }
1083                              } else {
1084                                      while (false !== $entry = $d->read()) {
1085                                              if ($entry == '.' || $entry == '..' || substr($entry,0,8) == 'DELETED_') continue;
1086                                              $new_file='DELETED_'.$entry;                    
1087                                              rename($path.$entry, $path.$new_file);
1088                                      }
1089                                      $new_dir_name = 'DELETED_'.basename($work);
1090                                      rename($path_dir.basename($work), $path_dir.$new_dir_name);
1091                              }
1092                          }
1093          }
1094      }
1095      echo '<script>window.location.href = "'.api_get_self().'?'.api_get_cidReq().'"</script>';
1096  }
1097  
1098  function send_mail_to_students($new_dir,$description,$deadline){
1099      global $_course,$_user;
1100      $session_id = api_get_session_id();
1101      $user_table         = Database :: get_main_table(TABLE_MAIN_USER);
1102      $course_user_table         = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
1103      $session_table         = Database :: get_main_table(TABLE_MAIN_SESSION);
1104      $session_user_table         = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1105      $emailtemplate_table         = Database :: get_main_table(TABLE_MAIN_EMAILTEMPLATES);
1106  
1107      $sql = "SELECT content FROM $emailtemplate_table WHERE description = 'Newassignment' AND language = '".api_get_interface_language()."'";
1108      $res = Database::query($sql,__FILE__,__LINE__);
1109      $num_rows = Database::num_rows($res);
1110      if($num_rows == 0){
1111      $sql = "SELECT content FROM $emailtemplate_table WHERE description = 'Newassignment' AND language = 'english'";
1112      $res = Database::query($sql,__FILE__,__LINE__);
1113      }
1114      $row = Database::fetch_array($res);
1115      $mail_content = $row['content'];    
1116      
1117      $siteUrl = api_get_setting('InstitutionUrl');
1118      $subject = get_lang('CreatedNewAssignment');
1119  
1120      if($session_id == 0){
1121          //Mail to all students of the course and the session user of this course + trainer of the session
1122          $sql_course = "SELECT usr.user_id FROM $user_table usr, $course_user_table cusr WHERE usr.user_id = cusr.user_id AND cusr.course_code = '".api_get_course_id()."'";
1123          $res_course = Database::query($sql_course,__FILE__,__LINE__);
1124          $course_user = array();
1125          while($row_course = Database::fetch_row($res_course)){
1126              $course_user[] = $row_course[0];
1127          }
1128  
1129          $sql_session = "SELECT usr.user_id FROM $user_table usr, $session_user_table susr WHERE usr.user_id = susr.id_user AND susr.course_code = '".api_get_course_id()."'";
1130          $res_session = Database::query($sql_session,__FILE__,__LINE__);        
1131          while($row_session = Database::fetch_row($res_session)){
1132              $course_user[] = $row_session[0];
1133          }        
1134  
1135          $course_user[] = get_all_group_tutors();
1136          $users_list = array();
1137          $users_list = array_unique($course_user);        
1138  
1139          foreach($users_list as $users){            
1140              $sql_user = "SELECT email,firstname,lastname FROM $user_table WHERE user_id = ".$users;
1141              $res_user = Database::query($sql_user,__FILE__,__LINE__);
1142              $row_user = Database::fetch_array($res_user);            
1143  
1144              $recipient_name = api_get_person_name($row_user['firstname'], $row_user['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
1145              $sender_name = $_user['firstName'].' '.$_user['lastName'];
1146  
1147              $message = $mail_content;
1148              $message = str_replace("{Name}",$recipient_name,$message);
1149              $message = str_replace("{courseName}",api_get_course_id(),$message);
1150              $message = str_replace("{assignmentName}",$new_dir,$message);
1151              $message = str_replace("{assignmentDescription}",$description,$message);
1152              $message = str_replace("{assignmentDeadline}",$deadline,$message);
1153              $message = str_replace("{siteName}",$siteUrl,$message);
1154              $message = str_replace("{authorName}",$sender_name,$message);
1155              
1156              $message = str_replace('<br />',"\n\n", $message);
1157          //    echo $message.'<br/><br/>';
1158              api_mail_html($recipient_name, $row_user['email'], $subject, $message, $sender_name, $_user['email']);
1159          }
1160      }
1161      else {
1162          //Mail to session users and trainer of the session.
1163  
1164          $sql_session = "SELECT usr.user_id,session.id_coach FROM $user_table usr, $session_user_table susr, $session_table session WHERE usr.user_id = susr.id_user AND susr.id_session = session.id AND susr.course_code = '".api_get_course_id()."' AND susr.id_session = ".api_get_session_id();    
1165          $res_session = Database::query($sql_session,__FILE__,__LINE__);        
1166          while($row_session = Database::fetch_row($res_session)){
1167              $session_user[] = $row_session[0];
1168              $session_user[] = $row_session[1];
1169          }
1170          
1171          $session_user[] = get_all_group_tutors();
1172          $users_list = array();
1173          $users_list = array_unique($session_user);    
1174  
1175          foreach($users_list as $users){
1176              $sql_user = "SELECT email,firstname,lastname FROM $user_table WHERE user_id = ".$users;
1177              $res_user = Database::query($sql_user,__FILE__,__LINE__);
1178              $row_user = Database::fetch_array($res_user);            
1179  
1180              $recipient_name = api_get_person_name($row_user['firstname'], $row_user['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
1181              $sender_name = $_user['firstName'].' '.$_user['lastName'];
1182  
1183              $message = $mail_content;
1184              $message = str_replace("{Name}",$recipient_name,$message);
1185              $message = str_replace("{courseName}",api_get_course_id(),$message);
1186              $message = str_replace("{assignmentName}",$new_dir,$message);
1187              $message = str_replace("{assignmentDescription}",$description,$message);
1188              $message = str_replace("{assignmentDeadline}",$deadline,$message);
1189              $message = str_replace("{siteName}",$siteUrl,$message);
1190              $message = str_replace("{authorName}",$sender_name,$message);
1191  
1192              $message = str_replace('<br />',"\n\n", $message);
1193          //    echo $message.'<br/><br/>';
1194              api_mail_html($recipient_name, $row_user['email'], $subject, $message, $sender_name, $_user['email']);
1195          }
1196      }
1197  
1198  }
1199  
1200  function sendmail_paper_to_tutor($author,$paper_id,$user_id,$title,$assignment_title,$assignment_description,$deadline){    
1201      $emailtemplate_table         = Database :: get_main_table(TABLE_MAIN_EMAILTEMPLATES);
1202      $session_table         = Database :: get_main_table(TABLE_MAIN_SESSION);
1203      $table_group     = Database :: get_course_table(TABLE_GROUP);
1204      $table_group_tutor     = Database :: get_course_table(TABLE_GROUP_TUTOR);
1205      $table_group_user     = Database :: get_course_table(TABLE_GROUP_USER);
1206      $user_table         = Database :: get_main_table(TABLE_MAIN_USER);
1207  
1208      $session_id = api_get_session_id();
1209      $sql = "SELECT content FROM $emailtemplate_table WHERE description = 'Submitwork' AND language = '".api_get_interface_language()."'";
1210      $res = Database::query($sql,__FILE__,__LINE__);
1211      $num_rows = Database::num_rows($res);
1212      if($num_rows == 0){
1213      $sql = "SELECT content FROM $emailtemplate_table WHERE description = 'Submitwork' AND language = 'english'";
1214      $res = Database::query($sql,__FILE__,__LINE__);
1215      }
1216      $row = Database::fetch_array($res);
1217      $mail_content = $row['content'];    
1218      
1219      $siteUrl = api_get_setting('InstitutionUrl');
1220      $subject = get_lang('NewPaperSubmitted');
1221      $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
1222      
1223      //Send mail to trainer of the course.
1224      $sql = "SELECT grt.user_id AS tutor_id FROM $table_group gp,$table_group_user gru, $table_group_tutor grt where gp.id = gru.group_id and gp.id = grt.group_id and gru.group_id = grt.group_id and gru.user_id = ".intval($user_id)." and gp.session_id = ".intval($session_id);
1225      $rs = Database :: query($sql,__FILE__,__LINE__);
1226      while($row = Database::fetch_array($rs)){
1227          $sql_user = "SELECT email,firstname,lastname FROM $user_table WHERE user_id = ".$row['tutor_id'];
1228          $res_user = Database::query($sql_user,__FILE__,__LINE__);
1229          $row_user = Database::fetch_array($res_user);    
1230  
1231          $recipient_name = api_get_person_name($row_user['firstname'], $row_user['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);        
1232          
1233          if(api_get_interface_language() == 'french'){
1234          $sent_date = date("d/m/y");
1235          }
1236          else {
1237          $sent_date = date("m/d/y");
1238          }
1239  
1240          $message = $mail_content;            
1241          $message = str_replace("{authorName}",$recipient_name,$message);
1242          $message = str_replace("{studentName}",$author,$message);
1243          $message = str_replace("{paperName}",$title,$message);
1244          $message = str_replace("{assignmentName}",$assignment_title,$message);
1245          $message = str_replace("{assignmentDescription}",$assignment_description,$message);
1246          $message = str_replace("{courseName}",api_get_course_id(),$message);
1247          $message = str_replace("{assignmentDeadline}",$deadline,$message);
1248          $message = str_replace("{assignmentSentDate}",$sent_date,$message);
1249          $message = str_replace("{siteName}",$siteUrl,$message);
1250          $message = str_replace("{administratorSurname}",$sender_name,$message);    
1251  
1252          $message = str_replace('<br />',"\n\n", $message);
1253      //    echo $message.'<br/><br/>';
1254          api_mail_html($recipient_name, $row_user['email'], $subject, $message, $sender_name, api_get_setting('emailAdministrator'));
1255      }
1256      
1257  }
1258  
1259  function sendmail_correctpaper_tostudent($paper_id,$parent_id,$paper_title,$sent_date){    
1260      global $_user;
1261      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
1262      $TSTDPUBASG            = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1263      $itemproperty_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
1264      $emailtemplate_table         = Database :: get_main_table(TABLE_MAIN_EMAILTEMPLATES);
1265  
1266      $sql = "SELECT content FROM $emailtemplate_table WHERE description = 'Correctwork' AND language = '".api_get_interface_language()."'";
1267      $res = Database::query($sql,__FILE__,__LINE__);
1268      $num_rows = Database::num_rows($res);
1269      if($num_rows == 0){
1270      $sql = "SELECT content FROM $emailtemplate_table WHERE description = 'Correctwork' AND language = 'english'";
1271      $res = Database::query($sql,__FILE__,__LINE__);
1272      }
1273      $row = Database::fetch_array($res);
1274      $message = $row['content'];
1275      
1276      $siteUrl = api_get_setting('InstitutionUrl');
1277      $subject = get_lang('AssignmentCorrected');
1278  
1279      $sql_user = "SELECT ip.insert_user_id FROM $work_table work,$itemproperty_table ip WHERE work.id = ip.ref AND ip.tool = 'work' AND work.id = ".intval($paper_id);
1280      $res_user = Database::query($sql_user,__FILE__,__LINE__);
1281      $row_user = Database::fetch_row($res_user);
1282  
1283      $sql_work = "SELECT work.title,work.description,workassign.ends_on,ip.insert_user_id FROM $work_table work, $TSTDPUBASG workassign, $itemproperty_table ip WHERE work.id = workassign.publication_id AND work.id = ip.ref AND ip.tool = 'work' AND work.id = ".intval($parent_id);
1284      $res_work = Database::query($sql_work,__FILE__,__LINE__);
1285      $row_work = Database::fetch_row($res_work);
1286      $deadline = $row_work[2];
1287      $datetime = explode(" ", $deadline);
1288      $dateparts = explode("-", $datetime[0]);    
1289      if(api_get_interface_language() == 'french'){
1290      $deadline = $dateparts[2].'/'.$dateparts[1].'/'.$dateparts[0];
1291      }
1292      else {
1293      $deadline = $dateparts[1].'/'.$dateparts[2].'/'.$dateparts[0];
1294      }
1295  
1296      $user_info = Database::get_user_info_from_id($row_user[0]);
1297      $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
1298      $sender_name = $_user['firstname'].' '.$_user['lastname'];
1299  
1300      $datetime = explode(" ", $sent_date);
1301      $dateparts = explode("-", $datetime[0]);        
1302      $sent_date = $dateparts[1].'/'.$dateparts[2].'/'.$dateparts[0];
1303      
1304      $message = str_replace("{studentName}",$recipient_name,$message);
1305      $message = str_replace("{paperName}",$paper_title,$message);    
1306      $message = str_replace("{assignmentName}",$row_work[0],$message);
1307      $message = str_replace("{assignmentDescription}",$row_work[1],$message);
1308      $message = str_replace("{courseName}",api_get_course_id(),$message);
1309      $message = str_replace("{assignmentDeadline}",$deadline,$message);
1310      $message = str_replace("{assignmentSentDate}",$sent_date,$message);
1311      $message = str_replace("{siteName}",$siteUrl,$message);
1312      $message = str_replace("{authorName}",$sender_name,$message);    
1313  
1314      $message = str_replace('<br />',"\n\n", $message);
1315  //    echo $message.'<br/><br/>';
1316      api_mail_html($recipient_name, $user_info['email'], $subject, $message, $sender_name, $_user['email']);
1317      
1318  }
1319  
1320  function get_grouptutor_users($tutor_id){
1321      $table_group_tutor     = Database :: get_course_table(TABLE_GROUP_TUTOR);
1322  
1323      $sql = "SELECT group_id FROM $table_group_tutor WHERE user_id = ".intval($tutor_id);
1324      $res = Database::query($sql,__FILE__,__LINE__);
1325      $groups = array();
1326      while($row = Database::fetch_array($res)){
1327          $groups[] = $row['group_id'];
1328      }
1329      
1330      foreach($groups as $group_id){
1331          $users = array();
1332          $users = GroupManager :: get_subscribed_users($group_id);
1333          foreach($users as $user){
1334              $userids[] = $user['user_id'];        
1335          }
1336      }
1337      $userids[] = api_get_user_id();
1338      $users_list = implode(",",$userids);
1339      
1340      return $users_list;
1341  }
1342  
1343  function get_all_group_tutors(){
1344      global $_course;
1345      $tbl_group = Database::get_course_table(TABLE_GROUP, $_course['dbName']);
1346      $tbl_group_tutor = Database::get_course_table(TABLE_GROUP_TUTOR, $_course['dbName']);    
1347      $tutors = array();
1348      $sql_tutor = "SELECT DISTINCT(grt.user_id) FROM $tbl_group gp, $tbl_group_tutor grt WHERE gp.id = grt.group_id AND  gp.session_id = ".api_get_session_id();
1349      $rs_tutor = Database::query($sql_tutor,__FILE__,__LINE__);
1350      while($row_tutor = Database::fetch_row($rs_tutor)){
1351              $tutors[] = $row_tutor[0];
1352      }
1353      return $tutors;
1354  }
1355  
1356  function get_group_name($paper_id){
1357      $work_table         = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
1358      $itemproperty_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
1359      $table_group =    Database::get_course_table(TABLE_GROUP);    
1360      $table_group_user =    Database::get_course_table(TABLE_GROUP_USER);
1361  
1362      $sql = "SELECT ip.insert_user_id AS user_id FROM $itemproperty_table ip, $work_table work WHERE work.id = ip.ref AND work.id =".intval($paper_id)." AND ip.tool = 'work'";
1363      $rs = Database::query($sql,__FILE__,__LINE__);
1364      $row = Database::fetch_array($rs);
1365  
1366      $sql = "SELECT name FROM $table_group gp, $table_group_user gru WHERE gp.id = gru.group_id AND gru.user_id = ".$row['user_id'];
1367      $result = Database::query($sql,__FILE__,__LINE__);
1368      $row_group = Database::fetch_array($result);
1369  
1370      return $row_group['name'];
1371  }
1372  
1373  function get_user_grouptutor($user_id){
1374      $table_group_user     = Database :: get_course_table(TABLE_GROUP_USER);
1375      $table_group_tutor     = Database :: get_course_table(TABLE_GROUP_TUTOR);
1376  
1377      $sql = "SELECT group_id FROM $table_group_user WHERE user_id = ".intval($user_id);
1378      $res = Database::query($sql,__FILE__,__LINE__);
1379      while($row = Database::fetch_array($res)){
1380          $group_id = $row['group_id'];
1381      }
1382      $tutors = get_group_tutorslist($group_id);
1383      
1384      $tutors[] = api_get_user_id();
1385      $tutors_list = implode(",",$tutors);
1386      
1387      return $tutors_list;
1388  }
1389  
1390  function get_group_tutorslist ($group_id) {
1391          $table_user = Database :: get_main_table(TABLE_MAIN_USER);
1392          $table_group_tutor = Database :: get_course_table(TABLE_GROUP_TUTOR);        
1393          //$group_id = Database::escape_string($group_id);
1394          $sql = "SELECT `ug`.`id`, `u`.`user_id`
1395              FROM ".$table_user." u, ".$table_group_tutor." ug
1396              WHERE `ug`.`group_id`='".intval($group_id)."'
1397              AND `ug`.`user_id`=`u`.`user_id`";
1398          $db_result = Database::query($sql,__FILE__,__LINE__);
1399          $tutors = array ();
1400          while ($user = Database::fetch_object($db_result))
1401          {            
1402              $tutors[] = $user->user_id;
1403          }
1404          return $tutors;
1405  }
1406  
1407  /**
1408   * Builds the form thats enables the user to
1409   * move a document from one directory to another
1410   * This function has been copied from the document/document.inc.php library
1411   *
1412   * @param array $folders
1413   * @param string $curdirpath
1414   * @param string $move_file
1415   * @return string html form
1416   */
1417  function build_work_move_to_selector($folders,$curdirpath,$move_file,$group_dir='')
1418  {
1419      //gets file title
1420      $tbl_work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1421      $sql = "SELECT title FROM $tbl_work WHERE id ='".(int)$move_file."'";
1422      $result = Database::query($sql,__FILE__,__LINE__);
1423      $title = Database::fetch_row($result);
1424      global $gradebook;
1425  
1426      $form = '<form class="outer_form" name="move_to" action="'.api_get_self().'?action=move_to&gradebook='.$gradebook.'" method="POST">'."\n";
1427      $form .= '<div class="row"><div class="form_header">'.get_lang('MoveFile').'</div></div>';
1428      $form .= '<input type="hidden" name="move_file" value="'.$move_file.'" />'."\n";
1429          
1430      $form .= '<div class="row">
1431                                  <table><tr><td>
1432                      <span class="form_required">*</span>'.sprintf(get_lang('MoveXTo'),$title[0]).'
1433                                  </td><td>';
1434      $form .= ' <select name="move_to">'."\n";
1435  
1436      //group documents cannot be uploaded in the root
1437      if($group_dir=='') {
1438          if($curdirpath!='/') {
1439              $form .= '<option value="/">/ ('.get_lang('Root').')</option>';
1440          }
1441          if (is_array($folders)) {
1442              foreach ($folders as $folder) {
1443                  //you cannot move a file to:
1444                  //1. current directory
1445                  //2. inside the folder you want to move
1446                  //3. inside a subfolder of the folder you want to move
1447                  if(($curdirpath!=$folder) && ($folder!=$move_file) && (substr($folder,0,strlen($move_file)+1) != $move_file.'/')) {
1448                      $form .= '<option value="'.$folder.'">'.$folder.'</option>'."\n";
1449                  }
1450              }
1451          }
1452      } else {
1453          if ($curdirpath!='/') {
1454              $form .= '<option value="/">/ ('.get_lang('Root').')</option>';
1455          }
1456          foreach ($folders as $folder) {
1457              if (($curdirpath!=$folder) && ($folder!=$move_file) && (substr($folder,0,strlen($move_file)+1) != $move_file.'/')) {
1458                  //cannot copy dir into his own subdir
1459                  $display_folder = substr($folder,strlen($group_dir));
1460                  $display_folder = ($display_folder == '')?'/ ('.get_lang('Root').')':$display_folder;
1461                  $form .= '<option value="'.$folder.'">'.$display_folder.'</option>'."\n";
1462              }
1463          }
1464      }
1465  
1466      $form .= '</select>'."\n";
1467      $form .= '    </td>
1468              <td>';
1469      $form .= '
1470  
1471                          <button type="submit" class="save" name="move_file_submit">'.get_lang('MoveFile').'</button>
1472                  </td></tr></table></div>';
1473      $form .= '</form>';
1474      $form .= '<div style="clear: both; margin-bottom: 10px;"></div>';
1475  
1476      return $form;
1477  }
1478  
1479  /**
1480   * Get the path of a document in the student_publication table (path relative to the course directory)
1481   * @param    integer    Element ID
1482   * @return    string    Path (or -1 on error)
1483   */
1484  function get_work_path($id)
1485  {
1486      $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1487      $sql = "SELECT * FROM $table WHERE id=".intval($id);
1488      $res = Database::query($sql);
1489      if(Database::num_rows($res)!=1) {
1490          return -1;
1491      } else {
1492          $row = Database::fetch_array($res);
1493          return $row['url'];
1494      }
1495  }
1496  
1497  /**
1498   * Update the url of a work in the student_publication table
1499   * @param    integer    ID of the work to update
1500   * @param    string    Destination directory where the work has been moved (must end with a '/')
1501   * @return    -1 on error, sql query result on success
1502   */
1503  function update_work_url($id,$new_path)
1504  {
1505      if(empty($id)) return -1;
1506      $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1507      $sql = "SELECT * FROM $table WHERE id=".intval($id);
1508      $res = Database::query($sql);
1509      if(Database::num_rows($res)!=1) {
1510          return -1;
1511      } else {
1512          $row = Database::fetch_array($res);
1513          $filename = basename($row['url']);
1514          $new_url = $new_path.$filename;
1515          $sql2 = "UPDATE $table SET url = '$new_url' WHERE id=".intval($id);
1516          $res2 = Database::query($sql2);
1517          return $res2;
1518      }
1519  }
1520  
1521  /**
1522   * Return an array with all the folder's ids that are in the given path
1523   * @param    string Path of the directory
1524   * @return    array The list of ids of all the directories in the path
1525   * @author     Julio Montoya Dokeos
1526   * @version April 2008
1527   */
1528  
1529  function get_parent_directories($my_cur_dir_path) {
1530      $list_id = array();
1531      if (!empty($my_cur_dir_path)) {
1532              $list_parents = explode('/', $my_cur_dir_path);
1533              $dir_acum = '';
1534              global $work_table;
1535              for ($i = 0; $i < count($list_parents) - 1; $i++) {
1536                      $item = Database::escape_string($list_parents[$i]);
1537                      $where_sentence = "url  LIKE BINARY '" . $dir_acum . "/" . $item."'";
1538                      $dir_acum .= '/' . $list_parents[$i];
1539                      $sql = "SELECT id FROM ". $work_table . " WHERE ". $where_sentence;
1540                      $result = Database::query($sql, __FILE__, __LINE__);
1541                      $row= Database::fetch_array($result);
1542                      $list_id[]=$row['id'];
1543              }
1544      }
1545      return $list_id;
1546  }
1547  
1548  /**
1549   * 
1550   */
1551  function move_form($paper_id) {
1552      $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
1553      $folders = array();
1554      $sql = "SELECT url FROM $work_table  WHERE url LIKE '/%' AND post_group_id = '".(empty($_SESSION['toolgroup'])?0:intval($_SESSION['toolgroup']))."'";
1555      $res = Database::query($sql,__FILE__,__LINE__);
1556      while($folder = Database::fetch_array($res)) {
1557          $folders[] = substr($folder['url'],1,(strlen($folder['url'])-1));
1558      }
1559      echo build_work_move_to_selector($folders, '', $paper_id);
1560  }
1561  
1562  /**
1563   * 
1564   */
1565  function move_to($move_file, $moveurl_to) {
1566      global $_course, $base_work_dir;
1567      $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
1568      $move_to = $moveurl_to;
1569      if ($move_to == '/' or empty ($move_to)) { $move_to = ''; } 
1570      elseif (substr($move_to, -1, 1) != '/') { $move_to = $move_to . '/'; }
1571      //security fix: make sure they can't move files that are not in the document table
1572      if ($path = get_work_path($move_file)) {
1573          if (move(api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/' . $path, $base_work_dir . '/' . $move_to)) {
1574              //update db
1575              update_work_url(Security::remove_XSS($move_file), 'work/' . $move_to);
1576              //set the current path
1577              $cur_dir_path = $move_to;
1578              $cur_dir_path_url = urlencode($move_to);
1579              // update all the parents in the table item propery
1580              $list_id=get_parent_directories($cur_dir_path);
1581              for ($i = 0; $i < count($list_id); $i++) {
1582                  api_item_property_update($_course, 'work', $list_id[$i], 'FolderUpdated', api_get_user_id());
1583              }
1584              // update parent_id
1585              $rs_parent = Database::query("SELECT id FROM $work_table WHERE url = '/".Database::escape_string($moveurl_to)."'");
1586              if (Database::num_rows($rs_parent) > 0) {
1587                  $row_parent = Database::fetch_row($rs_parent);
1588                  $parent_id = $row_parent[0];
1589                  Database::query("UPDATE $work_table SET parent_id = $parent_id WHERE id = '".intval($move_file)."'");
1590              }                                                
1591              Display :: display_confirmation_message(get_lang('DirMv'), true, true);
1592          } else {
1593              Display :: display_error_message(get_lang('Impossible'), true, true);
1594          }
1595      } else {
1596              Display :: display_error_message(get_lang('Impossible'), true, true);
1597      }      
1598  }
1599  
1600  /**
1601   * Gets the id of a student publication with a given path
1602   * @param string $path
1603   * @return The id if is found / false if not found
1604   */
1605  function get_folder_work_id($path) {
1606      $TBL_STUDENT_PUBLICATION = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);        
1607      $rs = Database::query("SELECT id FROM $TBL_STUDENT_PUBLICATION WHERE url LIKE '/".Database::escape_string($path)."%' AND filetype='folder'");
1608      if (Database::num_rows($rs) > 0) {
1609                  $row = Database::fetch_row($rs);
1610          return $row[0];
1611      } else {
1612          return false;
1613      }
1614  }

title

Description

title

Description

title

Description

title

title

Body