<?php
// Viewkarma.php

if (!defined('SMF'))
        die('Hacking attempt...');

function ViewKarma()
{
         global $db_prefix, $context, $scripturl, $modSettings, $txt, $user_info, $ID_MEMBER;

        // If mod disable, give me error please. Если мод выключен, то никаких действий не производим
        if (empty($modSettings['karmadescmod']))
                fatal_lang_error('smf63', false);
        
        if (!empty($modSettings['karmaisowner']) && ($user_info['is_admin']!=1))
                fatal_lang_error('cannot_karmalog_view', false);

        //Permissions
        isAllowedTo('karmalog_view');

        loadTemplate('Viewkarma');

        // Sorting...
        $sort_methods = array(
                'exec' => 'lk.ID_EXECUTOR',
                'targ' => 'lk.ID_TARGET',
                'action' => 'lk.action',
                'time' => 'lk.logTime'
        );

        // By default, sorting by time
        if (!isset($_REQUEST['sort']) || !isset($sort_methods[$_REQUEST['sort']]))
        {
                $context['sort_by'] = 'time';
                $_REQUEST['sort'] = 'lk.logTime';
        }
        // DESC, ASC
        else
        {
                $context['sort_by'] = $_REQUEST['sort'];
                $_REQUEST['sort'] = $sort_methods[$_REQUEST['sort']];
        }

        $context['sort_direction'] = isset($_REQUEST['asc']) ? 'up' : 'down';

        // All values
        $request = db_query("
                SELECT COUNT(action)
                FROM {$db_prefix}log_karma
                ", __FILE__, __LINE__);
        list ($totalActions) = mysql_fetch_row($request);
        mysql_free_result($request);


        // Context variables, like title, etc
        $context['page_title'] = $txt['viewkarma_title'];
        $context['linktree'][] = array(
                            'url' => $scripturl . '?action=viewkarma',
                            'name' => $txt['viewkarma_title'] );
        $context['page_index'] = constructPageIndex($scripturl . '?action=viewkarma' ,$_REQUEST['start'], $totalActions, $modSettings['karmamaxmembers']);
        $context['start'] = $_REQUEST['start'];
        $context['totalActions'] = $totalActions;

        //Main DB Query
        $result = db_query("
                             SELECT lk.ID_TARGET, lk.ID_EXECUTOR, lk.logTime, lk.action, lk.Description, lk.link, memt.realName AS targetName, meme.realName AS executorName, memt.karmaGood AS targetKarmaGood, memt.karmaBad AS targetKarmaBad, meme.KarmaGood AS executorKarmaGood, meme.KarmaBad AS executorKarmaBad
                             FROM {$db_prefix}log_karma AS lk, {$db_prefix}members AS memt, {$db_prefix}members AS meme
                             WHERE memt.ID_MEMBER = lk.ID_TARGET
                             AND meme.ID_MEMBER = lk.ID_EXECUTOR
                             ORDER BY $_REQUEST[sort] " . (isset($_REQUEST['asc']) ? 'ASC' : 'DESC') . "
                             LIMIT $context[start], $modSettings[karmamaxmembers]", __FILE__, __LINE__);

        $num_results = mysql_num_rows($result);
        $context['num_results'] = $num_results;

        //All recieve values to context variables please.
        $context['karma_changes'] = array();
            while ($row = mysql_fetch_assoc($result))
        $context['karma_changes'][] = array(
                      'executor' => stripslashes($row['executorName']),
                      'target' => stripslashes($row['targetName']),
                      'action' => ($row['action'] == 1) ? '+' : '-',
                      'Description' => stripslashes($row['Description']),
                      'time' => timeformat($row['logTime']),
                      'id_exec' => stripslashes($row['ID_EXECUTOR']),
                      'id_targ' => stripslashes($row['ID_TARGET']),
                      'targetkarmagood' => stripslashes($row['targetKarmaGood']),
                      'targetkarmabad' => stripslashes($row['targetKarmaBad']),
                      'executorkarmagood' => stripslashes($row['executorKarmaGood']),
                      'executorkarmabad' => stripslashes($row['executorKarmaBad']),
                      'link' => stripslashes($row['link']),
                      'logtime' => stripslashes($row['logTime']),
                                            );
mysql_free_result($result);

        // Delete specific karma?
        if (isset($_POST['delete']))
                deleteKarma();

        // Clear Get variable.
        if (!isset($_GET['start']) || $_GET['start'] < 0)
                $_GET['start'] = 0;

        //Show other karma statistic if needed
        if (!empty($modSettings['karmaotherstat']))
        show_other_stat();


}

function OwnKarma()
{
        global $db_prefix, $context, $scripturl, $modSettings, $txt, $user_info, $ID_MEMBER;

        // Если мод выключен, то никаких действий не производим
        if (empty($modSettings['karmadescmod']))
                fatal_lang_error('smf63', false);
        if (!empty($modSettings['karmaisowner']) && $_REQUEST['u']!=$ID_MEMBER && ($user_info['is_admin']!=1))
              fatal_lang_error('cannot_karmalog_view', false);


        //Права
        isAllowedTo('karmalog_view');


        loadTemplate('Viewkarma');

        // Сортировка...
        $sort_methods = array(
                'exec' => 'lk.ID_EXECUTOR',
                'targ' => 'lk.ID_TARGET',
                'action' => 'lk.action',
                'time' => 'lk.logTime'
        );

        // По умолчанию сортируем по времени
        if (!isset($_REQUEST['sort']) || !isset($sort_methods[$_REQUEST['sort']]))
        {
                $context['sort_by'] = 'time';
                $_REQUEST['sort'] = 'lk.logTime';
        }
        // Возрастание, убывание
        else
        {
                $context['sort_by'] = $_REQUEST['sort'];
                $_REQUEST['sort'] = $sort_methods[$_REQUEST['sort']];
        }

        $context['sort_direction'] = isset($_REQUEST['asc']) ? 'up' : 'down';

        //Request['u'] должен быть указан.
        $_REQUEST['u'] = isset($_REQUEST['u']) ? (int) $_REQUEST['u'] : 0;
        if (empty($_REQUEST['u']))
                        fatal_lang_error('viewkarma_error', false);

        // Получаем общее количество строк
        $request = db_query("
                SELECT COUNT(action)
                FROM {$db_prefix}log_karma
                WHERE ID_TARGET=".$_REQUEST['u']."
                ", __FILE__, __LINE__);
        list ($totalActions) = mysql_fetch_row($request);
        mysql_free_result($request);

        // Занесение некоторых значений в массив. (Название раздела, создание дерева ссылок)
        $context['page_title'] = $txt['viewkarma_title'];
        $context['linktree'][] = array(
                'url' => $scripturl . '?action=ownkarma;u=' . $_REQUEST['u'] . '',
                'name' => $txt['viewkarma_title'] );
        $context['page_index'] = constructPageIndex($scripturl . '?action=ownkarma;u=' . $_REQUEST['u'] . '' ,$_REQUEST['start'], $totalActions, $modSettings['karmamaxmembers']);
        $context['start'] = $_REQUEST['start'];
        $context['totalActions'] = $totalActions;

        //Запрос в базу данных
        $result = db_query("
                             SELECT lk.ID_TARGET, lk.ID_EXECUTOR, lk.logTime, lk.action, lk.Description, lk.link, memt.realName AS targetName, meme.realName AS executorName, memt.karmaGood AS targetKarmaGood, memt.karmaBad AS targetKarmaBad, meme.KarmaGood AS executorKarmaGood, meme.KarmaBad AS executorKarmaBad
                             FROM {$db_prefix}log_karma AS lk, {$db_prefix}members AS memt, {$db_prefix}members AS meme
                             WHERE memt.ID_MEMBER = lk.ID_TARGET
                             AND meme.ID_MEMBER = lk.ID_EXECUTOR
                             AND lk.ID_TARGET = ".$_REQUEST['u']."
                             ORDER BY $_REQUEST[sort] " . (isset($_REQUEST['asc']) ? 'ASC' : 'DESC') . "
                             LIMIT $context[start], $modSettings[karmamaxmembers]", __FILE__, __LINE__);

        $num_results = mysql_num_rows($result);
        $context['num_results'] = $num_results;

        //Занесение полученных данных в массив.
        $context['karma_changes'] = array();
            while ($row = mysql_fetch_assoc($result))
        $context['karma_changes'][] = array(
                      'executor' => stripslashes($row['executorName']),
                      'target' => stripslashes($row['targetName']),
                      'action' => ($row['action'] == 1) ? '+' : '-',
                      'Description' => stripslashes($row['Description']),
                      'time' => timeformat($row['logTime']),
                      'id_exec' => stripslashes($row['ID_EXECUTOR']),
                      'id_targ' => stripslashes($row['ID_TARGET']),
                      'targetkarmagood' => stripslashes($row['targetKarmaGood']),
                      'targetkarmabad' => stripslashes($row['targetKarmaBad']),
                      'executorkarmagood' => stripslashes($row['executorKarmaGood']),
                      'executorkarmabad' => stripslashes($row['executorKarmaBad']),
                      'link' => stripslashes($row['link']),
                      'logtime' => stripslashes($row['logTime']),
                                                                  );
mysql_free_result($result);

        // Deleting specific karma?
        if (isset($_POST['delete']))
                deleteKarma();

        // Clean up start.
        if (!isset($_GET['start']) || $_GET['start'] < 0)
                $_GET['start'] = 0;

        if (!empty($modSettings['karmaotherstat']))
        show_other_stat();
}

function OtherKarma()
{
        global $db_prefix, $context, $scripturl, $modSettings, $txt, $user_info, $ID_MEMBER;

        // Если мод выключен, то никаких действий не производим
        if (empty($modSettings['karmadescmod']))
                fatal_lang_error('smf63', false);
        if (!empty($modSettings['karmaisowner']) && $_REQUEST['u']!=$ID_MEMBER && ($user_info['is_admin']!=1))
                fatal_lang_error('cannot_karmalog_view', false);


        //Права
        isAllowedTo('karmalog_view');

        loadTemplate('Viewkarma');

        // Сортировка...
        $sort_methods = array(
                'exec' => 'lk.ID_EXECUTOR',
                'targ' => 'lk.ID_TARGET',
                'action' => 'lk.action',
                'time' => 'lk.logTime'
        );

        // По умолчанию сортируем по времени
        if (!isset($_REQUEST['sort']) || !isset($sort_methods[$_REQUEST['sort']]))
        {
                $context['sort_by'] = 'time';
                $_REQUEST['sort'] = 'lk.logTime';
        }
        // Возрастание, убывание
        else
        {
                $context['sort_by'] = $_REQUEST['sort'];
                $_REQUEST['sort'] = $sort_methods[$_REQUEST['sort']];
        }

        $context['sort_direction'] = isset($_REQUEST['asc']) ? 'up' : 'down';

        //Request['u'] должен быть указан.
        $_REQUEST['u'] = isset($_REQUEST['u']) ? (int) $_REQUEST['u'] : 0;
        if (empty($_REQUEST['u']))
                        fatal_lang_error('viewkarma_error', false);

        // Получаем общее количество строк
        $request = db_query("
                SELECT COUNT(action)
                FROM {$db_prefix}log_karma
                WHERE ID_EXECUTOR=".$_REQUEST['u']."
                ", __FILE__, __LINE__);
        list ($totalActions) = mysql_fetch_row($request);
        mysql_free_result($request);

        // Занесение некоторых значений в массив. (Название раздела, создание дерева ссылок)
        $context['page_title'] = $txt['viewkarma_title'];
        $context['linktree'][] = array(
                'url' => $scripturl . '?action=otherkarma;u=' . $_REQUEST['u'] . '',
                'name' => $txt['viewkarma_title'] );
        $context['page_index'] = constructPageIndex($scripturl . '?action=otherkarma;u=' . $_REQUEST['u'] . '' ,$_REQUEST['start'], $totalActions, $modSettings['karmamaxmembers']);
        $context['start'] = $_REQUEST['start'];
        $context['totalActions'] = $totalActions;

        //Запрос в базу данных
        $result = db_query("
                             SELECT lk.ID_TARGET, lk.ID_EXECUTOR, lk.logTime, lk.action, lk.Description, lk.link, memt.realName AS targetName, meme.realName AS executorName, memt.karmaGood AS targetKarmaGood, memt.karmaBad AS targetKarmaBad, meme.KarmaGood AS executorKarmaGood, meme.KarmaBad AS executorKarmaBad
                             FROM {$db_prefix}log_karma AS lk, {$db_prefix}members AS memt, {$db_prefix}members AS meme
                             WHERE memt.ID_MEMBER = lk.ID_TARGET
                             AND meme.ID_MEMBER = lk.ID_EXECUTOR
                             AND lk.ID_EXECUTOR = ".$_REQUEST['u']."
                             ORDER BY $_REQUEST[sort] " . (isset($_REQUEST['asc']) ? 'ASC' : 'DESC') . "
                             LIMIT $context[start], $modSettings[karmamaxmembers]", __FILE__, __LINE__);

        $num_results = mysql_num_rows($result);
        $context['num_results'] = $num_results;

        //Занесение полученных данных в массив.
        $context['karma_changes'] = array();
            while ($row = mysql_fetch_assoc($result))
        $context['karma_changes'][] = array(
                      'executor' => stripslashes($row['executorName']),
                      'target' => stripslashes($row['targetName']),
                      'action' => ($row['action'] == 1) ? '+' : '-',
                      'Description' => stripslashes($row['Description']),
                      'time' => timeformat($row['logTime']),
                      'id_exec' => stripslashes($row['ID_EXECUTOR']),
                      'id_targ' => stripslashes($row['ID_TARGET']),
                      'targetkarmagood' => stripslashes($row['targetKarmaGood']),
                      'targetkarmabad' => stripslashes($row['targetKarmaBad']),
                      'executorkarmagood' => stripslashes($row['executorKarmaGood']),
                      'executorkarmabad' => stripslashes($row['executorKarmaBad']),
                      'link' => stripslashes($row['link']),
                      'logtime' => stripslashes($row['logTime']),
                                                                  );
mysql_free_result($result);

        // Deleting specific karma?
        if (isset($_POST['delete']))
                deleteKarma();

        // Clean up start.
        if (!isset($_GET['start']) || $_GET['start'] < 0)
                $_GET['start'] = 0;

        if (!empty($modSettings['karmaotherstat']))
        show_other_stat();
}

// Delete checked karma entries from the database.
function deleteKarma()
{
        global $db_prefix, $context;

        // Just specific karma?
        if (!empty($_POST['delete']))
        {
                db_query("
                        DELETE FROM {$db_prefix}log_karma
                        WHERE logTime IN (" . implode(',', array_unique($_POST["delete"])) . ')', __FILE__, __LINE__);

                // Go back to where we were.
                redirectexit('action=viewkarma;start=' . $_GET['start'] . ';sort='. $_GET['sort'].';' . (isset($_GET['desc']) ? 'desc' : 'asc') . '');
        }

        // Back to the karma log!
        redirectexit('action=viewkarma');


}

function show_other_stat()
{
         global $db_prefix, $context, $scripturl, $modSettings, $txt, $user_info, $ID_MEMBER;

                $date = strftime('%Y%m%d', forum_time(false));

                //User, MAX applauded other users
                $user_max_appl_result = db_query("
                SELECT COUNT(*) AS cnt, mem.realName
                FROM {$db_prefix}log_karma AS lk, {$db_prefix}members AS mem
                WHERE lk.action = 1
                AND mem.ID_MEMBER = lk.ID_EXECUTOR
                GROUP BY lk.ID_EXECUTOR
                ORDER BY cnt DESC
                LIMIT 1",__FILE__,__LINE__);
                $row = mysql_fetch_row($user_max_appl_result);
                $context['memidappl']= stripslashes($row[1]);
                $context['memidapplcount'] = stripslashes($row[0]);
                mysql_free_result($user_max_appl_result);

                //User, MAX smited other users.
                $user_max_smit_result = db_query("
                SELECT COUNT(*) AS cnt, mem.realName
                FROM {$db_prefix}log_karma AS lk, {$db_prefix}members AS mem
                WHERE lk.action = -1
                AND mem.ID_MEMBER = lk.ID_EXECUTOR
                GROUP BY lk.ID_EXECUTOR
                ORDER BY cnt DESC
                LIMIT 1",__FILE__,__LINE__);
                $row = mysql_fetch_row($user_max_smit_result);
                $context['memidsmit']= stripslashes($row[1]);
                $context['memidsmitcount'] = stripslashes($row[0]);
                mysql_free_result($user_max_smit_result);

                //Today karma points
                $today_karma_points = db_query("
                SELECT COUNT(*)
                FROM {$db_prefix}log_karma
                WHERE FROM_UNIXTIME( logTime, '%Y%m%d' ) = $date
                ",__FILE__, __LINE__);
                $row = mysql_fetch_row($today_karma_points);
                $context['today_point'] = stripslashes($row[0]);
                mysql_free_result($today_karma_points);

                //Today plus
                $today_plus_points = db_query("
                SELECT COUNT(*)
                FROM {$db_prefix}log_karma
                WHERE FROM_UNIXTIME( logTime, '%Y%m%d' ) = $date
                AND action = 1
                ",__FILE__,__LINE__);
                $row = mysql_fetch_row($today_plus_points);
                $context['today_plus'] = stripslashes($row[0]);
                $context['today_minus'] = $context['today_point'] - $context['today_plus'];
                mysql_free_result($today_plus_points);


                //Top 5 max applauded users.
                $applaud_result = db_query("
                SELECT ID_MEMBER, realName, karmaGood
                FROM {$db_prefix}members
                WHERE karmaGood >= 0
                ORDER BY karmaGood DESC
                LIMIT 5", __FILE__, __LINE__);
        $context['top_applaud'] = array();
        $max_num_posts = 1;
        while ($row_applaud = mysql_fetch_assoc($applaud_result))
        {
                $context['top_applaud'][] = array(
                        'name' => $row_applaud['realName'],
                        'id' => $row_applaud['ID_MEMBER'],
                        'num_karma' => $row_applaud['karmaGood'],
                        'href' => $scripturl . '?action=profile;u=' . $row_applaud['ID_MEMBER'],
                        'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row_applaud['ID_MEMBER'] . '">' . $row_applaud['realName'] . '</a>'
                );

                if ($max_num_posts < $row_applaud['karmaGood'])
                        $max_num_posts = $row_applaud['karmaGood'];
        }
        mysql_free_result($applaud_result);

        foreach ($context['top_applaud'] as $i => $applauder)
                $context['top_applaud'][$i]['karma_percent'] = round(($applauder['num_karma'] * 100) / $max_num_posts);

                //Top 5 smited users.
                $smite_result = db_query("
                SELECT ID_MEMBER, realName, karmaBad
                FROM {$db_prefix}members
                WHERE karmaBad >= 0
                ORDER BY karmaBad DESC
                LIMIT 5", __FILE__, __LINE__);
        $context['top_smite'] = array();
        $max_num_posts = 1;
        while ($row_smite = mysql_fetch_assoc($smite_result))
        {
                $context['top_smite'][] = array(
                        'name' => $row_smite['realName'],
                        'id' => $row_smite['ID_MEMBER'],
                        'num_karma' => $row_smite['karmaBad'],
                        'href' => $scripturl . '?action=profile;u=' . $row_smite['ID_MEMBER'],
                        'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row_smite['ID_MEMBER'] . '">' . $row_smite['realName'] . '</a>'
                );

                if ($max_num_posts < $row_smite['karmaBad'])
                        $max_num_posts = $row_smite['karmaBad'];
        }
        foreach ($context['top_smite'] as $i => $smiter)
                $context['top_smite'][$i]['karma_percent'] = round(($smiter['num_karma'] * 100) / $max_num_posts);

        mysql_free_result($smite_result);
        }
?>
