<?php

/**
* Вывод части текста
* @param undefined $text
* @param undefined $limit
* 
* @return string 
*/
function wordtextwrap($text, $limit = 32) {
    $rows = explode(" ", strip_tags($text));

    if (count($rows) > $limit) {
        $text = '';
        
        foreach($rows AS $key => $str) {
            $text .= " " . $str;
            if ($key >= $limit) {
                $text .= '...';
                $text .= ' <div class="text-next">&bull;&bull;&bull; подробнее</div>';
                BREAK;
            }
        }        
    }
    
    return $text;
}

function redirect_url($msg = null, $url) {
    $_SESSION['message'] = $msg;
    header('Location: ' . $url);
    exit;
}

/**
* Удаление фотоальбомов
*/

function groups_delete_albums($uid = 0, $type = false, $group_id = 0) {
    if ($type == 'user') {
        $q = mysql_query("SELECT * FROM groups_albums WHERE id_user = '$uid'");
        
        while($post = mysql_fetch_assoc($q)) {
            groups_delete_albums($post['uid'], 'albums', $post['id_group']);
        }
    } 
    
    elseif ($type == 'group') {
        $q = mysql_query("SELECT * FROM groups_albums WHERE id_group = '$uid'");
        
        while($post = mysql_fetch_assoc($q)) {
            groups_delete_albums($post['uid'], 'albums', $uid);
        }
    } 
    
    elseif ($type == 'albums') {
        $q = mysql_query("SELECT * FROM groups_photos WHERE id_albums = '$uid' AND id_group = '$group_id'");
        
        while($post = mysql_fetch_assoc($q)) {
            groups_delete_albums($post['uid'], 'photo', $post['id_group']);
        }
        mysql_query("DELETE FROM groups_albums WHERE uid = '$uid' LIMIT 1");
    } 
    
    elseif ($type == 'photo') {
        $photo = mysql_fetch_assoc(mysql_query("SELECT * FROM `groups_photos` WHERE `uid` = '$uid' AND id_group = '$group_id' LIMIT 1"));
        
        if (mysql_result(mysql_query("SELECT COUNT(*) FROM `groups_photos` WHERE `hash` = '$photo[hash]' AND `uid` != '$uid'"), 0) == 0) {
            @unlink(H.'sys/files/groups/photos/' . $photo['hash'] . '.jpg');
        }
        
        mysql_query("DELETE FROM groups_photos WHERE uid = '$uid' LIMIT 1");
        mysql_query("DELETE FROM groups_comments WHERE id_object = '$uid' AND type = 'photo'");
        mysql_query("DELETE FROM discussions WHERE id_sim = '$uid' AND type = 'groups_photo'");
        send_tape('albums', $photo['id_group'], $photo['id_albums'], $photo['id_user'], $uid, true, true);
    }
}

function groups_delete_videos($uid = 0, $type = false, $group_id = 0) {
    
    if ($type == 'user') {
        $q = mysql_query("SELECT * FROM groups_videos WHERE id_user = '$uid'");
        
        while($post = mysql_fetch_assoc($q)) {
            groups_delete_videos($post['uid'], 'video', $post['id_group']);
        }
    } 
    
    elseif ($type == 'group') {
        $q = mysql_query("SELECT * FROM groups_videos WHERE id_group = '$uid'");
        
        while($post = mysql_fetch_assoc($q)) {
            groups_delete_videos($post['uid'], 'video', $uid);
        }
    } 
    
    elseif ($type == 'video') {
        $video = mysql_fetch_assoc(mysql_query("SELECT * FROM `groups_videos` WHERE `uid` = '$uid' AND id_group = '$group_id' LIMIT 1"));
        
        if (mysql_result(mysql_query("SELECT COUNT(*) FROM `groups_videos` WHERE `hash` = '$video[hash]' AND `uid` != '$uid'"), 0) == 0) {
            @unlink(H.'sys/files/groups/videos/files/' . $video['hash'] . '.video');
            @unlink(H.'sys/files/groups/videos/screen/' . $video['hash'] . '.jpg');
        }
        
        mysql_query("DELETE FROM groups_videos WHERE uid = '$uid' LIMIT 1");
        mysql_query("DELETE FROM groups_comments WHERE id_object = '$uid' AND type = 'video'");
        mysql_query("DELETE FROM groups_tape WHERE id_object = '$uid' AND type = 'videos'");
        mysql_query("DELETE FROM tape WHERE id_file = '$uid' AND type = 'groups_videos'");
        mysql_query("DELETE FROM discussions WHERE id_sim = '$uid' AND type = 'groups_video'");
    }
}

