<?php

// Moodle2.0以降の場合はtrue, それ以前ならばfalseを返す
// fs_deprecatedlib.php中のMoodle2下位互換のためのデータベースアクセス用の関数でのみ使用
// もしかしたら$CFG->versionを閲覧できない時点で用いられているのかも知れないので，これはイジらない．
// というつもりだったが，JavaScript問題が発生したので構造を強化して用いる．
// だが，そもそも不要では？という気もする．以下，コードからは原則的に消えているはず．
function over_moodle20()
{
    global $CFG, $version, $release;
// Moodle2.5.2+(2013/10/18)あたりからJavaScriptが読み込まれない異常現象が発生し始めた原因はversion.phpをsetup.phpの段階で読み込んでしまうことによる
//  if ((empty($version) or empty($release)) and is_readable("$CFG->dirroot/version.php")) {
    if ((empty($CFG->version) or empty($CFG->release)) and is_readable("$CFG->dirroot/version.php")) {
        if (empty($version) or empty($release)) {
            include("$CFG->dirroot/version.php");              # defines $version
            if ($version >= 2007101600) return true;
            return false;
        }
    }
    if ($CFG->version >= 2007101600) return true;
    return false;
}

// Moodle2.0から変更になったデータベースへのアクセスに用いる関数
// lib/dmllib.php
// lib/dml/moodle_database.p
// over_moodle20() で$DBの使用の可否を調べていたが，この関数による副作用が発生してしまったので，
// 考え方を変えて，$DBがグローバル変数として定義されているかどうかで現状は判断する．
// 将来的に$DBにMoodle2と互換性のないバージョンが現れた場合に，その識別方法を考えなくてはいけない．


// function get_record($table, $field1, $value1, $field2='', $value2='', $field3='', $value3='', $fields='*')
// function get_record($table, array $conditions, $fields='*', $strictness=IGNORE_MISSING)
function fs_get_record($table, $field1, $value1, $field2='', $value2='', $field3='', $value3='', $fields='*')
{
    global $DB;
    if (!empty($DB)) {
        $conditions = array();

        $conditions[$field1] = $value1;
        if (!empty($field2)) $conditions[$field2] = $value2;
        if (!empty($field3)) $conditions[$filed3] = $value3;
        return $DB->get_record($table, $conditions, $fields);
    }
    return get_record($table, $field1, $value1, $field2, $value2, $field3, $value3, $fields);
}

// function get_records($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='')
// function get_records($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)
function fs_get_records($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='')
{
    global $DB;
    if (!empty($DB)) {
        $conditions = null;

        if (empty($limitfrom)) $limitfrom = 0;
        if (empty($limitnum))  $limitnum  = 0;
        if (!empty($field)) $conditions[$field] = $value;
        return $DB->get_records($table, $conditions, $sort, $fields, $limitfrom, $limitnum);
    }
    return get_records($table, $field, $value, $sort, $fields, $limitfrom, $limitnum);
}

// function get_records_select($table, $select='', $sort='', $fields='*', $limitfrom='', $limitnum='')
// function get_records_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)
function fs_get_records_select($table, $select='', $sort='', $fields='*', $limitfrom='', $limitnum='')
{
    global $DB;
    if (!empty($DB)) {
        if (empty($limitfrom)) $limitfrom = 0;
        if (empty($limitnum))  $limitnum  = 0;
        return $DB->get_records_select($table, $select, null, $sort, $fields, $limitfrom, $limitnum);
    }
    return get_records_select($table, $select, $sort, $fields, $limitfrom, $limitnum);
}

// function get_records_select_menu($table, $select='', $sort='', $fields='*', $limitfrom='', $limitnum='')
// function get_records_select_menu($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)
function fs_get_records_select_menu($table, $select='', $sort='', $fields='*', $limitfrom='', $limitnum='')
{
    global $DB;
    if (!empty($DB)) {
        if (empty($limitfrom)) $limitfrom = 0;
        if (empty($limitnum))  $limitnum  = 0;
        return $DB->get_records_select_menu($table, $select, null, $sort, $fields, $limitfrom, $limitnum);
    }
    return get_records_select_menu($table, $select, $sort, $fields, $limitfrom, $limitnum);
}

// function get_record_sql($sql, $expectmultiple=false, $nolimit=false)
// function get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING)
function fs_get_record_sql($sql, $expectmultiple=false, $nolimit=false)
{
    global $DB;
    if (!empty($DB)) {
        $strictness = IGNORE_MISSING;
        if ($exceptmultiple) $strictness = IGNORE_MULTIPLE;
        if ($nolimit)        $strictness = MUST_EXIST;

        return $DB->get_record_sql($sql, null, $strictness);
    }
    return get_record_sql($sql, $expectmultiple, $nolimit);
}

