Dokeos PHP Cross Reference Learning Management Systems

Source: /main/mindmap/dropbox_functions.inc.php - 1654 lines - 55180 bytes - Summary - Text - Print

Description: This file contains additional dropbox functions. Initially there were some functions in the init files also but I have moved them over to one file         -- Patrick Cool <patrick.cool@UGent.be>, Ghent University

   1  <?php //$id: $
   2  /* For licensing terms, see /dokeos_license.txt */
   3  /**
   4  * This file contains additional dropbox functions. Initially there were some
   5  * functions in the init files also but I have moved them over
   6  * to one file         -- Patrick Cool <patrick.cool@UGent.be>, Ghent University
   7  */
   8  /**
   9  * This function is a wrapper function for the multiple actions feature.
  10  * @return    Mixed    If there is a problem, return a string message, otherwise nothing
  11  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  12  * @version march 2006
  13  */
  14  function handle_multiple_actions()
  15  {
  16      global $_user, $is_courseAdmin, $is_courseTutor;
  17  
  18      // STEP 1: are we performing the actions on the received or on the sent files?
  19      if($_POST['action']=='delete_received' || $_POST['action']=='download_received')
  20      {
  21          $part = 'received';
  22      }
  23      elseif($_POST['action']=='delete_sent' || $_POST['action']=='download_sent')
  24      {
  25          $part = 'sent';
  26      }
  27  
  28      // STEP 2: at least one file has to be selected. If not we return an error message
  29      foreach ($_POST as $key=>$value)
  30      {
  31          if (strstr($value,$part.'_') AND $key!='view_received_category' AND $key!='view_sent_category')
  32          {
  33              $checked_files=true;
  34              $checked_file_ids[]=intval(substr($value,strrpos($value,'_')));
  35          }
  36      }
  37      $checked_file_ids = $_POST['id'];
  38  
  39      if (!is_array($checked_file_ids) || count($checked_file_ids)==0)
  40      {
  41          return get_lang('CheckAtLeastOneFile');
  42      }
  43  
  44  
  45      // STEP 3A: deleting
  46      if ($_POST['action']=='delete_received' || $_POST['action']=='delete_sent')
  47      {
  48          $dropboxfile=new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
  49          foreach ($checked_file_ids as $key=>$value)
  50          {
  51              if ($_GET['view']=='received')
  52              {
  53                  $dropboxfile->deleteReceivedWork($value);
  54                  $message=get_lang('ReceivedFileDeleted');
  55              }
  56              if ($_GET['view']=='sent' OR empty($_GET['view']))
  57              {
  58                  $dropboxfile->deleteSentWork($value);
  59                  $message=get_lang('SentFileDeleted');
  60              }
  61          }
  62          return $message;
  63      }
  64  
  65      // STEP 3B: giving comment
  66      if ($_POST['actions']=='comment')
  67      {
  68          // This has not been implemented.
  69          // The idea was that it would be possible to write the same feedback for the selected documents.
  70      }
  71  
  72      // STEP 3C: moving
  73      if (strstr($_POST['action'], 'move_'))
  74      {
  75              // check move_received_n or move_sent_n command
  76          if (strstr($_POST['action'],'received')){
  77                      $part = 'received';
  78                      $to_cat_id = str_replace('move_received_','',$_POST['action']);
  79              }
  80              else {
  81                      $part = 'sent';
  82                      $to_cat_id = str_replace('move_sent_','',$_POST['action']);
  83              }
  84  
  85          foreach ($checked_file_ids as $key=>$value)
  86          {
  87              store_move($value, $to_cat_id, $part);
  88          }
  89          return get_lang('FilesMoved');
  90      }
  91  
  92      // STEP 3D: downloading
  93      if ($_POST['action']=='download_sent' || $_POST['action']=='download_received')
  94      {
  95          zip_download($checked_file_ids);
  96      }
  97  
  98  }
  99  
 100  /**
 101  * This function deletes a dropbox category
 102  *
 103  * @todo give the user the possibility what needs to be done with the files in this category: move them to the root, download them as a zip, delete them
 104  *
 105  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 106  * @version march 2006
 107  */
 108  function delete_category($action, $id)
 109  {
 110      global $dropbox_cnf;
 111      global $_user, $is_courseAdmin, $is_courseTutor;
 112  
 113      // an additional check that might not be necessary
 114      if ($action=='deletereceivedcategory')
 115      {
 116          $sentreceived='received';
 117          $entries_table=$dropbox_cnf['tbl_post'];
 118          $id_field='file_id';
 119          $return_message = get_lang('ReceivedCatgoryDeleted');
 120      }
 121      elseif ($action=='deletesentcategory')
 122      {
 123          $sentreceived='sent';
 124          $entries_table=$dropbox_cnf['tbl_file'];
 125          $id_field='id';
 126          $return_message = get_lang('SentCatgoryDeleted');
 127      }
 128      else
 129      {
 130          return get_lang('Error');
 131      }
 132  
 133      // step 1: delete the category
 134      $sql="DELETE FROM ".$dropbox_cnf['tbl_category']." WHERE cat_id='".Database::escape_string($id)."' AND $sentreceived='1'";
 135      $result=Database::query($sql,__FILE__,__LINE__);
 136  
 137      // step 2: delete all the documents in this category
 138      $sql="SELECT * FROM ".$entries_table." WHERE cat_id='".Database::escape_string($id)."'";
 139      $result=Database::query($sql,__FILE__,__LINE__);
 140  
 141      while ($row=Database::fetch_array($result))
 142      {
 143          $dropboxfile=new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
 144          if ($action=='deletereceivedcategory')
 145          {
 146              $dropboxfile->deleteReceivedWork($row[$id_field]);
 147          }
 148          if ($action=='deletesentcategory')
 149          {
 150              $dropboxfile->deleteSentWork($row[$id_field]);
 151          }
 152      }
 153      return $return_message;
 154  }
 155  
 156  /**
 157  * Displays the form to move one individual file to a category
 158  *
 159  * @return html code of the form that appears in a dokeos message box.
 160  *
 161  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 162  * @version march 2006
 163  */
 164  function display_move_form($part, $id, $target=array())
 165  {
 166      echo '<div class="row"><div class="form_header">'.get_lang('MoveFileTo').'</div></div>';
 167      echo '<form name="form1" method="post" action="'.api_get_self().'?view_received_category='.$_GET['view_received_category'].'&view_sent_category='.$_GET['view_sent_category'].'&view='.$_GET['view'].'">';
 168      echo '<input type="hidden" name="id" value="'.Security::remove_XSS($id).'">';
 169      echo '<input type="hidden" name="part" value="'.Security::remove_XSS($part).'">';
 170      echo '
 171              <div class="row">
 172                  <div class="label">
 173                      <span class="form_required">*</span> '.get_lang('MoveFileTo').'
 174                  </div>
 175                  <div class="formw">';
 176      echo '<select name="move_target">';
 177      echo '<option value="0">'.get_lang('Root').'</option>';
 178      foreach ($target as $key=>$category)
 179      {
 180          echo '<option value="'.$category['cat_id'].'">'.$category['cat_name'].'</option>';
 181      }
 182      echo  '</select>';
 183      echo '    </div>
 184              </div>';
 185  
 186      echo '
 187          <div class="row">
 188              <div class="label">
 189              </div>
 190              <div class="formw">
 191                  <button class="next" type="submit" name="do_move" value="'.get_lang('Ok').'">'.get_lang('MoveFile').'</button>
 192              </div>
 193          </div>
 194      ';
 195      echo '</form>';
 196  
 197      echo '<div style="clear: both;"></div>';
 198  }
 199  
 200  /**
 201  * This function moves a file to a different category
 202  *
 203  * @param $id the id of the file we are moving
 204  * @param $target the id of the folder we are moving to
 205  * @param $part are we moving a received file or a sent file?
 206  *
 207  * @return language string
 208  *
 209  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 210  * @version march 2006
 211  */
 212  function store_move($id, $target, $part)
 213  {
 214      global $_user;
 215      global $dropbox_cnf;
 216  
 217      if ((isset($id) AND $id<>'') AND (isset($target) AND $target<>'') AND (isset($part) AND $part<>''))
 218      {
 219          if ($part=='received')
 220          {
 221              $sql="UPDATE ".$dropbox_cnf["tbl_post"]." SET cat_id='".Database::escape_string($target)."'
 222                          WHERE dest_user_id='".Database::escape_string($_user['user_id'])."'
 223                          AND file_id='".Database::escape_string($id)."'
 224                          ";
 225              Database::query($sql,__FILE__,__LINE__);
 226              $return_message=get_lang('ReceivedFileMoved');
 227          }
 228          if ($part=='sent')
 229          {
 230              $sql="UPDATE ".$dropbox_cnf["tbl_file"]." SET cat_id='".Database::escape_string($target)."'
 231                          WHERE uploader_id='".Database::escape_string($_user['user_id'])."'
 232                          AND id='".Database::escape_string($id)."'
 233                          ";
 234              Database::query($sql,__FILE__,__LINE__);
 235              $return_message=get_lang('SentFileMoved');
 236          }
 237      }
 238      else
 239      {
 240          $return_message=get_lang('NotMovedError');
 241      }
 242      return $return_message;
 243  }
 244  
 245  /**
 246  * This functions displays all teh possible actions that can be performed on multiple files. This is the dropdown list that
 247  * appears below the sortable table of the sent / or received files.
 248  *
 249  * @return html value for the dropdown list
 250  *
 251  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 252  * @version march 2006
 253  */
 254  function display_action_options($part, $categories, $current_category=0)
 255  {
 256      echo '<select name="actions">';
 257      echo '<option value="download">'.get_lang('Download').'</option>';
 258      echo '<option value="delete">'.get_lang('Delete').'</option>';
 259      if(is_array($categories))
 260      {
 261          echo '<optgroup label="'.get_lang('MoveTo').'">';
 262          if ($current_category<>0)
 263          {
 264              echo '<option value="move_0">'.get_lang('Root').'</a>';
 265          }
 266          foreach ($categories as $key=>$value)
 267          {
 268              if( $current_category<>$value['cat_id'])
 269              {
 270                  echo '<option value="move_'.$value['cat_id'].'">'.$value['cat_name'].'</option>';
 271              }
 272          }
 273          echo '</optgroup>';
 274      }
 275      echo '</select>';
 276      echo '<input type="submit" name="do_actions_'.Security::remove_XSS($part).'" value="'.get_lang('Ok').'" />';
 277  }
 278  
 279  /**
 280  * this function returns the html code that displays the checkboxes next to the files so that
 281  * multiple actions on one file are possible.
 282  *
 283  * @param $id the unique id of the file
 284  * @param $part are we dealing with a sent or with a received file?
 285  *
 286  * @return html code
 287  *
 288  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 289  * @version march 2006
 290  */
 291  function display_file_checkbox($id, $part)
 292  {
 293      if (isset($_GET['selectall']))
 294      {
 295          $checked='checked';
 296      }
 297      $return_value='<input type="checkbox" name="'.Security::remove_XSS($part).'_'.Security::remove_XSS($id).'" value="'.Security::remove_XSS($id).'" '.$checked.' />';
 298      return $return_value;
 299  }
 300  
 301  
 302  /**
 303  * This function retrieves all the dropbox categories and returns them as an array
 304  *
 305  * @param $filter default '', when we need only the categories of the sent or the received part.
 306  *
 307  * @return array
 308  *
 309  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 310  * @version march 2006
 311  */
 312  function get_dropbox_categories($filter='')
 313  {
 314      global $_user;
 315      global $dropbox_cnf;
 316  
 317      $return_array=array();
 318      
 319      $session_id = api_get_session_id();
 320      $condition_session = api_get_session_condition($session_id);
 321          
 322      $sql="SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE user_id='".$_user['user_id']."' $condition_session";
 323  
 324      $result=Database::query($sql,__FILE__,__LINE__);
 325      while ($row=Database::fetch_array($result))
 326      {
 327          if(($filter=='sent' AND $row['sent']==1) OR ($filter=='received' AND $row['received']==1) OR $filter=='')
 328          {
 329              $return_array[$row['cat_id']]=$row;
 330          }
 331      }
 332  
 333      return $return_array;
 334  }
 335  
 336  /**
 337  * This functions stores a new dropboxcategory
 338  *
 339  * @var     it might not seem very elegant if you create a category in sent and in received with the same name that you get two entries in the
 340  *        dropbox_category table but it is the easiest solution. You get
 341  *        cat_name | received | sent | user_id
 342  *        test     |      1        |    0  |    237
 343  *        test     |      0        |    1  |    237
 344  *        more elegant would be
 345  *        test     |      1        |    1  |    237
 346  *
 347  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 348  * @version march 2006
 349  */
 350  function store_addcategory()
 351  {
 352      global $_user;
 353      global $dropbox_cnf;
 354  
 355      // check if the target is valid
 356      if ($_POST['target']=='sent')
 357      {
 358          $sent=1;
 359          $received=0;
 360      }
 361      elseif ($_POST['target']=='received')
 362      {
 363          $sent=0;
 364          $received=1;
 365      }
 366      else
 367      {
 368          return get_lang('Error');
 369      }
 370  
 371      // check if the category name is valid
 372      if ($_POST['category_name']=='')
 373      {
 374          return array('type' => 'error', 'message'=>get_lang('ErrorPleaseGiveCategoryName'));
 375      }
 376  
 377      if (!$_POST['edit_id'])
 378      {
 379          $session_id = api_get_session_id();
 380          // step 3a, we check if the category doesn't already exist
 381          $sql="SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE user_id='".$_user['user_id']."' AND cat_name='".Database::escape_string(Security::remove_XSS($_POST['category_name']))."' AND received='".$received."' AND sent='$sent' AND session_id='$session_id'";
 382          $result=Database::query($sql,__FILE__,__LINE__);
 383  
 384  
 385          // step 3b, we add the category if it does not exist yet.
 386          if (Database::num_rows($result)==0)
 387          {
 388              $sql="INSERT INTO ".$dropbox_cnf['tbl_category']." (cat_name, received, sent, user_id, session_id)
 389                      VALUES ('".Database::escape_string(Security::remove_XSS($_POST['category_name']))."', '".Database::escape_string($received)."', '".Database::escape_string($sent)."', '".Database::escape_string($_user['user_id'])."',$session_id)";
 390              Database::query($sql,__FILE__,__LINE__);
 391              
 392              global $_course,$_user;
 393              $to_group_id = 0;
 394              $to_user_id = 0;
 395              $course_name = explode("=",api_get_cidReq());
 396              $base_work_dir = api_get_path(SYS_COURSE_PATH).$course_name[1].'/document';
 397              $dir_name = '/mindmaps/'.Database::escape_string(Security::remove_XSS($_POST['category_name']));
 398              $post_dir_name = Database::escape_string(Security::remove_XSS($_POST['category_name']));
 399              $created_dir = create_unexisting_directory($_course,$_user['user_id'],$to_group_id,$to_user_id,$base_work_dir,$dir_name,$post_dir_name);
 400              if(!$created_dir)
 401              {
 402                  return array('type' => 'error', 'message'=>get_lang('CannotCreateDir'));
 403              }
 404              return array('type' => 'confirmation', 'message'=>get_lang('CategoryStored'));
 405          }
 406          else
 407          {
 408              return array('type' => 'error', 'message'=>get_lang('CategoryAlreadyExistsEditIt'));
 409          }
 410      }
 411      else
 412      {
 413          $sql="UPDATE ".$dropbox_cnf['tbl_category']." SET cat_name='".Database::escape_string(Security::remove_XSS($_POST['category_name']))."', received='".Database::escape_string($received)."' , sent='".Database::escape_string($sent)."'
 414                  WHERE user_id='".Database::escape_string($_user['user_id'])."'
 415                  AND cat_id='".Database::escape_string(Security::remove_XSS($_POST['edit_id']))."'";
 416          Database::query($sql,__FILE__,__LINE__);
 417          return array('type' => 'confirmation', 'message'=>get_lang('CategoryModified'));
 418      }
 419  }
 420  
 421  /**
 422  * This function displays the form to add a new category.
 423  *
 424  * @param $category_name this parameter is the name of the category (used when no section is selected)
 425  * @param $id this is the id of the category we are editing.
 426  *
 427  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 428  * @version march 2006
 429  */
 430  function display_addcategory_form($category_name='', $id='',$action)
 431  {
 432      global $dropbox_cnf;
 433  
 434      $title=get_lang('AddNewCategory');
 435  
 436      if (isset($id) AND $id<>'')
 437      {
 438          // retrieve the category we are editing
 439          $sql="SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE cat_id='".Database::escape_string($id)."'";
 440          $result=Database::query($sql,__FILE__,__LINE__);
 441          $row=Database::fetch_array($result);
 442  
 443          if ($category_name=='') // after an edit with an error we do not want to return to the original name but the name we already modified. (happens when createinrecievedfiles AND createinsentfiles are not checked)
 444          {
 445              $category_name=$row['cat_name'];
 446          }
 447          if ($row['received']=='1')
 448          {
 449              $target='received';
 450          }
 451          if ($row['sent']=='1')
 452          {
 453              $target='sent';
 454          }
 455          $title=get_lang('EditCategory');
 456  
 457      }
 458  
 459      if ($action=='addreceivedcategory') {
 460          $target='received';
 461      }
 462      if ($action=='addsentcategory') {
 463          $target='sent';
 464      }
 465  
 466      if ($action=='editcategory') {
 467          $text=get_lang('ModifyCategory');
 468          $class='save';
 469      } else if ($action=='addreceivedcategory' or $action=='addsentcategory')  {
 470          $text=get_lang('CreateCategory');
 471          $class='add';
 472      }
 473  
 474  
 475      echo "<form name=\"add_new_category\" method=\"post\" action=\"".api_get_self()."?view=".Security::remove_XSS($_GET['view'])."\">\n";
 476      if (isset($id) AND $id<>'')
 477      {
 478          echo '<input name="edit_id" type="hidden" value="'.Security::remove_XSS($id).'">';
 479      }
 480      echo '<input name="action" type="hidden" value="'.Security::remove_XSS($action).'">';
 481      echo '<input name="target" type="hidden" value="'.$target.'">';
 482  
 483      echo '<div class="row"><div class="form_header">'.$title.'</div></div>';
 484  
 485      echo '    <div class="row">
 486                  <div class="label">
 487                      <span class="form_required">*</span> '.get_lang('CategoryName').'
 488                  </div>
 489                  <div class="formw">';
 490      if ($_POST AND empty($_POST['category_name']))
 491      {
 492          echo '<span class="form_error">'.get_lang('ThisFieldIsRequired').'. '.get_lang('ErrorPleaseGiveCategoryName').'<span><br />';
 493      }
 494      if ($_POST AND !empty($_POST['category_name']))
 495      {
 496          echo '<span class="form_error">'.get_lang('CategoryAlreadyExistsEditIt').'<span><br />';
 497      }
 498      echo '            <input type="text" name="category_name" value="'.Security::remove_XSS($category_name).'" />
 499                  </div>
 500              </div>';
 501  
 502      echo '    <div class="row">
 503                  <div class="label">
 504                  </div>
 505                  <div class="formw">
 506                      <button class="'.$class.'" type="submit" name="StoreCategory">'.$text.'</button>
 507                  </div>
 508              </div>';
 509      echo '    <div class="row">
 510                  <div class="label">
 511                  </div>
 512                  <div class="formw">
 513                      <span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>
 514                  </div>
 515              </div>';
 516      echo '</form>';
 517      echo '<div style="clear: both;"></div>';
 518  }
 519  
 520  /**
 521  * this function displays the form to upload a new item to the dropbox.
 522  *
 523  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 524  * @version march 2006
 525  */
 526  function display_add_form()
 527  {
 528      global $_user, $is_courseAdmin, $is_courseTutor, $course_info, $origin, $dropbox_unid;
 529  
 530      $token = Security::get_token();
 531      $dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
 532      ?>
 533      <form method="post" action="index.php?view_received_category=<?php echo Security::remove_XSS($_GET['view_received_category']); ?>&view_sent_category=<?php echo Security::remove_XSS($_GET['view_sent_category']); ?>&view=<?php echo Security::remove_XSS($_GET['view']); ?>&<?php echo "origin=$origin"."&".api_get_cidreq(); ?>" enctype="multipart/form-data" onsubmit="return checkForm(this)">
 534  
 535      <!--<div class="row"><div class="form_header"><?php echo get_lang('UploadNewFile'); ?></div></div>-->
 536  
 537      <div class="row">
 538          <div class="label">
 539              <span class="form_required">*</span><?php echo dropbox_lang("uploadFile")?>:
 540          </div>
 541          <div class="formw">
 542                  <input type="hidden" name="MAX_FILE_SIZE" value='<?php echo dropbox_cnf("maxFilesize")?>' />
 543                  <input type="file" name="file" size="20" <?php if (dropbox_cnf("allowOverwrite")) echo 'onChange="checkfile(this.value)"'; ?> />
 544                  <input type="hidden" name="dropbox_unid" value="<?php echo $dropbox_unid ?>" />
 545                  <input type="hidden" name="sec_token" value="<?php echo $token ?>" />
 546                  <input type="hidden" name="curdirpath" value="<?php echo $_GET['curdirpath']; ?>" />
 547                  <?php
 548                  if ($origin=='learnpath')
 549                  {
 550                      echo '<input type="hidden" name="origin" value="learnpath" />';
 551                  }
 552                  ?>
 553          </div>
 554      </div>
 555  
 556      <?php
 557  //    if (dropbox_cnf("allowOverwrite"))
 558  //    {
 559          ?>
 560      <!--<div class="row">
 561              <div class="label">
 562  
 563              </div>
 564              <div class="formw">
 565                  <input type="checkbox" name="cb_overwrite" id="cb_overwrite" value="true" /><?php echo dropbox_lang("overwriteFile")?>
 566              </div>
 567          </div>-->
 568          <?php
 569  //    }
 570      ?>
 571  
 572      <div class="row">
 573          <div class="label">
 574              <?php echo dropbox_lang("sendTo")?>:
 575          </div>
 576          <div class="formw">
 577      <?php
 578  
 579      //list of all users in this course and all virtual courses combined with it
 580      if(isset($_SESSION['id_session'])){
 581          $complete_user_list_for_dropbox = array();
 582          if(api_get_setting('dropbox_allow_student_to_student')=='true' || $_user['status'] != STUDENT)
 583          {
 584              $complete_user_list_for_dropbox = CourseManager :: get_user_list_from_course_code($course_info['code'],true,$_SESSION['id_session'],'',api_get_setting('user_order_by'));
 585          }
 586          $complete_user_list2 = CourseManager :: get_coach_list_from_course_code($course_info['code'],$_SESSION['id_session']);
 587          $complete_user_list_for_dropbox = array_merge($complete_user_list_for_dropbox,$complete_user_list2);
 588      }
 589      else{
 590          if(api_get_setting('dropbox_allow_student_to_student')=='true' || $_user['status'] != STUDENT)
 591          {
 592              $complete_user_list_for_dropbox = CourseManager :: get_user_list_from_course_code($course_info['code'],true,$_SESSION['id_session'],'',api_get_setting('user_order_by'));
 593          }
 594          else
 595          {
 596              $complete_user_list_for_dropbox = CourseManager :: get_teacher_list_from_course_code($course_info['code']);
 597          }
 598      }    
 599  
 600      
 601  
 602      foreach ($complete_user_list_for_dropbox as $k => $e) {
 603          $complete_user_list_for_dropbox[$k] = $e + array('lastcommafirst' => api_get_person_name($e['firstname'], $e['lastname']));
 604      }
 605  
 606      $complete_user_list_for_dropbox = TableSort::sort_table($complete_user_list_for_dropbox, 'lastcommafirst');
 607  
 608      ?>
 609  
 610                  <select name="recipients[]" size="
 611      <?php
 612          if ( $dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin)
 613          {
 614              echo 10;
 615          }
 616          else
 617          {
 618              echo 6;
 619          }
 620  
 621  
 622      ?>" multiple style="width: 350px;">
 623      <?php
 624  
 625      /*
 626          Create the options inside the select box:
 627          List all selected users their user id as value and a name string as display
 628      */
 629  
 630      $current_user_id = '';
 631      foreach ($complete_user_list_for_dropbox as $current_user)
 632      {
 633          if ( ($dropbox_person -> isCourseTutor
 634          || $dropbox_person -> isCourseAdmin
 635          || dropbox_cnf("allowStudentToStudent")    // RH: also if option is set
 636          || $current_user['status']!=5                // always allow teachers
 637          || $current_user['tutor_id']==1                // always allow tutors
 638          ) && $current_user['user_id'] != $_user['user_id'] )     // don't include yourself
 639          {
 640              if ($current_user['user_id'] == $current_user_id) continue;
 641              $full_name = $current_user['lastcommafirst'];
 642              $current_user_id = $current_user['user_id'];
 643              echo '<option value="user_' . $current_user_id . '">' . $full_name . '</option>';
 644          }
 645      }
 646  
 647      /*
 648      * Show groups
 649      */
 650      if ( ($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin)
 651      && dropbox_cnf("allowGroup") || dropbox_cnf("allowStudentToStudent"))
 652      {
 653          $complete_group_list_for_dropbox = GroupManager::get_group_list(null,dropbox_cnf("courseId"));
 654  
 655          if (count($complete_group_list_for_dropbox) > 0)
 656          {
 657              foreach ($complete_group_list_for_dropbox as $current_group)
 658              {
 659                  if ($current_group['number_of_members'] > 0)
 660                  {
 661                      echo '<option value="group_'.$current_group['id'].'">G: '.$current_group['name'].' - '.$current_group['number_of_members'].' '.get_lang('Users').'</option>';
 662                  }
 663              }
 664          }
 665      }
 666  
 667      if ( ($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin) && dropbox_cnf("allowMailing"))  // RH: Mailing starting point
 668      {
 669              // echo '<option value="mailing">'.dropbox_lang("mailingInSelect").'</option>';
 670      }
 671  
 672      if ( dropbox_cnf("allowJustUpload"))  // RH
 673      {
 674        //echo '<option value="upload">'.dropbox_lang("justUploadInSelect").'</option>';
 675      //  echo '<option value="user_'.$_user['user_id'].'">'.dropbox_lang("justUploadInSelect").'</option>';
 676      }
 677  
 678          echo '</select>
 679          <img style="vertical-align:top;" src="../img/mindmap_128.png">
 680          </div>
 681      </div>';
 682  
 683      echo '
 684          <div class="row">
 685              <div class="label">
 686              </div>
 687              <div class="formw">
 688                  <button type="Submit" class="upload" name="submitWork">'.dropbox_lang("upload", "noDLTT").'</button>
 689              </div>
 690          </div>';
 691  
 692      echo '<div class="row"></div>';
 693  
 694      echo "</form>";
 695  }
 696  
 697  /**
 698  * returns username or false if user isn't registered anymore
 699  * @todo check if this function is still necessary. There might be a library function for this.
 700  */
 701  function getUserNameFromId ( $id)  // RH: Mailing: return 'Mailing ' + id
 702  {
 703      $mailingId = $id - dropbox_cnf("mailingIdBase");
 704      if ( $mailingId > 0)
 705      {
 706          return dropbox_lang("mailingAsUsername", "noDLTT") . $mailingId;
 707      }
 708      $id = intval($id);
 709      $sql = "SELECT ".(api_is_western_name_order() ? "CONCAT(firstname,' ', lastname)" : "CONCAT(lastname,' ', firstname)")." AS name
 710              FROM " . dropbox_cnf("tbl_user") . "
 711              WHERE user_id='$id'";
 712      $result = Database::query($sql,__FILE__,__LINE__);
 713      $res = Database::fetch_array( $result);
 714  
 715      if ( $res == FALSE) return FALSE;
 716      return stripslashes( $res["name"]);
 717  }
 718  
 719  /**
 720  * returns loginname or false if user isn't registered anymore
 721  * @todo check if this function is still necessary. There might be a library function for this.
 722  */
 723  function getLoginFromId ( $id)
 724  {
 725      $id = intval($id);
 726      $sql = "SELECT username
 727              FROM " . dropbox_cnf("tbl_user") . "
 728              WHERE user_id='$id'";
 729      $result =Database::query($sql,__FILE__,__LINE__);
 730      $res = Database::fetch_array( $result);
 731      if ( $res == FALSE) return FALSE;
 732      return stripslashes( $res["username"]);
 733  }
 734  
 735  /**
 736  * @return boolean indicating if user with user_id=$user_id is a course member
 737  * @todo eliminate global
 738  * @todo check if this function is still necessary. There might be a library function for this.
 739  */
 740  function isCourseMember( $user_id)
 741  {
 742      global $_course;
 743      $course_code = $_course['sysCode'];
 744      $is_course_member = CourseManager::is_user_subscribed_in_course($user_id, $course_code,true);
 745      return $is_course_member;
 746  }
 747  
 748  /**
 749  * Checks if there are files in the dropbox_file table that aren't used anymore in dropbox_person table.
 750  * If there are, all entries concerning the file are deleted from the db + the file is deleted from the server
 751  */
 752  function removeUnusedFiles( )
 753  {
 754      // select all files that aren't referenced anymore
 755      $sql = "SELECT DISTINCT f.id, f.filename
 756              FROM " . dropbox_cnf("tbl_file") . " f
 757              LEFT JOIN " . dropbox_cnf("tbl_person") . " p ON f.id = p.file_id
 758              WHERE p.user_id IS NULL";
 759      $result = Database::query($sql,__FILE__,__LINE__);
 760      while ( $res = Database::fetch_array( $result))
 761      {
 762          //delete the selected files from the post and file tables
 763          $sql = "DELETE FROM " . dropbox_cnf("tbl_post") . " WHERE file_id='" . $res['id'] . "'";
 764          $result1 = Database::query($sql,__FILE__,__LINE__);
 765          $sql = "DELETE FROM " . dropbox_cnf("tbl_file") . " WHERE id='" . $res['id'] . "'";
 766          $result1 = Database::query($sql,__FILE__,__LINE__);
 767  
 768          //delete file from server
 769          @unlink( dropbox_cnf("sysPath") . "/" . $res["filename"]);
 770      }
 771  }
 772  
 773  /**
 774  * RH: Mailing (2 new functions)
 775  *
 776  * Mailing zip-file is posted to (dest_user_id = ) mailing pseudo_id
 777  * and is only visible to its uploader (user_id).
 778  *
 779  * Mailing content files have uploader_id == mailing pseudo_id, a normal recipient,
 780  * and are visible initially to recipient and pseudo_id.
 781  *
 782  * @author René Haentjens, Ghent University
 783  *
 784  * @todo check if this function is still necessary.
 785  */
 786  function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '')
 787  {
 788      $mailingPseudoId = intval($mailingPseudoId);
 789      $sql = "SELECT f.uploader_id
 790              FROM " . dropbox_cnf("tbl_file") . " f
 791              LEFT JOIN " . dropbox_cnf("tbl_post") . " p ON f.id = p.file_id
 792              WHERE p.dest_user_id = '" . $mailingPseudoId . "'";
 793      $result = Database::query($sql,__FILE__,__LINE__);
 794  
 795      if (!($res = Database::fetch_array($result)))
 796          die(dropbox_lang("generalError")." (code 901)");
 797  
 798      if ($owner == 0) return $res['uploader_id'];
 799  
 800      if ($res['uploader_id'] == $owner) return TRUE;
 801  
 802      die(dropbox_lang("generalError")." (code ".$or_die.")");
 803  }
 804  /**
 805  * @author Ren� Haentjens, Ghent University
 806  * @todo check if this function is still necessary.
 807  */
 808  function removeMoreIfMailing($file_id)
 809  {
 810      // when deleting a mailing zip-file (posted to mailingPseudoId):
 811      // 1. the detail window is no longer reachable, so
 812      //    for all content files, delete mailingPseudoId from person-table
 813      // 2. finding the owner (getUserOwningThisMailing) is no longer possible, so
 814      //    for all content files, replace mailingPseudoId by owner as uploader
 815      $file_id = intval($file_id);
 816      $sql = "SELECT p.dest_user_id
 817              FROM " . dropbox_cnf("tbl_post") . " p
 818              WHERE p.file_id = '" . $file_id . "'";
 819      $result = Database::query($sql,__FILE__,__LINE__);
 820  
 821      if ( $res = Database::fetch_array( $result))
 822      {
 823          $mailingPseudoId = $res['dest_user_id'];
 824          if ( $mailingPseudoId > dropbox_cnf("mailingIdBase"))
 825          {
 826              $sql = "DELETE FROM " . dropbox_cnf("tbl_person") . " WHERE user_id='" . $mailingPseudoId . "'";
 827              $result1 = Database::query($sql,__FILE__,__LINE__);
 828  
 829              $sql = "UPDATE " . dropbox_cnf("tbl_file") .
 830                  " SET uploader_id='" . api_get_user_id() . "' WHERE uploader_id='" . $mailingPseudoId . "'";
 831              $result1 = Database::query($sql,__FILE__,__LINE__);
 832          }
 833      }
 834  }
 835  
 836  /**
 837  * The dropbox has a deviant naming scheme for language files so it needs an additional language function
 838  *
 839  * @todo check if this function is still necessary.
 840  *
 841  * @author René Haentjens, Ghent University
 842  */
 843  function dropbox_lang($variable, $notrans = 'DLTT')
 844  {
 845      global $charset;
 846      return (api_get_setting('server_type') == 'test' ?
 847          get_lang('dropbox_lang["'.$variable.'"]', $notrans) :
 848          api_html_entity_decode(api_to_system_encoding(str_replace("\\'", "'", $GLOBALS['dropbox_lang'][$variable]), null, true), ENT_QUOTES, $charset));
 849  }
 850  /**
 851  * Function that finds a given config setting
 852  *
 853  * @author René Haentjens, Ghent University
 854  */
 855  function dropbox_cnf($variable)
 856  {
 857      return $GLOBALS['dropbox_cnf'][$variable];
 858  }
 859  
 860  
 861  
 862  /**
 863  *
 864  */
 865  function store_add_dropbox()
 866  {
 867      global $dropbox_cnf;
 868      global $_user;
 869      global $_course;    
 870      
 871      // ----------------------------------------------------------
 872      // Validating the form data
 873      // ----------------------------------------------------------
 874  
 875      // the author is
 876      /*
 877      if (!isset( $_POST['authors']))
 878      {
 879          return get_lang('AuthorFieldCannotBeEmpty');
 880      }
 881      */
 882      // Check if mindmap folder exists, if doen't exists we will create the folder
 883      $course_id=api_get_course_id();
 884      DocumentManager::create_specifics_folder_in_course($course_id,'mindmaps');
 885      // there are no recipients selected
 886      if ( !isset( $_POST['recipients']) || count( $_POST['recipients']) <= 0)
 887      {    
 888          $_POST["recipients"] = 'user_'.$_user['user_id'];     
 889      }
 890      // Check if all the recipients are valid
 891      if(count( $_POST['recipients']) <= 0)
 892      {    
 893          return get_lang('YouMustSelectAtLeastOneDestinee');
 894      }
 895      else
 896      {
 897          $thisIsAMailing = FALSE;  // RH: Mailing selected as destination
 898          $thisIsJustUpload = FALSE;  // RH
 899          foreach( $_POST['recipients'] as $rec)
 900          {
 901              if ( $rec == 'mailing')
 902              {
 903                  $thisIsAMailing = TRUE;
 904              }
 905              elseif ( $rec == 'upload')
 906              {
 907                  $thisIsJustUpload = TRUE;
 908              }
 909              elseif (strpos($rec, 'user_') === 0 && !isCourseMember(substr($rec, strlen('user_') ) ))
 910              {
 911                  return get_lang('InvalideUserDetected');
 912              }
 913              elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0)
 914              {
 915                  return get_lang('InvalideGroupDetected');
 916              }
 917          }
 918      }
 919  
 920      // we are doing a mailing but an additional recipient is selected
 921      if ( $thisIsAMailing && ( count($_POST['recipients']) != 1))
 922      {
 923          return get_lang('MailingSelectNoOther');
 924      }
 925  
 926      // we are doing a just upload but an additional recipient is selected.
 927      // note: why can't this be valid? It is like sending a document to yourself AND to a different person (I do this quite often with my e-mails)
 928      if ( $thisIsJustUpload && ( count($_POST['recipients']) != 1))
 929      {
 930          return get_lang('mailingJustUploadSelectNoOther');
 931      }
 932  
 933      if ( empty( $_FILES['file']['name']))
 934      {
 935          $error = TRUE;
 936          return  get_lang('NoFileSpecified');
 937      }
 938  
 939      // ----------------------------------------------------------
 940      // are we overwriting a previous file or sending a new one
 941      // ----------------------------------------------------------
 942      $dropbox_overwrite = false;
 943      if ( isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']==true)
 944      {
 945          $dropbox_overwrite = true;
 946      }
 947  
 948      // ----------------------------------------------------------
 949      // doing the upload
 950      // ----------------------------------------------------------
 951      $dropbox_filename = $_FILES['file']['name'];
 952      $dropbox_filesize = $_FILES['file']['size'];
 953      $dropbox_filetype = $_FILES['file']['type'];
 954      $dropbox_filetmpname = $_FILES['file']['tmp_name'];
 955  
 956      // check if the filesize does not exceed the allowed size.
 957      if ( $dropbox_filesize <= 0 || $dropbox_filesize > $dropbox_cnf["maxFilesize"])
 958      {
 959          return get_lang('DropboxFileTooBig');
 960      }
 961  
 962      // check if the file is actually uploaded
 963      if ( !is_uploaded_file( $dropbox_filetmpname)) // check user fraud : no clean error msg.
 964      {
 965          return get_lang('TheFileIsNotUploaded');
 966      }
 967  
 968      // Try to add an extension to the file if it hasn't got one
 969      $dropbox_filename = add_ext_on_mime( $dropbox_filename,$dropbox_filetype);
 970      // Replace dangerous characters
 971      $dropbox_filename = replace_dangerous_char( $dropbox_filename);
 972      // Transform any .php file in .phps fo security
 973      $dropbox_filename = php2phps ( $dropbox_filename);
 974      //filter extension    
 975    /*  if(!filter_extension($dropbox_filename))
 976      {
 977          return get_lang('UplUnableToSaveFileFilteredExtension');
 978      }*/
 979  
 980      $dropbox_filename_ext = pathinfo($dropbox_filename, PATHINFO_EXTENSION);    
 981      $allow_extension_files=array('png', 'jpg', 'gif', 'jpeg','xmind');
 982      if(!in_array($dropbox_filename_ext,$allow_extension_files))
 983      {
 984          return get_lang('UplUnableToSaveFileFilteredExtension');
 985      }
 986  
 987      // set title
 988      $dropbox_title = $dropbox_filename;
 989      // set author
 990      if ( $_POST['authors'] == '')
 991      {
 992          $_POST['authors'] = getUserNameFromId( $_user['user_id']);
 993      }
 994  
 995      // note: I think we could better migrate everything from here on to separate functions: store_new_dropbox, store_new_mailing, store_just_upload
 996  
 997      if ($dropbox_overwrite)  // RH: Mailing: adapted
 998      {
 999          $dropbox_person = new Dropbox_Person( $_user['user_id'], api_is_course_admin(), api_is_course_tutor());
1000  
1001          foreach($dropbox_person->sentWork as $w)
1002          {
1003              if ($w->title == $dropbox_filename)
1004              {
1005                  if ( ($w->recipients[0]['id'] > dropbox_cnf("mailingIdBase")) xor $thisIsAMailing)
1006                  {
1007                      return get_lang('MailingNonMailingError');
1008                  }
1009                  if ( ($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload)
1010                  {
1011                      return get_lang('MailingJustUploadSelectNoOther');
1012                  }
1013                  $dropbox_filename = $w->filename;
1014                  $found = true; // note: do we still need this?
1015                  break;
1016              }
1017          }
1018      }
1019      else  // rename file to login_filename_uniqueId format
1020      {
1021      //    $dropbox_filename = getLoginFromId( $_user['user_id']) . "_" . $dropbox_filename . "_".uniqid('');
1022      }
1023  
1024      // creating the array that contains all the users who will receive the file
1025      $new_work_recipients = array();
1026      foreach ($_POST["recipients"] as $rec)
1027      {
1028          if (strpos($rec, 'user_') === 0)
1029          {
1030              $new_work_recipients[] = substr($rec, strlen('user_') );
1031          }
1032          elseif (strpos($rec, 'group_') === 0 )
1033          {
1034              $userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_') ));
1035              foreach ($userList as $usr)
1036              {
1037                  if (! in_array($usr['user_id'], $new_work_recipients) && $usr['user_id'] != $_user['user_id'])
1038                  {
1039                      $new_work_recipients[] = $usr['user_id'];
1040                  }
1041              }
1042          }
1043      }
1044      $course_name = explode("=",api_get_cidReq());
1045      $mindmap_syspath = api_get_path(SYS_COURSE_PATH).$course_name[1].'/document/mindmaps';
1046      $thumbnail_width = 250;
1047      $thumbnail_height = 150;
1048      $curdirpath = '';
1049      if(isset($_POST['curdirpath'])){     
1050          $curdirpath = Security::remove_XSS($_POST['curdirpath']);
1051          if ($curdirpath == '/') {
1052              $curdirpath = '';
1053          }        
1054      }
1055      $mindmap_path = $mindmap_syspath.$curdirpath.'/';
1056      if ($curdirpath == '') {
1057        $mindmap_path = $mindmap_syspath;
1058      }
1059  
1060      if($dropbox_filename_ext == 'png' || $dropbox_filename_ext == 'gif' || $dropbox_filename_ext == 'jpeg' || $dropbox_filename_ext == 'jpg')
1061      {        
1062      //    @move_uploaded_file( $dropbox_filetmpname, dropbox_cnf("sysPath") . '/' . $dropbox_filename);
1063          @move_uploaded_file( $dropbox_filetmpname, $mindmap_path .'/'. $dropbox_filename);
1064      /*    copy($mindmap_path . '/' . $dropbox_filename, $mindmap_syspath . '/thumbs/' . $dropbox_filename);        
1065          $image = $mindmap_syspath . '/thumbs/' . $dropbox_filename;
1066          list($twidth,$theight) = getimagesize($image);
1067          $ratio_orig = $twidth/$theight;
1068  
1069          if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
1070             $thumbnail_width = $thumbnail_height*$ratio_orig;
1071          } else {
1072             $thumbnail_height = $thumbnail_width/$ratio_orig;
1073          }
1074      
1075          create_thumbnail($image,$thumbnail_width,$thumbnail_height);        */
1076      }
1077      elseif($dropbox_filename_ext == 'xmind')
1078      {
1079          require_once  '../inc/lib/mindmapConverter.php';
1080          @move_uploaded_file( $dropbox_filetmpname, $mindmap_syspath . '/xmind/' . $dropbox_filename);
1081          $converter = new MindmapConverter('127.0.0.1',1984);
1082          $source = $mindmap_syspath . '/xmind/' . $dropbox_filename;
1083          $tmp_filename = pathinfo($dropbox_filename);
1084          $destination = $mindmap_path . '/' . $tmp_filename['filename'].'.png';
1085          $converter->convertToPng($source, $destination);
1086      /*    copy($mindmap_syspath . '/' . $dropbox_filename, $mindmap_syspath . '/thumbs/' . $dropbox_filename);        
1087          $image = $mindmap_syspath . '/thumbs/' . $dropbox_filename;
1088          create_thumbnail($image,$thumbnail_width,$thumbnail_height);*/
1089      }
1090  
1091      $b_send_mail = api_get_course_setting('email_alert_on_new_doc_dropbox');
1092  
1093      if($b_send_mail)
1094      {
1095          foreach($new_work_recipients as $recipient_id)
1096          {
1097              include_once(api_get_path(LIBRARY_PATH) . 'usermanager.lib.php');
1098              $recipent_temp=UserManager :: get_user_info_by_id($recipient_id);
1099              api_mail(api_get_person_name($recipent_temp['firstname'].' '.$recipent_temp['lastname'], null, PERSON_NAME_EMAIL_ADDRESS), $recipent_temp['email'],
1100                  get_lang('NewDropboxFileUploaded'),
1101                  get_lang('NewDropboxFileUploadedContent').' '.api_get_path(WEB_CODE_PATH).'dropbox/index.php?cidReq='.$_course['sysCode']."\n\n".api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS)."\n".  get_lang('Email') ." : ".$_user['mail'], api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS), $_user['mail']);
1102                  //get_lang('NewDropboxFileUploadedContent').' '.api_get_path(WEB_CODE_PATH).'dropbox/index.php?cidReq='.$_course['sysCode']."\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS)."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator'), api_get_person_name(api_get_setting('administratorName')." ".api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS), api_get_setting('emailAdministrator'));
1103          }
1104      }
1105  
1106      $_SESSION['curdirpath'] = $curdirpath;
1107  
1108      new Dropbox_SentWork( $_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $new_work_recipients);
1109      
1110  /*    if(empty($curdirpath))
1111      {
1112      $desired_filename = '/mindmaps/'.$dropbox_filename;
1113      }
1114      else
1115      {
1116      $desired_filename = '/mindmaps/'.$curdirpath.'/'.$dropbox_filename;
1117      }    
1118      $document_id = add_document($_course, $desired_filename,'file',$dropbox_filesize,$dropbox_filename);
1119      if ($document_id)
1120      {
1121      //update document item_property
1122      $to_group_id = 0;
1123      $to_user_id = 0;
1124      $current_session_id = api_get_session_id();
1125      api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'MindmapCreated',$_user['user_id'],$to_group_id,$to_user_id,null,null,$current_session_id);        
1126      }*/
1127  
1128      Security::clear_token();
1129      return get_lang('FileUploadSucces');
1130  }
1131  
1132  
1133  
1134  /**
1135  * This function displays the firstname and lastname of the user as a link to the user tool.
1136  *
1137  * @see this is the same function as in the new forum, so this probably has to move to a user library.
1138  *
1139  * @todo move this function to the user library
1140  *
1141  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1142  * @version march 2006
1143  */
1144  function display_user_link($user_id, $name='')
1145  {
1146      global $_otherusers;
1147  
1148      if ($user_id<>0)
1149      {
1150          if ($name=='')
1151          {
1152              $table_user = Database::get_main_table(TABLE_MAIN_USER);
1153              $sql="SELECT * FROM $table_user WHERE user_id='".Database::escape_string($user_id)."'";
1154              $result=Database::query($sql,__FILE__,__LINE__);
1155              $row=Database::fetch_array($result);
1156              return "<a href=\"../user/userInfo.php?uInfo=".$row['user_id']."\">".api_get_person_name($row['firstname'], $row['lastname'])."</a>";
1157          }
1158          else
1159          {
1160              $user_id = intval($user_id);
1161              return "<a href=\"../user/userInfo.php?uInfo=".$user_id."\">".Security::remove_XSS($name)."</a>";
1162          }
1163      }
1164      else
1165      {
1166          return $name.' ('.get_lang('Anonymous').')';
1167      }
1168  }
1169  
1170  /**
1171  * this function transforms the array containing all the feedback into something visually attractive.
1172  *
1173  * @param an array containing all the feedback about the given message.
1174  *
1175  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1176  * @version march 2006
1177  */
1178  function feedback($array)
1179  {
1180  
1181      foreach ($array as $key=>$value)
1182      {
1183          $output.=format_feedback($value);
1184      }
1185      $output.=feedback_form();
1186      return $output;
1187  }
1188  
1189  /**
1190  * This function returns the html code to display the feedback messages on a given dropbox file
1191  * @param $feedback_array an array that contains all the feedback messages about the given document.
1192  * @return html code
1193  * @todo add the form for adding new comment (if the other party has not deleted it yet).
1194  *
1195  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1196  * @version march 2006
1197  */
1198  function format_feedback($feedback)
1199  {
1200      $output.=display_user_link($feedback['author_user_id']);
1201      $output.='&nbsp;&nbsp;['.$feedback['feedback_date'].']<br />';
1202      $output.='<div style="padding-top:6px">'.nl2br($feedback['feedback']).'</div><hr size="1" noshade/><br />';
1203      return $output;
1204  }
1205  
1206  /**
1207  * this function returns the code for the form for adding a new feedback message to a dropbox file.
1208  * @return html code
1209  *
1210  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1211  * @version march 2006
1212  */
1213  function feedback_form()
1214  {
1215      global $dropbox_cnf;
1216  
1217      $return = get_lang('AddNewFeedback').'<br />';
1218  
1219      // we now check if the other users have not delete this document yet. If this is the case then it is useless to see the
1220      // add feedback since the other users will never get to see the feedback.
1221      echo $sql="SELECT * FROM ".$dropbox_cnf["tbl_person"]." WHERE file_id='".Database::escape_string($_GET['id'])."'";
1222      $result=Database::query($sql,__LINE__, __FILE__);
1223      $number_users_who_see_file=Database::num_rows($result);
1224      if ($number_users_who_see_file>=1)
1225      {
1226          $return .= '<textarea name="feedback" style="width: 80%; height: 80px;"></textarea><br /><button type="submit" class="add" name="store_feedback" value="'.get_lang('Ok').'"
1227              onclick="document.form_tablename.attributes.action.value = document.location;">'.get_lang('AddComment').'</button>';
1228      }
1229      else
1230      {
1231          $return .= get_lang('AllUsersHaveDeletedTheFileAndWillNotSeeFeedback');
1232      }
1233      return $return;
1234  }
1235  
1236  /**
1237  * @return a language string (depending on the success or failure.
1238  *
1239  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1240  * @version march 2006
1241  */
1242  function store_feedback()
1243  {
1244      global $dropbox_cnf;
1245      global $_user;
1246  
1247      if (!is_numeric($_GET['id']))
1248      {
1249          return get_lang('FeedbackError');
1250      }
1251  
1252      if ($_POST['feedback']=='')
1253      {
1254          return get_lang('PleaseTypeText');
1255      }
1256      else
1257      {
1258           $sql="INSERT INTO ".$dropbox_cnf['tbl_feedback']." (file_id, author_user_id, feedback, feedback_date) VALUES
1259                  ('".Database::escape_string($_GET['id'])."','".Database::escape_string($_user['user_id'])."','".Database::escape_string($_POST['feedback'])."',NOW())";
1260          Database::query($sql,__FILE__,__LINE__);
1261          return get_lang('DropboxFeedbackStored');
1262      }
1263  }
1264  
1265  /**
1266  * This function downloads all the files of the inputarray into one zip
1267  * @param $array an array containing all the ids of the files that have to be downloaded.
1268  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1269  * @todo consider removing the check if the user has received or sent this file (zip download of a folder already sufficiently checks for this).
1270  * @todo integrate some cleanup function that removes zip files that are older than 2 days
1271  *
1272  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1273  * @version march 2006
1274  */
1275  function zip_download ($array)
1276  {
1277      global $_course;
1278      global $dropbox_cnf;
1279      global $_user;
1280      global $files;
1281  
1282      $sys_course_path = api_get_path(SYS_COURSE_PATH);
1283  
1284      // zip library for creation of the zipfile
1285      include(api_get_path(LIBRARY_PATH)."/pclzip/pclzip.lib.php");
1286  
1287      // place to temporarily stash the zipfiles
1288      $temp_zip_dir = api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/";
1289  
1290      // create the directory if it does not exist yet.
1291      if(!is_dir($temp_zip_dir))
1292      {
1293          mkdir($temp_zip_dir);
1294      }
1295  
1296      cleanup_temp_dropbox();
1297  
1298      $files='';
1299  
1300      // note: we also have to add the check if the user has received or sent this file. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1301      $sql="SELECT distinct file.filename, file.title, file.author, file.description
1302              FROM ".$dropbox_cnf["tbl_file"]." file, ".$dropbox_cnf["tbl_person"]." person
1303              WHERE file.id IN (".implode(', ',$array).")
1304              AND file.id=person.file_id
1305              AND person.user_id='".$_user['user_id']."'";
1306      $result=Database::query($sql,__FILE__,__LINE__);
1307      while ($row=Database::fetch_array($result))
1308      {
1309          $files[$row['filename']]=array('filename'=>$row['filename'],'title'=>$row['title'], 'author'=>$row['author'], 'description'=>$row['description']);
1310      }
1311  
1312      //$alternative is a variable that uses an alternative method to create the zip
1313      // because the renaming of the files inside the zip causes error on php5 (unexpected end of archive)
1314      $alternative=true;
1315      if ($alternative)
1316      {
1317          zip_download_alternative($files);
1318          exit;
1319      }
1320  
1321      // create the zip file
1322      $name = 'dropboxdownload-'.$_user['user_id'].'-'.mktime().'.zip';
1323      $temp_zip_file=$temp_zip_dir.'/'.$name;
1324      $zip_folder=new PclZip($temp_zip_file);
1325  
1326      foreach ($files as $key=>$value)
1327      {
1328          // met hernoemen van de files in de zip
1329          $zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox/".$value['filename'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox", PCLZIP_CB_PRE_ADD, 'my_pre_add_callback');
1330          // zonder hernoemen van de files in de zip
1331          //$zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox/".$value['filename'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox");
1332      }
1333  
1334      // create the overview file
1335      $overview_file_content=generate_html_overview($files, array('filename'), array('title'));
1336      $overview_file=$temp_zip_dir.'/overview.html';
1337      $handle=fopen($overview_file,'w');
1338      fwrite($handle,$overview_file_content);
1339  
1340  
1341      // send the zip file
1342      DocumentManager::file_send_for_download($temp_zip_file,true,$name);
1343      exit;
1344  }
1345  /**
1346  * This is a callback function to decrypt the files in the zip file to their normal filename (as stored in the database)
1347  * @param $p_event a variable of PCLZip
1348  * @param $p_header a variable of PCLZip
1349  *
1350  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1351  * @version march 2006
1352  */
1353  function my_pre_add_callback($p_event, &$p_header)
1354  {
1355      global $files;
1356  
1357      $p_header['stored_filename']=$files[$p_header['stored_filename']]['title'];
1358      return 1;
1359  }
1360  
1361  /**
1362  * This function is an alternative zip download. It was added because PCLZip causes problems on PHP5 when using PCLZIP_CB_PRE_ADD and a callback function to rename
1363  * the files inside the zip file (dropbox scrambles the files to prevent
1364  * @todo consider using a htaccess that denies direct access to the file but only allows the php file to access it. This would remove the scrambling requirement
1365  *        but it would require additional checks to see if the filename of the uploaded file is not used yet.
1366  * @param $files is an associative array that contains the files that the user wants to download (check to see if the user is allowed to download these files already
1367  *         happened so the array is clean!!. The key is the filename on the filesystem. The value is an array that contains both the filename on the filesystem and
1368  *         the original filename (that will be used in the zip file)
1369  * @todo when we copy the files there might be two files with the same name. We need a function that (recursively) checks this and changes the name
1370  *
1371  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1372  * @version march 2006
1373  */
1374  function zip_download_alternative($files)
1375  {
1376      global $_course;
1377      global $_user;
1378  
1379      $temp_zip_dir = api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/";
1380  
1381      // Step 2: we copy all the original dropbox files to the temp folder and change their name into the original name
1382      foreach ($files as $key=>$value)
1383      {
1384          $value['title']=check_file_name(api_strtolower($value['title']));
1385          $files[$value['filename']]['title']=$value['title'];
1386          copy(api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox/".$value['filename'], api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$value['title']);
1387      }
1388  
1389      // Step 3: create the zip file and add all the files to it
1390      $temp_zip_file=$temp_zip_dir.'/dropboxdownload-'.$_user['user_id'].'-'.mktime().'.zip';
1391      $zip_folder=new PclZip($temp_zip_file);
1392      foreach ($files as $key=>$value)
1393      {
1394          $zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$value['title'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/temp");
1395      }
1396  
1397      // Step 1: create the overview file and add it to the zip
1398      $overview_file_content=generate_html_overview($files, array('filename'), array('title'));
1399      $overview_file=$temp_zip_dir.'overview'.replace_dangerous_char(api_is_western_name_order() ? $_user['firstname'].$_user['lastname'] : $_user['lastname'].$_user['firstname'], 'strict').'.html';
1400      $handle=fopen($overview_file,'w');
1401      fwrite($handle,$overview_file_content);
1402      // todo: find a different solution for this because even 2 seconds is no guarantee.
1403      sleep(2);
1404  
1405      // Step 4: we add the overview file
1406      $zip_folder->add($overview_file,PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/temp");
1407  
1408      // Step 5: send the file for download;
1409      DocumentManager::file_send_for_download($temp_zip_file,true);
1410  
1411      // Step 6: remove the files in the temp dir
1412      foreach ($files as $key=>$value)
1413      {
1414          unlink(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$value['title']);
1415      }
1416      //unlink($overview_file);
1417  
1418      exit;
1419  }
1420  
1421  /**
1422  * @desc This function checks if the real filename of the dropbox files doesn't already exist in the temp folder. If this is the case then
1423  *        it will generate a different filename;
1424  *
1425  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1426  * @version march 2006
1427  */
1428  function check_file_name($file_name_2_check, $counter=0)
1429  {
1430      global $_course;
1431  
1432      $new_file_name=$file_name_2_check;
1433      if ($counter<>0)
1434      {
1435          $new_file_name=$counter.$new_file_name;
1436      }
1437  
1438      if (!file_exists(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$new_file_name))
1439      {
1440          return $new_file_name;
1441      }
1442      else
1443      {
1444          $counter++;
1445          $new_file_name=check_file_name($file_name_2_check,$counter);
1446          return $new_file_name;
1447      }
1448  }
1449  
1450  
1451  /**
1452  * @desc Cleans the temp zip files that were created when users download several files or a whole folder at once.
1453  *        T
1454  * @return true
1455  * @todo
1456  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1457  * @version march 2006
1458  */
1459  
1460  function cleanup_temp_dropbox()
1461  {
1462      global $_course;
1463  
1464      $handle=opendir(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp");
1465      while (false !== ($file = readdir($handle)))
1466      {
1467          if ($file<>'.' OR $file<>'..')
1468          {
1469              $name=str_replace('.zip', '',$file);
1470              $name_part=explode('-',$name);
1471              $timestamp_of_file=$name_part[count($name_part)-1];
1472              // if it is a dropboxdownloadfile and the file is older than one day then we delete it
1473              if (strstr($file, 'dropboxdownload') AND $timestamp_of_file<(mktime()-86400))
1474              {
1475                  unlink(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$file);
1476              }
1477          }
1478  
1479      }
1480      closedir($handle);
1481      return true;
1482  }
1483  
1484  /**
1485  * @desc generates the contents of a html file that gives an overview of all the files in the zip file.
1486  *        This is to know the information of the files that are inside the zip file (who send it, the comment, ...)
1487  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1488  * @version march 2006
1489  */
1490  function generate_html_overview($files, $dont_show_columns=array(), $make_link=array())
1491  {
1492      $return="<html>\n<head>\n\t<title>".get_lang('OverviewOfFilesInThisZip')."</title>\n</head>";
1493      $return.="\n\n<body>\n<table border=\"1px\">";
1494  
1495      $counter=0;
1496      foreach ($files as $key=>$value)
1497      {
1498          // We add the header
1499          if ($counter==0)
1500          {
1501              $columns_array=array_keys($value);
1502              $return.="\n<tr>";
1503              foreach ($columns_array AS $columns_array_key=>$columns_array_value)
1504              {
1505                  if (!in_array($columns_array_value,$dont_show_columns))
1506                  {
1507                      $return.="\n\t<th>".$columns_array_value."</th>";
1508                  }
1509                  $column[]=$columns_array_value;
1510              }
1511              $return.="</tr><n";
1512          }
1513          $counter++;
1514  
1515          // We add the content
1516          $return.="\n<tr>";
1517          foreach ($column AS $column_key=>$column_value)
1518          {
1519              if (!in_array($column_value,$dont_show_columns))
1520              {
1521                  $return.="\n\t<td>";
1522                  if (in_array($column_value, $make_link))
1523                  {
1524                      $return.='<a href="'.$value[$column_value].'">'.$value[$column_value].'</a>';
1525                  }
1526                  else
1527                  {
1528                      $return.=$value[$column_value];
1529                  }
1530                  $return.="</td>";
1531              }
1532          }
1533          $return.="</tr><n";
1534  
1535  
1536      }
1537      $return.="\n</table>\n\n</body>";
1538      $return.="\n</html>";
1539  
1540      return $return;
1541  }
1542  
1543  /**
1544  * @desc This function retrieves the number of feedback messages on every document. This function might become obsolete when
1545  *         the feedback becomes user individual.
1546  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1547  * @version march 2006
1548  */
1549  function get_total_number_feedback($file_id='')
1550  {
1551      global $dropbox_cnf;
1552  
1553      $sql="SELECT COUNT(feedback_id) AS total, file_id FROM ".$dropbox_cnf['tbl_feedback']." GROUP BY file_id";
1554      $result=Database::query($sql, __FILE__, __LINE__);
1555      while ($row=Database::fetch_array($result))
1556      {
1557          $return[$row['file_id']]=$row['total'];
1558      }
1559      return $return;
1560  }
1561  
1562  
1563  /**
1564  * @desc this function checks if the key exists. If this is the case it returns the value, if not it returns 0
1565  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1566  * @version march 2006
1567  */
1568  function check_number_feedback($key, $array)
1569  {
1570      if (is_array($array))
1571      {
1572          if (key_exists($key,$array))
1573          {
1574              return $array[$key];
1575          }
1576          else
1577          {
1578              return 0;
1579          }
1580      }
1581      else
1582      {
1583          return 0;
1584      }
1585  }
1586  
1587  /**
1588   * Get the last access to a given tool of a given user
1589   * @param $tool string the tool constant
1590   * @param $course_code the course_id
1591   * @param $user_id the id of the user
1592   * @return string last tool access date
1593   *
1594   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1595   * @version march 2006
1596   *
1597   * @todo consider moving this function to a more appropriate place.
1598   */
1599  function get_last_tool_access($tool, $course_code='', $user_id='')
1600  {
1601      global $_course, $_user;
1602  
1603      // The default values of the parameters
1604      if ($course_code=='')
1605      {
1606          $course_code=$_course['id'];
1607      }
1608      if ($user_id=='')
1609      {
1610          $user_id=$_user['user_id'];
1611      }
1612  
1613      // the table where the last tool access is stored (=track_e_lastaccess)
1614      $table_last_access=Database::get_statistic_table('track_e_lastaccess');
1615  
1616      $sql="SELECT access_date FROM $table_last_access WHERE access_user_id='".Database::escape_string($user_id)."'
1617                  AND access_cours_code='".Database::escape_string($course_code)."'
1618                  AND access_tool='".Database::escape_string($tool)."'
1619                  ORDER BY access_date DESC
1620                  LIMIT 1";
1621      $result=Database::query($sql,__FILE__,__LINE__);
1622      $row=Database::fetch_array($result);
1623      return $row['access_date'];
1624  }
1625  function create_thumbnail($image,$thumbnail_width,$thumbnail_height)
1626  {
1627          $img = imagecreatefrompng($image);
1628          $width = imagesx( $img );
1629          $height = imagesy( $img );
1630  
1631         // create a new temporary image
1632          $tmp_img = imagecreatetruecolor( $thumbnail_width, $thumbnail_height );
1633        
1634         // copy and resize old image into new image
1635         imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $width, $height );
1636  
1637         // save thumbnail into a file
1638         imagepng( $tmp_img, $image );
1639  }
1640  
1641  /**
1642   * Checkf if user is allowed to download the file
1643   */
1644  
1645  function check_if_user_is_allowed_to_download_file ($file_id, $user_id) {
1646    $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY);
1647    $allowed_to_download=false;
1648    $sql = "SELECT * FROM ".$propTable." WHERE ref='".Database::escape_string($file_id)."' AND (insert_user_id = '".Database::escape_string($user_id)."' OR to_user_id = '".Database::escape_string($user_id)."')";
1649    $result=Database::query($sql);
1650    if (Database::num_rows($result)>0) {
1651        $allowed_to_download=true;
1652    }
1653    return $allowed_to_download;
1654  }

title

Description

title

Description

title

Description

title

title

Body