function groups_delete_topic($uid = 0, $type = false, $group_id = 0) {
    
    if ($type == 'user') {
        $q = mysql_query("SELECT * FROM groups_topic WHERE id_user = '$uid'");
        
        while($post = mysql_fetch_assoc($q)) {
            groups_delete_topic($post['uid'], 'topic', $post['id_group']);
        }
    } 
    
    elseif ($type == 'group') {
        $q = mysql_query("SELECT * FROM groups_topic WHERE id_group = '$uid'");
        
        while($post = mysql_fetch_assoc($q)) {
            groups_delete_topic($post['uid'], 'topic', $uid);
        }
    } 
    
    elseif ($type == 'topic') {
        $topic = mysql_fetch_assoc(mysql_query("SELECT * FROM `groups_topic` WHERE `uid` = '$uid' AND id_group = '$group_id' LIMIT 1"));
        
        mysql_query("DELETE FROM groups_topic WHERE uid = '$uid' LIMIT 1");
        mysql_query("DELETE FROM groups_comments WHERE id_object = '$uid' AND type = 'topic'");
        mysql_query("DELETE FROM groups_tape WHERE id_object = '$uid' AND type = 'topic'");
        mysql_query("DELETE FROM tape WHERE id_file = '$uid' AND type = 'groups_topic'");
        mysql_query("DELETE FROM discussions WHERE id_sim = '$uid' AND type = 'groups_topic'");
    }
}

function groups_delete_tape($uid = 0, $type = false, $group_id = 0) {
    if ($type == 'group') {
        mysql_query("DELETE FROM groups_tape WHERE id_group = '$uid'");
    }
}

/**
* Удаление групп
* @param undefined $uid
* @param undefined $type
* 
* @return
*/
function groups_delete($uid = 0, $type = false) {
    
    if ($type == 'user') {
        $q = mysql_query("SELECT * FROM groups WHERE id_admin = '$uid'");
        
        while($post = mysql_fetch_assoc($q)) {
            groups_delete($post['uid'], 'group');
        }
    } 
    
    elseif ($type == 'all') {
        $q = mysql_query("SELECT * FROM groups");
        
        while($post = mysql_fetch_assoc($q)) {
            groups_delete($post['uid'], 'group');
        }
    } 
    
    elseif ($type == 'group') {
        groups_delete_topic($uid, 'group');
        groups_delete_videos($uid, 'group');
        groups_delete_albums($uid, 'group');
        groups_delete_albums(0, 'albums', $uid);
        mysql_query("DELETE FROM groups WHERE uid = '$uid' LIMIT 1");
        mysql_query("DELETE FROM groups_users WHERE id_group = '$uid'");
        mysql_query("DELETE FROM groups_tape WHERE id_group = '$group_id'");
        mysql_query("DELETE FROM groups_friends WHERE id_group = '$group_id'");
    }
}

/**
* Cписок друзей и участников группы
* @return array 
*/