// function get_records_sql($sql, $limitfrom='', $limitnum='')
// function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0)
function fs_get_records_sql($sql, $limitfrom='', $limitnum='')
{
    global $DB;
    if (!empty($DB)) {
        if (empty($limitfrom)) $limitfrom = 0;
        if (empty($limitnum))  $limitnum  = 0;
        return $DB->get_records_sql($sql, null, $limitfrom, $limitnum);
    }
    return get_records_sql($sql, $limitfrom, $limitnum);
}

// Moodle2からは無くなった
function fs_isadmin()
{
    global $USER, $CFG;
    if (function_exists('isadmin')) {
        return isadmin();
    }
    $admin = get_admin();
    return ($USER->id == $admin->id);
}

// (Shirai086): 言語パックのアップデート時にlocalフォルダ内のdefault.ttfをfontsフォルダにコピーする機能の追加 (2008/08/27)
// 言語パック：　default.ttfファイルをlocalからコピー
// この機能は理解不足で実装してしまったもの．実際には，
// (Moodle2.0以前): moodledata/lang/ja_utf8_local/fonts
// (Moodle2.0以降): moodledata/lang/ja_local/fonts
// に各言語用のdefault.ttfを置いておけば問題なし．
function restore_fontfile($pack)
{
    global $CFG;
    $fontfile = 'default.ttf';

    $src  = $CFG->dataroot.'/lang/'.$pack.'_local';
    $dest = $CFG->dataroot.'/lang/'.$pack.'/fonts';

    if (file_exists($src."/$fontfile") && file_exists($dest)) {
        if (!file_exists($dest."/$fontfile")) @copy($src."/$fontfile", $dest."/$fontfile");
    }
}

