<?php

// (Shirai192): Wikiなどのコンテンツに更新があったことをコースの画面上に表示する機能を追加 (2010/08/03)

// (1) Wiki
// mod/wiki/lib.phpの function wiki_print_recent_activity($course, $isteacher, $timestart) を改造
function wiki_get_recent_activity($course, $isteacher, $timestart) {
/// Given a course and a time, this module should find recent activity
/// that has occurred in wiki activities and print it out.
/// Return true if there was output, or false is there was none.

    global $CFG;
// (Shirai192): ここから追加
    global $fsCFG;
    $logdatas = array();
// (Shirai192): ここまで追加
    
// (Shirai192): 条件を修正
//  $sql = "SELECT l.*, cm.instance FROM {$CFG->prefix}log l 
//          ORDER BY l.time ASC";
    $sql = "SELECT l.time,l.cmid,l.url,l.info, cm.instance FROM {$CFG->prefix}log l 
                INNER JOIN {$CFG->prefix}course_modules cm ON l.cmid = cm.id 
            WHERE l.time > '$timestart' AND l.course = {$course->id} 
                AND l.module = 'wiki' AND action LIKE 'edit%'
            ORDER BY l.time DESC";
            
    if (!$logs = fs_get_records_sql($sql)){
        return false;
    }

    $modinfo = get_fast_modinfo($course);
// (Shirai192): ここからコメントアウト
//  $wikis = array();
// (Shirai192): ここまでコメントアウト

// (Shirai192): ここから追加
    $maxnumber = array();
// (Shirai192): ここまで追加
    foreach ($logs as $log) {
        $cm = $modinfo->instances['wiki'][$log->instance];
        if (!$cm->uservisible) {
            continue;
        }

    /// Process log->url and rebuild it here to properly clean the pagename - MDL-15896
        $extractedpage = preg_replace('/^.*&page=/', '', $log->url);
        $log->url = preg_replace('/page=.*$/', 'page='.urlencode($extractedpage), $log->url);

// (Shirai192): ここからコメントアウト
//      $wikis[$log->info] = wiki_log_info($log);
//      $wikis[$log->info]->pagename = $log->info;
//      $wikis[$log->info]->time = $log->time;
//      $wikis[$log->info]->url  = str_replace('&', '&amp;', $log->url);
// (Shirai192): ここまでコメントアウト
// (Shirai192): ここから追加
//      if ($log->cmid != $mod->id) continue;
        // 最大項目数のチェック
        if (!isset($maxnumbers[$log->cmid])) $maxnumbers[$log->cmid] = 0;
        if (!isset($logdatas[$log->info])) {
            if (++$maxnumbers[$log->cmid] > $fsCFG->ra_wiki_maxnum) continue;
        }
        // データの追加
        $logdatas[$log->info]->pagename = substr($log->info, strlen($modinfo->instances['wiki'][$log->instance]->name)+2);
//      $logdatas[$log->info]->time = $log->time;
        $logdatas[$log->info]->url  = str_replace('&', '&amp;', $log->url);
        $logdatas[$log->info]->cmid = $log->cmid;
// (Shirai192): ここまで追加
    }

// (Shirai192): ここから追加
    $newdatas = array();
    // データを再構成
    foreach ($logdatas as $logdata) {
        $newdatas[$logdata->cmid][] = $logdata;
    }
    foreach ($newdatas as $cmid => $newdata) {
        $returndatas[$cmid]->maxnum = $maxnumbers[$cmid];
        $returndatas[$cmid]->list   = $newdata;
    }
    return $returndatas;
// (Shirai192): ここまで追加
// (Shirai192): ここからコメントアウト
/*
    if (!$wikis) {
        return false;
    }
    print_headline(get_string('updatedwikipages', 'wiki').':', 3);
    foreach ($wikis as $wiki) {
        print_recent_activity_note($wiki->time, $wiki, $wiki->pagename,
                                   $CFG->wwwroot.'/mod/wiki/'.$wiki->url);
    }

    return false;
*/
// (Shirai192): ここまでコメントアウト
}