function get_users_tape($user_id = 0, $group_id = 0) {
    
    static $users;
    
    if (!isset($users[$user_id])) {
        $q = mysql_query("SELECT ru.id
                  FROM user AS ru
                  LEFT JOIN groups_users AS u ON u.id_group = '$group_id' AND u.id_user != '$user_id'
                  LEFT JOIN frends AS f ON f.user = '$user_id' AND f.i = '1'
                  WHERE (f.frend = ru.id OR u.id_user = ru.id)
                  GROUP BY ru.id");
        
        while($feed = mysql_fetch_assoc($q)) {
            $users[$user_id][] = $feed['id'];
        }
        
        return $users[$user_id];    
    }
    
    if (isset($users[$user_id])) {
        return $users[$user_id];
    }
    
    return array();
}

/**
* Отправка в ленту группы
* @param undefined $type
* @param undefined $id_group
* @param undefined $id_object
* @param undefined $id_user
*/

function send_tape($type, $id_group, $id_object, $id_user, $id_last = 0, $update = true, $down = false) {
    $tape = mysql_fetch_assoc(mysql_query("SELECT * FROM groups_tape
                                           WHERE `type` = '$type' AND `id_object` = '$id_object' AND `id_user` = '$id_user' AND `id_group` = '$id_group'
                                           ORDER BY uid DESC
                                           LIMIT 1"));
    $time = time();
    
    if (isset($tape['uid']) && $tape['time'] > ($time - 600) && $update == true) {           
        if ($down && $tape['count'] <= 1) {
            mysql_query("DELETE FROM `groups_tape` 
                         WHERE `uid` = '$tape[uid]' LIMIT 1");
        } else {
            mysql_query("UPDATE `groups_tape` 
                         SET `count` = `count` + '" . (!$down ? 1 : -1) . "', `time` = " . (!$down ? $time : '`time`') . ", `id_last` = '$id_last'
                         WHERE `uid` = '$tape[uid]' LIMIT 1");            
        }
    } 
    
    elseif (!$down) {
        mysql_query("INSERT INTO `groups_tape`(`id_user`, `id_object`, `id_group`, `time`, `type`, `id_last`) 
                        VALUES ('$id_user', '$id_object', '$id_group', '$time', '$type', '$id_last')");
          
    }
    
    /**
    * Лента друзей и участников группы
    */
    foreach(get_users_tape($id_user, $id_group) AS $key => $id) {
        $feed = mysql_fetch_array(mysql_query("SELECT * FROM `tape` WHERE `type` = 'groups_$type' AND `id_file` = '$id_object' LIMIT 1"));
        
        if ($feed && $update == true && $feed['time'] > ($time - 600)) {
            if ($down && $feed['count'] <= 1) {
                mysql_query("DELETE FROM `tape` 
                             WHERE `id` = '$feed[id]' LIMIT 1");
            } else {
                mysql_query("UPDATE `tape` 
                             SET `count` = `count` + '" . (!$down ? 1 : -1) . "', `read` = '0', `time` = '$time', `ot_kogo` = '$id_last'
                             WHERE id = '$feed[id]' LIMIT 1");                
            }
        } else {
            mysql_query("INSERT INTO `tape` (`id_user`, `avtor`, `type`, `time`, `id_file`, `count`, `ot_kogo`) 
                            VALUES('$id', '$id_user', 'groups_$type', '$time', '$id_object', '1', '$id_last')");            
        }
    }
    
    mysql_query("UPDATE `groups_users` 
                 SET `read` = `read` + '" . (!$down ? 1 : 0) . "'
                 WHERE `id_group` = '$id_group' AND `id_user` != '$id_user'");
}

function get_comments_count($type, $group_id, $object_id) {
    $count = mysql_result(mysql_query("SELECT COUNT(*) FROM groups_comments
									   WHERE type = '$type' AND id_object = '$object_id' AND `id_group` = '$group_id'"), 0);
    
    return '<i class="comments"></i> ' . $count;
}

function get_comments($type, $member = false, $group, $object, $action) {
		global $user, $set, $insert, $tPanel, $config;
		?>
		<div class="group-post">
		  <div class="group-post-title">
		    <b>Комментарии</b>
		  </div>
		</div>
		<?
		
		$k_post = mysql_result(mysql_query("SELECT COUNT(*) FROM groups_comments
											WHERE type = '$type' AND id_object = '$object[uid]'"), 0);
		
    $k_page = k_page($k_post, $set['p_str']);
    $page = page($k_page);
    $start = $set['p_str'] * $page - $set['p_str'];
    
    if ($k_post == 0) {
        ?>
        <div class="group-post-none none-albums">
          <div class="none-title">
            Нет комментариев
          </div>
        </div>
        <?
    }
  	
		$q = mysql_query("SELECT c.*, ru.nick, ru.date_last FROM groups_comments AS c
                            LEFT JOIN user AS ru ON ru.id = c.id_user
                            WHERE c.id_group = '$group[uid]' AND c.type = '$type' AND c.id_object = '$object[uid]'
                            ORDER BY c.uid DESC 
                            LIMIT $start, $set[p_str]");   
    
    while ($post = mysql_fetch_assoc($q))
    {
      ?>
      <div class="group-table group-post">
        <div class="group-table-cell group-post-avatar">
          <?= avatar($post['id_user'])?>
        </div>
        <div class="group-table-cell group-post-title">
          <span class="group-post-time">
            <?= vremja($post['time'])?>
          </span>
          <a href="/info?id=<?= $post['id_user']?>"><?= text($post['nick'])?></a> 
          <span class="<?= ($post['date_last'] >= ($time - $set['time_online']) ? 'online' : 'offline')?>"></span> 
          <? if (isset($member) && $member['id_user'] != $post['id_user']) { ?>
	           <a href="<?= $action?>&amp;response=<?= $post['id_user']?>">[*]</a> 
	        <? } ?>
          <span class="topic-text"><?= output_text($post['msg'])?></span>
        </div>
      </div>
      <?
    } 
    
    if ($k_page > 1) {
        str($action . '&', $k_page, $page); 
    }
    
		if (isset($user) && isset($member['uid']))
		{
			?>
			<form method="post" name="message" action="<?= $action . REPLY?>">
			<?
			if (is_file(H.'style/themes/' . $set['set_them'] . '/altername_post_form.php'))
			    include_once H.'style/themes/' . $set['set_them'] . '/altername_post_form.php';
			else
			    echo $tPanel . '<textarea name="msg">' . $insert . '</textarea><br />';

			?>
			<input name="type" value="<?= $type?>" type="hidden" />
			<input name="member_uid" value="<?= $member['uid']?>" type="hidden" />
			<input name="groups_uid" value="<?= $group['uid']?>" type="hidden" />
			<input name="object_uid" value="<?= $object['uid']?>" type="hidden" />
			<input name="uri" value="<?= $action?>" type="hidden" />
			<input name="hash" value="<?= md5($type . $member['uid'].$group['uid'].$object['uid'].$action.$config['secret_key'])?>" type="hidden" />
			<input name="comments" value="Написать" type="submit" />
			</form>
			<?
		}
}