// Moodle2.5のlib/moodlelib.php中のcheck_browser_version()
function fs_check_browser_version($brand, $version = null) {
    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        return false;
    }

    $agent = $_SERVER['HTTP_USER_AGENT'];

    switch ($brand) {

      case 'Camino':   /// OSX browser using Gecke engine
          if (strpos($agent, 'Camino') === false) {
              return false;
          }
          if (empty($version)) {
              return true; // no version specified
          }
          if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
              if (version_compare($match[1], $version) >= 0) {
                  return true;
              }
          }
          break;


      case 'Firefox':   /// Mozilla Firefox browsers
          if (strpos($agent, 'Iceweasel') === false and strpos($agent, 'Firefox') === false) {
              return false;
          }
          if (empty($version)) {
              return true; // no version specified
          }
          if (preg_match("/(Iceweasel|Firefox)\/([0-9\.]+)/i", $agent, $match)) {
              if (version_compare($match[2], $version) >= 0) {
                  return true;
              }
          }
          break;


      case 'Gecko':   /// Gecko based browsers
          // Do not look for dates any more, we expect real Firefox version here.
          if (empty($version)) {
              $version = 1;
          } else if ($version > 20000000) {
              // This is just a guess, it is not supposed to be 100% accurate!
              if (preg_match('/^201/', $version)) {
                  $version = 3.6;
              } else if (preg_match('/^200[7-9]/', $version)) {
                  $version = 3;
              } else if (preg_match('/^2006/', $version)) {
                  $version = 2;
              } else {
                  $version = 1.5;
              }
          }
          if (preg_match("/(Iceweasel|Firefox)\/([0-9\.]+)/i", $agent, $match)) {
              // Use real Firefox version if specified in user agent string.
              if (version_compare($match[2], $version) >= 0) {
                  return true;
              }
          } else if (preg_match("/Gecko\/([0-9\.]+)/i", $agent, $match)) {
              // Gecko might contain date or Firefox revision, let's just guess the Firefox version from the date.
              $browserver = $match[1];
              if ($browserver > 20000000) {
                  // This is just a guess, it is not supposed to be 100% accurate!
                  if (preg_match('/^201/', $browserver)) {
                      $browserver = 3.6;
                  } else if (preg_match('/^200[7-9]/', $browserver)) {
                      $browserver = 3;
                  } else if (preg_match('/^2006/', $version)) {
                      $browserver = 2;
                  } else {
                      $browserver = 1.5;
                  }
              }
              if (version_compare($browserver, $version) >= 0) {
                  return true;
              }
          }
          break;


      case 'MSIE':   /// Internet Explorer
          if (strpos($agent, 'Opera') !== false) {     // Reject Opera
              return false;
          }
          // In case of IE we have to deal with BC of the version parameter.
          if (is_null($version)) {
              $version = 5.5; // Anything older is not considered a browser at all!
          }
          // IE uses simple versions, let's cast it to float to simplify the logic here.
          $version = round($version, 1);
          // See: http://www.useragentstring.com/pages/Internet%20Explorer/
          if (preg_match("/MSIE ([0-9\.]+)/", $agent, $match)) {
              $browser = $match[1];
          // See: http://msdn.microsoft.com/en-us/library/ie/bg182625%28v=vs.85%29.aspx for IE11+ useragent details.
          } else if (preg_match("/Trident\/[0-9\.]+/", $agent) && preg_match("/rv:([0-9\.]+)/", $agent, $match)) {
              $browser = $match[1];
          } else {
              return false;
          }
          // IE8 and later versions may pretend to be IE7 for intranet sites, use Trident version instead,
          // the Trident should always describe the capabilities of IE in any emulation mode.
          if ($browser === '7.0' and preg_match("/Trident\/([0-9\.]+)/", $agent, $match)) {
              $browser = $match[1] + 4; // NOTE: Hopefully this will work also for future IE versions.
          }
          $browser = round($browser, 1);
          return ($browser >= $version);
          break;


      case 'Opera':  /// Opera
          if (strpos($agent, 'Opera') === false) {
              return false;
          }
          if (empty($version)) {
              return true; // no version specified
          }
          // Recent Opera useragents have Version/ with the actual version, e.g.:
          // Opera/9.80 (Windows NT 6.1; WOW64; U; en) Presto/2.10.289 Version/12.01
          // That's Opera 12.01, not 9.8.
          if (preg_match("/Version\/([0-9\.]+)/i", $agent, $match)) {
              if (version_compare($match[1], $version) >= 0) {
                  return true;
              }
          } else if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
              if (version_compare($match[1], $version) >= 0) {
                  return true;
              }
          }
          break;


      case 'WebKit':  /// WebKit based browser - everything derived from it (Safari, Chrome, iOS, Android and other mobiles)
          if (strpos($agent, 'AppleWebKit') === false) {
              return false;
          }
          if (empty($version)) {
              return true; // no version specified
          }
          if (preg_match("/AppleWebKit\/([0-9.]+)/i", $agent, $match)) {
              if (version_compare($match[1], $version) >= 0) {
                  return true;
              }
          }
          break;


      case 'Safari':  /// Desktop version of Apple Safari browser - no mobile or touch devices
          if (strpos($agent, 'AppleWebKit') === false) {
              return false;
          }
          // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SymbianOS and any other mobile devices
          if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
              return false;
          }
          if (strpos($agent, 'Shiira')) { // Reject Shiira
              return false;
          }
          if (strpos($agent, 'SymbianOS')) { // Reject SymbianOS
              return false;
          }
          if (strpos($agent, 'Android')) { // Reject Androids too
              return false;
          }
          if (strpos($agent, 'iPhone') or strpos($agent, 'iPad') or strpos($agent, 'iPod')) {
              // No Apple mobile devices here - editor does not work, course ajax is not touch compatible, etc.
              return false;
          }
          if (strpos($agent, 'Chrome')) { // Reject chrome browsers - it needs to be tested explicitly
              return false;
          }

          if (empty($version)) {
              return true; // no version specified
          }
          if (preg_match("/AppleWebKit\/([0-9.]+)/i", $agent, $match)) {
              if (version_compare($match[1], $version) >= 0) {
                  return true;
              }
          }
          break;


      case 'Chrome':
          if (strpos($agent, 'Chrome') === false) {
              return false;
          }
          if (empty($version)) {
              return true; // no version specified
          }
          if (preg_match("/Chrome\/(.*)[ ]+/i", $agent, $match)) {
              if (version_compare($match[1], $version) >= 0) {
                  return true;
              }
          }
          break;


      case 'Safari iOS':  /// Safari on iPhone, iPad and iPod touch
          if (strpos($agent, 'AppleWebKit') === false or strpos($agent, 'Safari') === false) {
              return false;
          }
          if (!strpos($agent, 'iPhone') and !strpos($agent, 'iPad') and !strpos($agent, 'iPod')) {
              return false;
          }
          if (empty($version)) {
              return true; // no version specified
          }
          if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
              if (version_compare($match[1], $version) >= 0) {
                  return true;
              }
          }
          break;


      case 'WebKit Android':  /// WebKit browser on Android
          if (strpos($agent, 'Linux; U; Android') === false) {
              return false;
          }
          if (empty($version)) {
              return true; // no version specified
          }
          if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
              if (version_compare($match[1], $version) >= 0) {
                  return true;
              }
          }
          break;

    }

    return false;
}

?>