// (2) Glossary
// mod/glossary/lib.phpのfunction glossary_print_recent_activity($course, $viewfullnames, $timestart)を改造
function glossary_get_recent_activity($course, $viewfullnames, $timestart) {
/// Given a course and a time, this module should find recent activity
/// that has occurred in glossary activities and print it out.
/// Return true if there was output, or false is there was none.

    global $CFG, $USER;
// (Shirai192): ここから追加
    global $fsCFG;
    $logdatas = array();
// (Shirai192): ここまで追加

    //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0

    $modinfo = get_fast_modinfo($course);
    $ids = array();
    foreach ($modinfo->cms as $cm) {
        if ($cm->modname != 'glossary') {
            continue;
        }
        if (!$cm->uservisible) {
            continue;
        }
        $ids[$cm->instance] = $cm->instance;
    }

    if (!$ids) {
        return false;
    }

    $glist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right?

// (Shirai192): 条件を修正
//                                 ORDER BY ge.timemodified ASC")) {
//                                          ge.userid, u.firstname, u.lastname, u.email, u.picture
    if (!$entries = fs_get_records_sql("SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
                                            ge.userid
                                       FROM {$CFG->prefix}glossary_entries ge
                                            JOIN {$CFG->prefix}user u ON u.id = ge.userid
                                      WHERE ge.glossaryid IN ($glist) AND ge.timemodified > $timestart
                                   ORDER BY ge.timemodified DESC")) {
        return false;
    }

    $editor  = array();

// (Shirai192): ここから追加
    $maxnumber = array();
// (Shirai192): ここまで追加
    foreach ($entries as $entryid=>$entry) {
// (Shirai192): ここからコメントアウト
//      if ($entry->approved) {
//          continue;
//      }
//
//      if (!isset($editor[$entry->glossaryid])) {
//          $editor[$entry->glossaryid] = has_capability('mod/glossary:approve', get_context_instance(CONTEXT_MODULE, $modinfo->instances['glossary'][$entry->glossaryid]->id));
//      }
//
//      if (!$editor[$entry->glossaryid]) {
//          unset($entries[$entryid]);
//      }
// (Shirai192): ここまでコメントアウト
// (Shirai192): ここから追加
        // 最大項目数のチェック
        $cmid  = $modinfo->instances['glossary'][$entry->glossaryid]->id;
        if (!isset($maxnumbers[$cmid])) $maxnumbers[$cmid] = 0;
        $index = $entry->glossaryid.':'.$entry->concept;
        if (!isset($logdatas[$index])) {
            if (++$maxnumbers[$cmid] > $fsCFG->ra_glossary_maxnum) continue;
        }
        // データの追加
        $logdatas[$index]->pagename = format_text($entry->concept, true);
        $logdatas[$index]->url      = str_replace('&', '&amp;', 'view.php?g='.$entry->glossaryid.'&mode=entry&hook='.$entry->id);
//      $logdatas[$index]->url      = str_replace('&', '&amp;', 'showentry.php?eid='.$entry->id);
        $logdatas[$index]->cmid     = $cmid;
// (Shirai192): ここまで追加
    }

// (Shirai192): ここから追加
    $newdatas = array();
    // データを再構成
    foreach ($logdatas as $logdata) {
        $newdatas[$logdata->cmid][] = $logdata;
    }
    foreach ($newdatas as $cmid => $newdata) {
        $returndatas[$cmid]->maxnum = $maxnumbers[$cmid];
        $returndatas[$cmid]->list   = $newdata;
    }
    return $returndatas;
// (Shirai192): ここまで追加
// (Shirai192): ここからコメントアウト
/*
    if (!$entries) {
        return false;
    }
    print_headline(get_string('newentries', 'glossary').':');

    $strftimerecent = get_string('strftimerecent');
    foreach ($entries as $entry) {
        $link = $CFG->wwwroot.'/mod/glossary/view.php?g='.$entry->glossaryid.'&amp;mode=entry&amp;hook='.$entry->id;
        if ($entry->approved) {
            $dimmed = '';
        } else {
            $dimmed = ' dimmed_text';
        }
        echo '<div class="head'.$dimmed.'">';
        echo '<div class="date">'.userdate($entry->timemodified, $strftimerecent).'</div>';
        echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
        echo '</div>';
        echo '<div class="info"><a href="'.$link.'">'.format_text($entry->concept, true).'</a></div>';
    }

    return true;
*/
// (Shirai192): ここまでコメントアウト
}

// ---------------------------------------------------------

// Overlibの設定を１度だけ行う（カレンダーに悪影響を与えないためにカレンダーの設定を流用）
function set_overlib_for_updatemark()
{
    if (!defined('CALENDAR_URL')) define ('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
    echo '<script type="text/javascript" src="'.CALENDAR_URL.'overlib.cfg.php"></script>';
}


// コース画面にマークとリストを表示する
function print_recent_activity_link($mod, $recentDatas)
{
    global $CFG, $fsCFG;
    static $overlib_setting = false;

    // データの分離
    $maxnum     = $recentDatas->maxnum;
    $recentData = $recentDatas->list;
    // 更新情報が存在しない場合（事前にチェック済みだが）は何もしない．
    if (($newnum = count($recentData)) < 1) return;
    // リストの表示タイプ（高度／低レベル）を切り替える．
    if (fs_function_enable('FS_DISABLE_RA_LINK_JAVASCRIPT')) {
        // もし特定の端末やブラウザで表示できない場合はifで$advstyle = falseとする．
        $advstyle = true;
    } else {
        $advstyle = false;
    }
    $updatestr = '&nbsp;&nbsp;'.get_string('update').'&nbsp;:&nbsp;'.$maxnum.'&nbsp;&nbsp;';
    if (fs_function_enable('FS_ENABLE_RA_LINK_CUSTOMATTRIBUTE')) {
        // カスタム設定適用時
        $updatestr = '<span style="margin-left:2em;'.$fsCFG->ra_link_customattribute.'">'.$updatestr.'</span>';
    }
    if ($advstyle) {
        // JavaScript(Overlib)使用時
        if (!$overlib_setting) {
            set_overlib_for_updatemark();
            $overlib_setting = true;
        }
        echo '<span ';
        if (!fs_function_enable('FS_ENABLE_RA_LINK_CUSTOMATTRIBUTE')) echo 'class="unread" ';
        $popupcontent = '';
        foreach ($recentData as $entry) {
            $url = $CFG->wwwroot.'/mod/'.$mod->modname.'/'.$entry->url;
            $popupcontent .= '<div><a href="'.$url.'">'.$entry->pagename.'</a></div>';
        }
        $popupcaption  = get_string('latestupdatedentries', 'fs_moodle', $newnum);
        $popupcontent = str_replace("'", "\'", htmlspecialchars($popupcontent));
        $popupcaption = str_replace("'", "\'", htmlspecialchars($popupcaption));
        $popup = 'onmouseover="return overlib(\''.$popupcontent.'\', CAPTION, \''.$popupcaption.'\');" onmouseout="return nd();"';
        echo $popup.'>';
        echo $updatestr;
        echo "</span>\n";
    } else {
        // HTMLによるリスト表示（少しだけJavaScript）
        echo '<span class="unread">'.$updatestr.'</span>'."\n";
        echo '<select onChange="location.href=value;">'."\n";
        echo '  <option value="#">'.get_string('latestupdatedentries', 'fs_moodle', $newnum)."</option>\n";
        foreach ($recentData as $entry) {
            echo '  <option value="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/'.$entry->url.'">'.$entry->pagename."</option>\n";
        }
        echo "</select>\n";
    }
}

?>
