Dokeos PHP Cross Reference Learning Management Systems

Source: /main/link/linkfunctions.php - 930 lines - 37275 bytes - Summary - Text - Print

Description: Function library for the links tool. This is a complete remake of the original link tool. New features: - Organize links into categories; - favorites/bookmarks interface; - move links up/down within a category; - move categories up/down; - expand/collapse all categories; - add link to 'root' category => category-less link is always visible.

   1  <?php
   2  /*
   3  ==============================================================================
   4      Dokeos - elearning and course management software
   5  
   6      Copyright (c) 2004-2008 Dokeos S.A.
   7      Copyright (c) 2003 Ghent University (UGent)
   8      Copyright (c) 2001 Universite catholique de Louvain (UCL)
   9  
  10      For a full list of contributors, see "credits.txt".
  11      The full license can be read in "license.txt".
  12  
  13      This program is free software; you can redistribute it and/or
  14      modify it under the terms of the GNU General Public License
  15      as published by the Free Software Foundation; either version 2
  16      of the License, or (at your option) any later version.
  17  
  18      See the GNU General Public License for more details.
  19  
  20      Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
  21      Mail: info@dokeos.com
  22  ==============================================================================
  23  */
  24  /**
  25  ==============================================================================
  26  * Function library for the links tool.
  27  *
  28  * This is a complete remake of the original link tool.
  29  * New features:
  30  * - Organize links into categories;
  31  * - favorites/bookmarks interface;
  32  * - move links up/down within a category;
  33  * - move categories up/down;
  34  * - expand/collapse all categories;
  35  * - add link to 'root' category => category-less link is always visible.
  36  *
  37  *    @author Patrick Cool, complete remake (December 2003 - January 2004)
  38  *    @author Rene Haentjens, CSV file import (October 2004)
  39  *    @package dokeos.link
  40  ==============================================================================
  41  */
  42  
  43  /*
  44  ==============================================================================
  45          FUNCTIONS
  46  ==============================================================================
  47  */
  48  
  49  /**
  50  * Used to add a link or a category
  51  * @param string $type, "link" or "category"
  52  * @todo replace strings by constants
  53  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  54  */
  55  function addlinkcategory($type)
  56  {
  57      global $catlinkstatus;
  58      global $msgErr;
  59  
  60      $ok = true;
  61  
  62      if ($type == "link")
  63      {
  64          $tbl_link = Database :: get_course_table(TABLE_LINK);
  65  
  66          $title = Security::remove_XSS($_POST['title']);
  67          $urllink = Security::remove_XSS($_POST['urllink']);
  68          $description = Security::remove_XSS($_POST['description']);
  69          $selectcategory = Security::remove_XSS($_POST['selectcategory']);
  70  
  71          if ($_POST['onhomepage'] == '') {
  72              $onhomepage = 0;
  73              $target='_self';//default target
  74          } else {
  75              $onhomepage = Security::remove_XSS($_POST['onhomepage']);
  76              $target = Security::remove_XSS($_POST['target_link']);
  77          }
  78  
  79          $urllink = trim($urllink);
  80          $title = trim($title);
  81          $description = trim($description);
  82  
  83          // if title is empty, an error occurs
  84          if (empty ($urllink) OR $urllink == 'http://')
  85          {
  86              $msgErr = get_lang('GiveURL');
  87  
  88              Display::display_error_message(get_lang('GiveURL'));
  89  
  90              $ok = false;
  91          }
  92          // if the title is empty, we use the url as the title
  93          else
  94          {
  95              if (empty ($title))
  96              {
  97                  $title = $urllink;
  98              }
  99  
 100              // we check weither the $url starts with http://, if not we add this
 101              if (!strstr($urllink, '://'))
 102              {
 103                  $urllink = "http://".$urllink;
 104              }
 105  
 106              // looking for the largest order number for this category
 107              $result = Database::query("SELECT MAX(display_order) FROM  ".$tbl_link." WHERE category_id='".Database::escape_string($_POST['selectcategory'])."'");
 108  
 109              list ($orderMax) = Database::fetch_row($result);
 110  
 111              $order = $orderMax +1;
 112  
 113              $session_id = api_get_session_id();
 114  
 115              $sql = "INSERT INTO ".$tbl_link." (url, title, description, category_id, display_order, on_homepage, target, session_id)
 116      VALUES ('".Database::escape_string($urllink)."','".Database::escape_string($title)."',
 117     '".Database::escape_string($description)."','".Database::escape_string($selectcategory)."',
 118      '".Database::escape_string($order)."', '".Database::escape_string($onhomepage)."',
 119     '".Database::escape_string($target)."','$session_id')";
 120              $catlinkstatus = get_lang('LinkAdded');
 121  
 122              Database::query($sql, __FILE__, __LINE__);
 123              $link_id = Database::insert_id();
 124  
 125              if (isset($_SESSION['oLP']) && $link_id > 0) {            
 126                // Get the previous item ID
 127                $parent = 0;
 128                $previous = $_SESSION['oLP']->select_previous_item_id();
 129                // Add quiz as Lp Item
 130                $_SESSION['oLP']->add_item($parent, $previous, TOOL_LINK, $link_id, $title, '');
 131              }
 132  
 133              if ( (api_get_setting('search_enabled')=='true') && $link_id && extension_loaded('xapian')) {
 134                  require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
 135                  require_once(api_get_path(LIBRARY_PATH) .'search/IndexableChunk.class.php');
 136                  require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
 137  
 138                  $courseid = api_get_course_id();
 139                  $specific_fields = get_specific_field_list();
 140                  $ic_slide = new IndexableChunk();
 141  
 142                  // add all terms to db
 143                  /*$all_specific_terms = '';
 144                  foreach ($specific_fields as $specific_field) {
 145                      if (isset($_REQUEST[$specific_field['code']])) {
 146                          $sterms = trim($_REQUEST[$specific_field['code']]);
 147                          if (!empty($sterms)) {
 148                              $all_specific_terms .= ' '. $sterms;
 149                              $sterms = explode(',', $sterms);
 150                              foreach ($sterms as $sterm) {
 151                                  $ic_slide->addTerm(trim($sterm), $specific_field['code']);
 152                                  add_specific_field_value($specific_field['id'], $courseid, TOOL_LINK, $link_id, $sterm);
 153                              }
 154                          }
 155                      }
 156                  }*/
 157  
 158                  // build the chunk to index
 159                  $ic_slide->addValue("title", $title);
 160                  $ic_slide->addCourseId($courseid);
 161                  $ic_slide->addToolId(TOOL_LINK);
 162                  $xapian_data = array(
 163                      SE_COURSE_ID => $courseid,
 164                      SE_TOOL_ID => TOOL_LINK,
 165                      SE_DATA => array('link_id' => (int)$link_id),
 166                      SE_USER => (int)api_get_user_id(),
 167                  );
 168                  $ic_slide->xapian_data = serialize($xapian_data);
 169                  $description = $description;
 170                  $ic_slide->addValue("content", $description);
 171  
 172                  // add category name if set
 173                  if (isset($_POST['selectcategory']) && $selectcategory>0) {
 174                      $table_link_category = Database::get_course_table(TABLE_LINK_CATEGORY);
 175                      $sql_cat = 'SELECT * FROM %s WHERE id=%d LIMIT 1';
 176                      $sql_cat = sprintf($sql_cat, $table_link_category, (int)$selectcategory);
 177                      $result = Database::query($sql_cat, __FILE__, __LINE__);
 178                      if (Database::num_rows($result) == 1) {
 179                          $row = Database::fetch_array($result);
 180                          $ic_slide->addValue("category", $row['category_title']);
 181                      }
 182                  }
 183  
 184                  $di = new DokeosIndexer();
 185                  isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
 186                  $di->connectDb(NULL, NULL, $lang);
 187                  $di->addChunk($ic_slide);
 188  
 189                  //index and return search engine document id
 190                  $did = $di->index();
 191                  if ($did) {
 192                      // save it to db
 193                      $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
 194                      $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
 195                          VALUES (NULL , \'%s\', \'%s\', %s, %s)';
 196                      $sql = sprintf($sql, $tbl_se_ref, $courseid, TOOL_LINK, $link_id, $did);
 197                      Database::query($sql,__FILE__,__LINE__);
 198                  }
 199  
 200              }
 201  
 202              unset ($urllink, $title, $description, $selectcategory);
 203  
 204              Display::display_confirmation_message(get_lang('LinkAdded'));
 205          }
 206      } elseif ($type == "category") {
 207          $tbl_categories = Database :: get_course_table(TABLE_LINK_CATEGORY);
 208  
 209          $category_title = trim($_POST['category_title']);
 210          $description = trim($_POST['description']);
 211  
 212          if (empty ($category_title)) {
 213              $msgErr = get_lang('GiveCategoryName');
 214  
 215              Display::display_error_message(get_lang('GiveCategoryName'));
 216  
 217              $ok = false;
 218          } else {
 219              // looking for the largest order number for this category
 220              $result = Database::query("SELECT MAX(display_order) FROM  ".$tbl_categories."");
 221  
 222              list ($orderMax) = Database::fetch_row($result);
 223  
 224              $order = $orderMax +1;
 225  
 226              $session_id = api_get_session_id();
 227  
 228              $sql = "INSERT INTO ".$tbl_categories." (category_title, description, display_order, session_id) VALUES ('".Database::escape_string(Security::remove_XSS($category_title))."','".Database::escape_string(Security::remove_XSS($description))."', '$order', '$session_id')";
 229              Database::query($sql, __FILE__, __LINE__);
 230  
 231              $catlinkstatus = get_lang('CategoryAdded');
 232  
 233              unset ($category_title, $description);
 234  
 235              Display::display_confirmation_message(get_lang('CategoryAdded'));
 236          }
 237      }
 238  
 239      // "WHAT'S NEW" notification : update last tool Edit
 240      if ($type == "link")
 241      {
 242          global $_user;
 243          global $_course;
 244          global $nameTools;
 245  
 246          api_item_property_update($_course, TOOL_LINK, $link_id, "LinkAdded", $_user['user_id']);
 247      }
 248  
 249      return $ok;
 250  }
 251  // End of the function addlinkcategory
 252  
 253  /**
 254  * Used to delete a link or a category
 255  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 256  */
 257  function deletelinkcategory($type)
 258  {
 259      global $catlinkstatus;
 260      global $_course;
 261      global $_user;
 262      $tbl_link = Database :: get_course_table(TABLE_LINK);
 263      $tbl_categories = Database :: get_course_table(TABLE_LINK_CATEGORY);
 264      $TABLE_ITEM_PROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 265  
 266      if ($type == "link")
 267      {
 268          global $id;
 269          // -> items are no longer fysically deleted, but the visibility is set to 2 (in item_property). This will
 270          // make a restore function possible for the platform administrator
 271          if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
 272              $sql="UPDATE $tbl_link SET on_homepage='0' WHERE id='".Database::escape_string($_GET['id'])."'";
 273              Database::query($sql,__FILE__,__LINE__);
 274          }
 275  
 276          api_item_property_update($_course, TOOL_LINK, $id, "delete", $_user['user_id']);
 277          delete_link_from_search_engine(api_get_course_id(), $id);
 278          $catlinkstatus = get_lang("LinkDeleted");
 279          unset ($id);
 280  
 281          Display::display_confirmation_message(get_lang('LinkDeleted'));
 282      }
 283      if ($type == "category")
 284      {
 285          global $id;
 286  
 287          // first we delete the category itself and afterwards all the links of this category.
 288          $sql = "DELETE FROM ".$tbl_categories." WHERE id='".Database::escape_string(Security::remove_XSS($_GET['id']))."'";
 289          Database::query($sql, __FILE__, __LINE__);
 290          $sql = "DELETE FROM ".$tbl_link." WHERE category_id='".Database::escape_string(Security::remove_XSS($_GET['id']))."'";
 291          $catlinkstatus = get_lang('CategoryDeleted');
 292          unset ($id);
 293          Database::query($sql, __FILE__, __LINE__);
 294  
 295          Display::display_confirmation_message(get_lang('CategoryDeleted'));
 296      }
 297  }
 298  
 299  /**
 300   * Removes a link from search engine database
 301   *
 302   * @param string $course_id Course code
 303   * @param int $document_id Document id to delete
 304   */
 305  function delete_link_from_search_engine($course_id, $link_id) {
 306      // remove from search engine if enabled
 307      if (api_get_setting('search_enabled') == 'true') {
 308          $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
 309          $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
 310          $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $link_id);
 311          $res = Database::query($sql, __FILE__, __LINE__);
 312          if (Database::num_rows($res) > 0) {
 313              $row = Database::fetch_array($res);
 314              require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
 315              $di = new DokeosIndexer();
 316              $di->remove_document((int)$row['search_did']);
 317          }
 318          $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
 319          $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $link_id);
 320          Database::query($sql, __FILE__, __LINE__);
 321  
 322          // remove terms from db
 323          require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
 324          delete_all_values_for_item($course_id, TOOL_DOCUMENT, $link_id);
 325      }
 326  }
 327  
 328  
 329  /**
 330  * Used to edit a link or a category
 331  * @todo rewrite the whole links tool because it is becoming completely cluttered,
 332  *         code does not follow the coding conventions, does not use html_quickform, ...
 333  *         some features were patched in
 334  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 335  * @todo replace the globals with the appropriate $_POST or $_GET values
 336  */
 337  function editlinkcategory($type)
 338  {
 339      global $catlinkstatus;
 340      global $id;
 341      global $submitLink;
 342      global $submitCategory;
 343      global $_user;
 344      global $_course;
 345      global $nameTools;
 346      global $urllink;
 347      global $title;
 348      global $description;
 349      global $category;
 350      global $selectcategory;
 351      global $description;
 352      global $category_title;
 353      global $onhomepage;
 354  
 355      $tbl_link         = Database :: get_course_table(TABLE_LINK);
 356      $tbl_categories = Database :: get_course_table(TABLE_LINK_CATEGORY);
 357  
 358      if ($type == "link")
 359      {
 360          // this is used to populate the link-form with the info found in the database
 361          $sql = "SELECT * FROM ".$tbl_link." WHERE id='".$_GET['id']."'";
 362          $result = Database::query($sql, __FILE__, __LINE__);
 363          if ($myrow = Database::fetch_array($result))
 364          {
 365              $urllink = $myrow["url"];
 366              $title = $myrow["title"];
 367              $description = $myrow["description"];
 368              $category = $myrow["category_id"];
 369              if ($myrow["on_homepage"] <> 0)
 370              {
 371                  $onhomepage = "checked";
 372              }
 373          }
 374          // this is used to put the modified info of the link-form into the database
 375          if ($_POST['submitLink'])
 376          {
 377              if ($_POST['onhomepage'] == '') {
 378                  $onhomepage = 0;
 379                  $mytarget='';
 380              } else {
 381                  $onhomepage = Security::remove_XSS($_POST['onhomepage']);
 382                  $target = Security::remove_XSS($_POST['target_link']);
 383                  $mytarget=",target='".$target."'";
 384              }
 385  
 386              // finding the old category_id
 387              $sql = "SELECT * FROM ".$tbl_link." WHERE id='".Database::escape_string(Security::remove_XSS($_POST['id']))."'";
 388              $result = Database::query($sql, __FILE__, __LINE__);
 389              $row = Database::fetch_array($result);
 390              $category_id = $row['category_id'];
 391  
 392              if ($category_id <> $_POST['selectcategory']) {
 393                  $sql = "SELECT MAX(display_order) FROM ".$tbl_link." WHERE category_id='".$_POST['selectcategory']."'";
 394                  $result = Database::query($sql);
 395                  list ($max_display_order) = Database::fetch_row($result);
 396                  $max_display_order ++;
 397              } else {
 398                  $max_display_order = $row['display_order'];
 399              }
 400  
 401              $sql = "UPDATE ".$tbl_link." set url='".Database::escape_string(Security::remove_XSS($_POST['urllink']))."', title='".Database::escape_string(Security::remove_XSS($_POST['title']))."', description='".Database::escape_string(Security::remove_XSS($_POST['description']))."', category_id='".Database::escape_string(Security::remove_XSS($_POST['selectcategory']))."', display_order='".$max_display_order."', on_homepage='".Database::escape_string(Security::remove_XSS($onhomepage))." ' $mytarget WHERE id='".Database::escape_string(Security::remove_XSS($_POST['id']))."'";
 402              Database::query($sql, __FILE__, __LINE__);
 403  
 404              // update search enchine and its values table if enabled
 405              if (api_get_setting('search_enabled')=='true') {
 406                  $link_id = $_POST['id'];
 407                  $course_id = api_get_course_id();
 408                  $link_url = $_POST['urllink'];
 409                  $link_title = $_POST['title'];
 410                  $link_description = $_POST['description'];
 411  
 412                  // actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
 413                  // get search_did
 414                  $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
 415                  $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
 416                  $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $link_id);
 417                  $res = Database::query($sql, __FILE__, __LINE__);
 418  
 419                  if (Database::num_rows($res) > 0) {
 420                      require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
 421                      require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
 422                      require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
 423  
 424                      $se_ref = Database::fetch_array($res);
 425                      $specific_fields = get_specific_field_list();
 426                      $ic_slide = new IndexableChunk();
 427  
 428                      $all_specific_terms = '';
 429                      foreach ($specific_fields as $specific_field) {
 430                          delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_LINK, $link_id);
 431                          if (isset($_REQUEST[$specific_field['code']])) {
 432                              $sterms = trim($_REQUEST[$specific_field['code']]);
 433                              if (!empty($sterms)) {
 434                                  $all_specific_terms .= ' '. $sterms;
 435                                  $sterms = explode(',', $sterms);
 436                                  foreach ($sterms as $sterm) {
 437                                      $ic_slide->addTerm(trim($sterm), $specific_field['code']);
 438                                      add_specific_field_value($specific_field['id'], $course_id, TOOL_LINK, $link_id, $sterm);
 439                                  }
 440                              }
 441                          }
 442                      }
 443  
 444                      // build the chunk to index
 445                      $ic_slide->addValue("title", $link_title);
 446                      $ic_slide->addCourseId($course_id);
 447                      $ic_slide->addToolId(TOOL_LINK);
 448                      $xapian_data = array(
 449                          SE_COURSE_ID => $course_id,
 450                          SE_TOOL_ID => TOOL_LINK,
 451                          SE_DATA => array('link_id' => (int)$link_id),
 452                          SE_USER => (int)api_get_user_id(),
 453                      );
 454                      $ic_slide->xapian_data = serialize($xapian_data);
 455                      $link_description = $all_specific_terms .' '. $link_description;
 456                      $ic_slide->addValue("content", $link_description);
 457  
 458                      // add category name if set
 459                      if (isset($_POST['selectcategory']) && $selectcategory>0) {
 460                          $table_link_category = Database::get_course_table(TABLE_LINK_CATEGORY);
 461                          $sql_cat = 'SELECT * FROM %s WHERE id=%d LIMIT 1';
 462                          $sql_cat = sprintf($sql_cat, $table_link_category, (int)$selectcategory);
 463                          $result = Database::query($sql_cat, __FILE__, __LINE__);
 464                          if (Database::num_rows($result) == 1) {
 465                              $row = Database::fetch_array($result);
 466                              $ic_slide->addValue("category", $row['category_title']);
 467                          }
 468                      }
 469  
 470                      $di = new DokeosIndexer();
 471                      isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
 472                      $di->connectDb(NULL, NULL, $lang);
 473                      $di->remove_document((int)$se_ref['search_did']);
 474                      $di->addChunk($ic_slide);
 475  
 476                      //index and return search engine document id
 477                      $did = $di->index();
 478                      if ($did) {
 479                          // save it to db
 480                          $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
 481                          $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $link_id);
 482                          Database::query($sql,__FILE__,__LINE__);
 483                          //var_dump($sql);
 484                          $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
 485                              VALUES (NULL , \'%s\', \'%s\', %s, %s)';
 486                          $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $link_id, $did);
 487                          Database::query($sql,__FILE__,__LINE__);
 488                      }
 489  
 490                  }
 491              }
 492  
 493              // "WHAT'S NEW" notification: update table last_toolEdit
 494              api_item_property_update($_course, TOOL_LINK, $_POST['id'], "LinkUpdated", $_user['user_id']);
 495  
 496              Display::display_confirmation_message(get_lang('LinkModded'));
 497          }
 498      }
 499      if ($type == "category")
 500      {
 501          // this is used to populate the category-form with the info found in the database
 502          if (!$submitCategory)
 503          {
 504              $sql = "SELECT * FROM ".$tbl_categories." WHERE id='".$_GET['id']."'";
 505              $result = Database::query($sql, __FILE__, __LINE__);
 506              if ($myrow = Database::fetch_array($result))
 507              {
 508                  $category_title = $myrow["category_title"];
 509                  $description = $myrow["description"];
 510              }
 511          }
 512          // this is used to put the modified info of the category-form into the database
 513          if ($submitCategory)
 514          {
 515              $sql = "UPDATE ".$tbl_categories." set category_title='".Database::escape_string(Security::remove_XSS($_POST['category_title']))."', description='".Database::escape_string(Security::remove_XSS($_POST['description']))."' WHERE id='".Database::escape_string(Security::remove_XSS($_POST['id']))."'";
 516              Database::query($sql, __FILE__, __LINE__);
 517              Display::display_confirmation_message(get_lang('CategoryModded'));
 518          }
 519  
 520  
 521      }
 522  }
 523  // END of function editlinkcat
 524  
 525  /**
 526  * creates a correct $view for in the URL
 527  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 528  */
 529  function makedefaultviewcode($locatie)
 530  {
 531      global $aantalcategories;
 532      global $view;
 533  
 534      for ($j = 0; $j <= $aantalcategories -1; $j ++)
 535      {
 536          $view[$j] = 0;
 537      }
 538      $view[intval($locatie)] = "1";
 539  }
 540  // END of function makedefaultviewcode
 541  
 542  /**
 543  * changes the visibility of a link
 544  * @todo add the changing of the visibility of a course
 545  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 546  */
 547  function change_visibility($id, $scope)
 548  {
 549      global $_course;
 550      global $_user;
 551      $TABLE_ITEM_PROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 552  
 553      if ($scope == "link")
 554      {
 555          $sqlselect = "SELECT * FROM $TABLE_ITEM_PROPERTY WHERE tool='".TOOL_LINK."' and ref='".Database::escape_string($id)."'";
 556          $result = Database::query($sqlselect);
 557          $row = Database::fetch_array($result);
 558          api_item_property_update($_course, TOOL_LINK, $id, $_GET['action'], $_user['user_id']);
 559      }
 560  
 561      Display::display_confirmation_message(get_lang('VisibilityChanged'));
 562  }
 563  
 564  /**
 565  * displays all the links of a given category.
 566  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 567  */
 568  function showlinksofcategory($catid)
 569  {
 570      global $is_allowed, $charset, $urlview, $up, $down, $_user, $linkCounter;
 571      $tbl_link = Database :: get_course_table(TABLE_LINK);
 572  
 573      $TABLE_ITEM_PROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 574  
 575      //condition for the session
 576      $session_id = api_get_session_id();
 577      $condition_session = api_get_session_condition($session_id);
 578  
 579      $sqlLinks = "SELECT * FROM ".$tbl_link." link, ".$TABLE_ITEM_PROPERTY." itemproperties WHERE itemproperties.tool='".TOOL_LINK."' AND link.id=itemproperties.ref AND  link.category_id='".$catid."' AND (itemproperties.visibility='0' OR itemproperties.visibility='1') $condition_session ORDER BY link.display_order DESC";
 580      $result = Database::query($sqlLinks);
 581      $numberoflinks = Database::num_rows($result);
 582      
 583      if($numberoflinks > 0)
 584      {
 585  //    echo '<table class="data_table" width="100%">';
 586      echo '<div id="contentWrap"><div id="contentLeft"><ul style="min-height: 10px;" class="dragdrop nobullets category_'.$catid.'">';
 587      $i = 1;
 588          while ($myrow = Database::fetch_array($result)) {
 589              //validacion when belongs to a session
 590              $session_img = api_get_session_image($myrow['session_id'], $_user['status']);
 591      
 592              if($i%2==0) $css_class = 'row_odd';
 593              else $css_class = 'row_even';
 594      
 595              $myrow[3] = text_filter($myrow[3]);
 596              
 597              $paddingLeftSubLinks = ""; 
 598              if($catid != "0"){
 599                  $paddingLeftSubLinks = "padding-left: 0px;";
 600              }
 601              $drag = 'move1';
 602              if ($myrow['visibility'] == '1')
 603              {
 604                  $draggable_class = api_is_allowed_to_edit() ? 'draggable' : '';
 605                  echo "<li id='recordsArray_".$myrow[0]."' class='$drag'>
 606                          <table class='data_table' width='100%'>
 607                              <tr class='".$css_class."'>";
 608                  if (api_is_allowed_to_edit ()) {
 609                    echo "<td align=\"left\" valign=\"center\" width=\"6%\" class='$draggable_class'>
 610                        ".Display::return_icon('pixel.gif', null, array('class' => 'actionplaceholdericon actionsdraganddrop'))."
 611                    </td>";
 612                  }
 613                  if(! api_is_allowed_to_edit(null,true)){
 614  
 615                      echo "<td class='nodrag' width=\"94%\" align=\"left\" valign=\"top\">";
 616                  }
 617                  else{
 618                      if($catid == 0)
 619                      {
 620                      echo "<td class='nodrag' width=\"54%\" align=\"left\" style=\"".$paddingLeftSubLinks."\" valign=\"bottom\">";
 621                      }
 622                      else
 623                      {
 624                      echo "<td class='nodrag' width=\"52%\" align=\"left\" style=\"".$paddingLeftSubLinks."\" valign=\"bottom\">";
 625                      }
 626                  }
 627                  echo "<a href=\"link_goto.php?".api_get_cidreq()."&link_id=".$myrow[0]."&amp;link_url=".urlencode($myrow[1])."\" target=\"_blank\">".api_htmlentities($myrow[2],ENT_QUOTES,$charset)."</a>".$session_img."<br/>".$myrow[3]."
 628                  </td>";
 629              }
 630              else
 631              {
 632                  if (api_is_allowed_to_edit(null,true))
 633                  {
 634                      echo "<li id='recordsArray_".$myrow[0]."' class='draggable $drag'>
 635                              <table class='data_table' width='100%'>
 636                                  <tr class='".$css_class."'>
 637                                      <td align=\"left\" valign=\"top\" width=\"6%\">
 638                                          ".Display::return_icon('pixel.gif', null, array('class' => 'actionplaceholdericon actionsdraganddrop'))."<span style='display: inline-block; margin-top: 5px;margin-left: 2px;'>".$linkCounter."</span>.
 639                                      </td>
 640                                      <td class='nodrag' width=\"54%\" align=\"left\" style=\"".$paddingLeftSubLinks."\" valign=\"top\">
 641                                          <a href=\"link_goto.php?".api_get_cidreq()."&link_id=".$myrow[0]."&amp;link_url=".urlencode($myrow[1])."\" target=\"_blank\"  class=\"invisible\">".api_htmlentities($myrow[2],ENT_QUOTES,$charset)."</a>\n", $session_img , "<br />", $myrow[3]."
 642                                      </td>";
 643                  }
 644              }
 645      
 646              if (api_is_allowed_to_edit(null,true))
 647              {
 648                  echo '<td class="nodrag" style="text-align:center; width: 10%;">';
 649                      echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=editlink&amp;category=".(!empty($category)?$category:'')."&amp;id=".$myrow[0]." &amp;urlview=$urlview \"  title=\"".get_lang('Modify')."\"  >", Display::return_icon('pixel.gif', get_lang('Modify'), array('class' => 'actionplaceholdericon actionedit')), "</a>";
 650                  echo '</td>';
 651                  echo '<td class="nodrag" style="text-align:center; width: 10%;">';
 652                      echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=deletelink&amp;id=", $myrow[0], "&amp;urlview=", $urlview, "\" onclick=\"javascript:if(!confirm('".get_lang('LinkDelconfirm')."')) return false;\"  title=\"".get_lang('Delete')."\" >", Display::return_icon('pixel.gif', get_lang('Delete'), array('class' => 'actionplaceholdericon actiondelete')), "</a>";
 653                  echo '</td>';
 654                  echo '<td class="nodrag" style="text-align:center; width: 10%;">';
 655                      if ($myrow['visibility'] == "1")
 656                      {
 657                          echo '<a href="link.php?'.api_get_cidreq().'&action=invisible&amp;id='.$myrow['id'].'&amp;scope=link&amp;urlview='.$urlview.'" title="'.get_lang('Hide').'">'.Display::return_icon('pixel.gif', get_lang('Hide'), array('class' => 'actionplaceholdericon actionvisible')).'</a>';
 658                      }
 659                      if ($myrow['visibility'] == "0")
 660                      {
 661                           echo '<a href="link.php?'.api_get_cidreq().'&action=visible&amp;id='.$myrow['id'].'&amp;scope=link&amp;urlview='.$urlview.'" title="'.get_lang('Show').'">'.Display::return_icon('pixel.gif', get_lang('Show'), array('class' => 'actionplaceholdericon actioninvisible')).'</a>';
 662                      }
 663                  echo '</td>';
 664                  echo '<td class="nodrag" style="text-align:center; width: 10%;">';
 665                      echo '<a class="thickbox" href="integrate_link_in_course.php?linkId='.$myrow[0].'&urlview='.$urlview.api_get_cidreq().'&height=180&width=500" title="'.get_lang('IntegrateLinkInCourse').'">'.Display::return_icon('pixel.gif', get_lang('IntegrateLinkInCourse'), array('class' => 'actionplaceholdericon actioncourseadd')).'</a>';
 666                  echo '</td>';
 667              }
 668              echo '</td>';
 669              echo '</tr></table></li>';
 670              $i ++;
 671              $linkCounter++;
 672          }
 673      echo '</ul></div></div>';
 674      }else{ //End for the loop if number of link > 0
 675              echo '<div id="contentWrap"><div id="contentLeft"><ul style="min-height: 10px;" class="dragdrop nobullets category_'.$catid.'">';
 676              echo get_lang('ThereAreNoLinksInThisFolder');//There are no links in this folder
 677              echo '<br/><br/></ul></div></div>';
 678          }
 679  }
 680  
 681  /**
 682  * displays the edit, delete and move icons
 683  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 684  */
 685  function showcategoryadmintools($categoryid)
 686  {
 687      global $urlview;
 688      global $aantalcategories;
 689      global $catcounter;
 690      echo '<th style="text-align:center; width: 10%;padding-right: 0px; vertical-align: top;"><a href="'.api_get_self().'?'.api_get_cidreq().'&action=editcategory&amp;id='.$categoryid.'&amp;urlview='.$urlview.'"  title="'.get_lang('Modify').' ">'.Display::return_icon('pixel.gif',get_lang('Modify'),array('class'=>'actionplaceholdericon actionedit','border'=>'0','align'=>'top')).'</a></th>';
 691      echo "<th style='text-align:center; width: 10%;padding-right: 0px; vertical-align: top;'><a href=\"".api_get_self()."?".api_get_cidreq()."&action=deletecategory&amp;id=", $categoryid, "&amp;urlview=$urlview\" onclick=\"javascript:if(!confirm('".get_lang('CategoryDelconfirm')."')) return false;\">&nbsp;&nbsp;",Display::return_icon('pixel.gif',get_lang('Delete'),array('class'=>'actionplaceholdericon actiondelete','border'=>'0','alt'=>'','align'=>'top')), "</a></th>";
 692      $catcounter ++;
 693  }
 694  
 695  /**
 696  * move a link or a linkcategory up or down
 697  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 698  */
 699  function movecatlink($catlinkid)
 700  {
 701      global $catmove;
 702      global $up;
 703      global $down;
 704      $tbl_link = Database :: get_course_table(TABLE_LINK);
 705      $tbl_categories = Database :: get_course_table(TABLE_LINK_CATEGORY);
 706  
 707      if (!empty($_GET['down']))
 708      {
 709          $thiscatlinkId = $_GET['down'];
 710          $sortDirection = "DESC";
 711      }
 712      if (!empty($_GET['up']))
 713      {
 714          $thiscatlinkId = Security::remove_XSS($_GET['up']);
 715          $sortDirection = "ASC";
 716      }
 717  
 718      // We check if it is a category we are moving or a link. If it is a category, a querystring catmove = true is present in the url
 719      if ($catmove == "true")
 720      {
 721          $movetable = $tbl_categories;
 722          $catid = $catlinkid;
 723      }
 724      else
 725      {
 726          $movetable = $tbl_link;
 727          //getting the category of the link
 728          if(!empty($thiscatlinkId))
 729          {
 730              $sql = "SELECT category_id from ".$movetable." WHERE id='$thiscatlinkId'";
 731              $result = Database::query($sql, __FILE__, __LINE__);
 732              $catid = Database::fetch_array($result);
 733          }
 734      }
 735  
 736      // this code is copied and modified from announcements.php
 737      if (!empty($sortDirection))
 738      {
 739          if (!in_array(trim(strtoupper($sortDirection)), array ('ASC', 'DESC')))
 740              die("Bad sort direction used."); //sanity check of sortDirection var
 741          if ($catmove == "true")
 742          {
 743              $sqlcatlinks = "SELECT id, display_order FROM ".$movetable." ORDER BY display_order $sortDirection";
 744          }
 745          else
 746          {
 747              $sqlcatlinks = "SELECT id, display_order FROM ".$movetable." WHERE category_id='".$catid[0]."' ORDER BY display_order $sortDirection";
 748          }
 749          $linkresult = Database::query($sqlcatlinks);
 750          while ($sortrow = Database::fetch_array($linkresult))
 751          {
 752              // STEP 2 : FOUND THE NEXT ANNOUNCEMENT ID AND ORDER, COMMIT SWAP
 753              // This part seems unlogic, but it isn't . We first look for the current link with the querystring ID
 754              // and we know the next iteration of the while loop is the next one. These should be swapped.
 755              if (isset ($thislinkFound) && $thislinkFound == true)
 756              {
 757                  $nextlinkId = $sortrow["id"];
 758                  $nextlinkOrdre = $sortrow["display_order"];
 759  
 760                  Database::query("UPDATE ".$movetable."
 761                                           SET display_order = '$nextlinkOrdre'
 762                                           WHERE id =  '$thiscatlinkId'");
 763  
 764                  Database::query("UPDATE ".$movetable."
 765                                           SET display_order = '$thislinkOrdre'
 766                                           WHERE id =  '$nextlinkId'");
 767  
 768                  break;
 769              }
 770  
 771              if ($sortrow["id"] == $thiscatlinkId)
 772              {
 773                  $thislinkOrdre = $sortrow["display_order"];
 774                  $thislinkFound = true;
 775              }
 776          }
 777      }
 778  
 779      Display::display_confirmation_message(get_lang('LinkMoved'));
 780  }
 781  
 782  /**
 783  * CSV file import functions
 784  * @author Rene Haentjens , Ghent University
 785  */
 786  function get_cat($catname) // get category id (existing or make new)
 787  {
 788      $tbl_categories = Database :: get_course_table(TABLE_LINK_CATEGORY);
 789  
 790      $result = Database::query("SELECT `id` FROM ".$tbl_categories." WHERE `category_title`='".addslashes($catname)."'", __FILE__, __LINE__);
 791  
 792      if (Database::num_rows($result) >= 1 && ($row = Database::fetch_array($result)))
 793          return $row['id']; // several categories with same name: take first
 794  
 795      $result = Database::query("SELECT MAX(display_order) FROM ".$tbl_categories."", __FILE__, __LINE__);
 796      list ($max_order) = Database::fetch_row($result);
 797  
 798      Database::query("INSERT INTO ".$tbl_categories." (category_title, description, display_order) VALUES ('".addslashes($catname)."','','". ($max_order +1)."')", __FILE__, __LINE__);
 799  
 800      return Database::insert_id();
 801  }
 802  /**
 803  * CSV file import functions
 804  * @author Rene Haentjens , Ghent University
 805  */
 806  function put_link($url, $cat, $title, $description, $on_homepage, $hidden)
 807  {
 808      $tbl_link = Database :: get_course_table(TABLE_LINK);
 809  
 810      $urleq = "url='".addslashes($url)."'";
 811      $cateq = "category_id=".$cat;
 812  
 813      $result = Database::query("SELECT id FROM $tbl_link WHERE ".$urleq.' AND '.$cateq, __FILE__, __LINE__);
 814  
 815      if (Database::num_rows($result) >= 1 && ($row = Database::fetch_array($result)))
 816      {
 817          Database::query("UPDATE $tbl_link set title='".addslashes($title)."', description='".addslashes($description)."' WHERE id='".addslashes($id = $row['id'])."'", __FILE__, __LINE__);
 818  
 819          $lang_link = get_lang('update_link');
 820          $ipu = "LinkUpdated";
 821          $rv = 1; // 1= upd
 822      }
 823      else // add new link
 824          {
 825          $result = Database::query("SELECT MAX(display_order) FROM  $tbl_link WHERE category_id='".addslashes($cat)."'", __FILE__, __LINE__);
 826          list ($max_order) = Database::fetch_row($result);
 827  
 828          Database::query("INSERT INTO $tbl_link (url, title, description, category_id, display_order, on_homepage) VALUES ('".addslashes($url)."','".addslashes($title)."','".addslashes($description)."','".addslashes($cat)."','". ($max_order +1)."','".$on_homepage."')", __FILE__, __LINE__);
 829  
 830          $id = Database::insert_id();
 831          $lang_link = get_lang('new_link');
 832          $ipu = "LinkAdded";
 833          $rv = 2; // 2= new
 834      }
 835  
 836      global $_course, $nameTools, $_user;
 837      api_item_property_update($_course, TOOL_LINK, $id, $ipu, $_user['user_id']);
 838  
 839      if ($hidden && $ipu == "LinkAdded")
 840          api_item_property_update($_course, TOOL_LINK, $id, "invisible", $_user['user_id']);
 841  
 842      return $rv;
 843  }
 844  /**
 845  * CSV file import functions
 846  * @author Rene Haentjens , Ghent University
 847  */
 848  function import_link($linkdata) // url, category_id, title, description, ...
 849  {
 850      // field names used in the uploaded file
 851      $known_fields = array ('url', 'category', 'title', 'description', 'on_homepage', 'hidden');
 852      $hide_fields = array ('kw', 'kwd', 'kwds', 'keyword', 'keywords');
 853  
 854      // all other fields are added to description, as "name:value"
 855  
 856      // only one hide_field is assumed to be present, <> is removed from value
 857  
 858      if (!($url = trim($linkdata['url'])) || !($title = trim($linkdata['title'])))
 859          return 0; // 0= fail
 860  
 861      $cat = ($catname = trim($linkdata['category'])) ? get_cat($catname) : 0;
 862  
 863      $regs = array(); // will be passed to ereg()
 864      foreach ($linkdata as $key => $value)
 865          if (!in_array($key, $known_fields))
 866              if (in_array($key, $hide_fields) && ereg('^<?([^>]*)>?$', $value, $regs)) // possibly in <...>
 867                  if (($kwlist = trim($regs[1])) != '')
 868                      $kw = '<i kw="'.htmlspecialchars($kwlist).'">';
 869                  else
 870                      $kw = '';
 871      // i.e. assume only one of the $hide_fields will be present
 872      // and if found, hide the value as expando property of an <i> tag
 873      elseif (trim($value)) $d .= ', '.$key.':'.$value;
 874      if ($d)
 875          $d = substr($d, 2).' - ';
 876  
 877      return put_link($url, $cat, $title, $kw.ereg_replace('\[((/?(b|big|i|small|sub|sup|u))|br/)\]', '<\\1>', htmlspecialchars($d.$linkdata['description'])). ($kw ? '</i>' : ''), $linkdata['on_homepage'] ? '1' : '0', $linkdata['hidden'] ? '1' : '0');
 878      // i.e. allow some BBcode tags, e.g. [b]...[/b]
 879  }
 880  /**
 881  * CSV file import functions
 882  * @author Rene Haentjens , Ghent University
 883  */
 884  function import_csvfile()
 885  {
 886      global $catlinkstatus; // feedback message to user
 887  
 888      if (is_uploaded_file($filespec = $_FILES['import_file']['tmp_name']) && filesize($filespec) && ($myFile = @ fopen($filespec, 'r')))
 889      {
 890          // read first line of file (column names) and find ',' or ';'
 891          $listsep = strpos($colnames = trim(fgets($myFile)), ',') !== FALSE ? ',' : (strpos($colnames, ';') !== FALSE ? ';' : '');
 892  
 893          if ($listsep)
 894          {
 895              $columns = array_map('strtolower', explode($listsep, $colnames));
 896  
 897              if (in_array('url', $columns) && in_array('title', $columns))
 898              {
 899                  $stats = array (0, 0, 0); // fails, updates, inserts
 900  
 901                  while (($data = fgetcsv($myFile, 32768, $listsep)))
 902                  {
 903                      foreach ($data as $i => $text)
 904                          $linkdata[$columns[$i]] = $text;
 905                      //  $linkdata['url', 'title', ...]
 906  
 907                      $stats[import_link($linkdata)]++;
 908                      unset ($linkdata);
 909                  }
 910  
 911                  $catlinkstatus = '';
 912  
 913                  if ($stats[0])
 914                      $catlinkstatus .= $stats[0].' '.get_lang('CsvLinesFailed');
 915                  if ($stats[1])
 916                      $catlinkstatus .= $stats[1].' '.get_lang('CsvLinesOld');
 917                  if ($stats[2])
 918                      $catlinkstatus .= $stats[2].' '.get_lang('CsvLinesNew');
 919              }
 920              else
 921                  $catlinkstatus = get_lang('CsvFileNoURL'). ($colnames ? get_lang('CsvFileLine1').htmlspecialchars(substr($colnames, 0, 200)).'...' : '');
 922          }
 923          else
 924              $catlinkstatus = get_lang('CsvFileNoSeps'). ($colnames ? get_lang('CsvFileLine1').htmlspecialchars(substr($colnames, 0, 200)).'...' : '');
 925          fclose($myFile);
 926      }
 927      else
 928          $catlinkstatus = get_lang('CsvFileNotFound');
 929  }
 930  ?>

title

Description

title

Description

title

Description

title

title

Body