function index()
    {
        // Try to get the user's id on Facebook
        $userId = $this->facebook->getUser();
        // If user is not yet authenticated, the id will be zero
        if ($userId == 0) {
            // Generate a login url
            $data['url'] = $this->facebook->getLoginUrl(array('scope' => 'email'));
            redirect($data['url']);
        } else {
            // Get user's data and print it
            $user = $this->facebook->api('/me');
            $this->load->model('auth_model');
            $row = $this->auth_model->register_user_if_not_exists($user);
            if (is_banned($row['user_email'])) {
                $msg = '<div class="alert alert-danger">
				        	<button data-dismiss="alert" class="close" type="button">×</button>
				        	<strong>User banned
				    	</div>';
                $this->session->set_flashdata('msg', $msg);
                redirect(site_url('account/trylogin'));
            } else {
                $this->login($row);
            }
        }
    }
    public function auth_callback()
    {
        $this->load->library('session');
        $this->load->library('googleplus');
        try {
            if (isset($_GET['code'])) {
                $this->googleplus->client->authenticate($_GET['code']);
                $this->googleplus->client->getAccessToken();
                $user_data = $this->googleplus->plus->people->get('me');
                /******** For debuggin purpose*********/
                // echo 'email: '.$user_data['emails']['0']['value'].'<br>';
                // echo 'first_name: '.$user_data['name']['givenName'].'<br>';
                // echo 'last_name: '.$user_data['name']['familyName'].'<br>';
                // echo 'gender: '.$user_data['gender'].'<br>';
                // echo 'user_name: '.strstr($user_data['emails']['0']['value'], '@', true).'<br>';
                /*************************************/
                $user['first_name'] = $user_data['name']['givenName'];
                $user['last_name'] = $user_data['name']['familyName'];
                $user['gender'] = $user_data['gender'];
                $user['username'] = strstr($user_data['emails']['0']['value'], '@', true);
                $user['email'] = $user_data['emails']['0']['value'];
                $this->load->model('auth_model');
                $row = $this->auth_model->register_user_if_not_exists($user, 'google');
                if (is_banned($row['user_email'])) {
                    $msg = '<div class="alert alert-danger">
					        	<button data-dismiss="alert" class="close" type="button">×</button>
					        	<strong>User banned</strong>
					    	</div>';
                    $this->session->set_flashdata('msg', $msg);
                    redirect(site_url('account/trylogin'));
                } else {
                    $this->session->set_userdata('user_id', $row['id']);
                    $this->session->set_userdata('user_name', $row['user_name']);
                    $this->session->set_userdata('user_type', $row['user_type']);
                    $this->session->set_userdata('user_email', $row['user_email']);
                    if ($this->session->userdata('req_url') != '') {
                        $req_url = $this->session->userdata('req_url');
                        $this->session->set_userdata('req_url', '');
                        redirect($req_url);
                    } else {
                        redirect(base_url());
                    }
                }
            }
        } catch (Exception $e) {
            $msg = '<div class="alert alert-danger">
			        	<button data-dismiss="alert" class="close" type="button">×</button>
			        	<strong>Permission denied</strong>
			    	</div>';
            $this->session->set_flashdata('msg', $msg);
            redirect(site_url('account/trylogin'));
        }
    }
예제 #3
0
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/professions.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/commune.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/links.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/lenta.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/blogs.php';
$header = '../header.php';
//$additional_header = "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"Блоги на Free-lance.ru (".$gr_name.")\" href=\"/rss/blogs.php?gr=".$gr."&amp;t=".$t."\" />";
$css_file = array('lenta.css', 'commune.css', '/css/nav.css');
$content = 'content.php';
$js_file = array('polls.js', 'commune.js');
$footer = '../footer.html';
$user_mod = commune::MOD_ADMIN * hasPermissions('communes');
$user_mod |= commune::MOD_PRO * (users::IsPro($uid, $e) ? 1 : 0);
$user_mod |= commune::MOD_EMPLOYER * (int) is_emp();
$user_mod |= commune::MOD_BANNED * is_banned($uid);
$page = __paramInit('int', 'page', 'page', 1);
$action = __paramInit('string', NULL, 'action');
switch ($action) {
    case 'Save':
        $has_lenta = __paramInit('bool', NULL, 'has_lenta', NULL);
        $my_team = __paramInit('bool', NULL, 'my_team');
        $all_profs = __paramInit('bool', NULL, 'all_profs');
        $communes = __paramInit('array', NULL, 'commune_id');
        $prof_groups = __paramInit('array', NULL, 'prof_group_id');
        if (!lenta::SaveUserSettings($has_lenta, $uid, $my_team, $all_profs, $communes, $prof_groups)) {
        }
        // ошибка.
        header('Location: /lenta/');
        exit;
        break;
예제 #4
0
function VoteTopic($topic_id, $user_id, $mod, $vote)
{
    global $session;
    session_start();
    $objResponse = new xajaxResponse();
    if (!get_uid(false)) {
        return $objResponse;
    }
    if (get_uid(false) != $user_id) {
        return $objResponse;
    }
    if (!commune_carma::isAllowedVote()) {
        return $objResponse;
    }
    // !!! Вообще, везде бы, где ajax, проверку такую делать.
    $topic = commune::GetTopMessageByAnyOther($topic_id, $user_id, $mod);
    $uStatus = commune::GetUserCommuneRel($topic['commune_id'], $user_id);
    if ((!$uStatus || !$uStatus['is_accepted']) && (!$uStatus['is_author'] && $topic['user_id'] != $user_id) || $uStatus['is_deleted'] || $uStatus['is_banned'] || is_banned($user_id)) {
        $objResponse->script("lockRating{$topic_id}=0;");
        return $objResponse;
    } else {
        if ($topic && !$topic['is_blocked']) {
            $v = commune::TopicVote($topic_id, $user_id, intval($vote));
            //        $rating = intval($prev_rating) + $v;
            //$rating = commune::GetTopicRating($topic_id);
            $html = __commPrntTopicRating(commune::GetTopMessageByAnyOther($topic_id, $user_id, commune::MOD_COMM_MODERATOR), $mod, $user_id);
            $objResponse->assign('topicRate_' . $topic_id, 'innerHTML', $html);
            $objResponse->script("if(window.lockRating{$topic_id}) lockRating{$topic_id}=0;");
        }
    }
    return $objResponse;
}
예제 #5
0
 function useremail_user_ban_check($str)
 {
     if (is_banned($str)) {
         $this->form_validation->set_message('useremail_user_ban_check', 'User banned');
         return FALSE;
     } else {
         return TRUE;
     }
 }
예제 #6
0
/**
 * Возвращает UID авторизованного юзера. Если юзер неавторизован и у него стоит
 * "автологин", то авторизует его. Может запоминать текущий URI страницы в сессии,
 * чтобы после залогинивания отправить юзера на эту страницу.
 * ВНИМАНИЕ! возвращает UID юзера, если находит его. Либо возвращает
 * 	0 - не найден
 *  -1 - аккаунт забанен
 *  -2 - аккаунт неактивирован
 *  Отрицательные значения возвращает только для юзеров с "автологином"
 *
 * @param boolean $set_uri		сохранять ли текущуй URI страницы в сессии
 * @return integer				UID юзера
 */
function get_uid($set_uri = true)
{
    if (defined('NEO')) {
        return xFront::creaker()->triggerFunction(__FUNCTION__, func_get_args());
    }
    $fid = 0;
    $fid = isset($_SESSION['uid']) ? $_SESSION['uid'] : '';
    $ip = getRemoteIP();
    if ($fid) {
        is_banned(intval($fid));
    } else {
        // случайное число, используемое в get/post запросах для защиты.
        if (!$_SESSION['rand']) {
            $_SESSION['rand'] = csrf_token();
        }
    }
    /*if ($fid) {
    		if(!isset($_SESSION['user_ip']) || $_SESSION['user_ip']!=$ip) {
    			$GLOBALS['session']->logout($_SESSION['login']);
    			session_unset();
    			$fid = 0;
    		}
           }*/
    require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/users.php";
    if ($fid) {
        if (!isset($_SESSION['user_ip']) || $_SESSION['user_ip'] != $ip) {
            users::SaveLoginIPLog($fid, $ip);
            if (!users::CheckUserAllowIP($ip, $fid)) {
                // IP запрещен
                $GLOBALS['session']->logout($_SESSION['login']);
                session_unset();
                $fid = 0;
                header('Location: /denyip.php?login='******'login']);
                exit;
            }
        }
    }
    if (!$fid && (int) $_COOKIE['id'] && !headers_sent()) {
        if ($_COOKIE['pwd'] && $_COOKIE['pwd'] == users::cookieHashPasswd($_COOKIE['id'], $pwd_data)) {
            $fid = login($_COOKIE['name'], $pwd_data['pwd'], 1, false);
        } else {
            uncookie();
            // например, пароль сменили а в куки старый остался.
        }
        is_banned(intval($fid));
    } else {
        if ($set_uri) {
            $_SESSION['ref_uri'] = urlencode(isset($_SERVER['HTTP_ORIGINAL_URI']) ? $_SERVER['HTTP_ORIGINAL_URI'] : $_SERVER['REQUEST_URI']);
        }
    }
    return intval($fid);
}
예제 #7
0
파일: bot.php 프로젝트: Artea/storybot
define("IN_STORYBOT", 1);
require_once "src/snapchat.php";
require_once "config/config.php";
$snapchat = new Snapchat($config['username'], $config['password']);
//create new instance of class Snapchat
$snaps = $snapchat->getSnaps();
//get feed
$snaps = json_decode(json_encode($snaps), true);
//turn into php array
$i = 0;
foreach ($snaps as $item) {
    if ($item['status'] == 1) {
        //if unopened
        if ($item['sender'] != $config['username']) {
            //if not sent from yourself
            if (!is_banned($item['sender'])) {
                $snapchat->addFriend($item['sender']);
                //add sender as friend if not already
                if ($item['media_type'] == 0) {
                    //if still image
                    if ($config['picturesallowed']) {
                        $data = $snapchat->getMedia($item['id']);
                        //get received snap
                        if ($data != "") {
                            $filename = time() . '__' . $item['sender'] . '.jpg';
                            file_put_contents('media/temp/' . $filename, $data);
                            //create temp file with the received snap
                            if ($config['moderation'] == false) {
                                postImageStory($filename, mod_id(), $config['username'], $config['password']);
                            }
                        }
예제 #8
0
파일: views.php 프로젝트: nellka/mebel
function show_guestbook_add_form($formTitle = NULL, $buttonName = NULL)
{
    global $MAX_NAME_LENGTH;
    global $MAX_EMAIL_LENGTH;
    global $MAX_URL_LENGTH;
    global $NAME_FIELD_NAME;
    global $EMAIL_FIELD_NAME;
    global $URL_FIELD_NAME;
    global $COMMENTS_FIELD_NAME;
    global $ADD_FORM_LEGEND;
    global $ADD_FORM_BUTTON_TEXT;
    global $CHALLENGE_STRING_LENGTH;
    global $CHALLENGE_FIELD_NAME;
    global $CHALLENGE_FIELD_PARAM_NAME;
    global $ENABLE_EMAIL_FIELD;
    global $ENABLE_URL_FIELD;
    global $ENABLE_COMMENT_FIELD;
    global $GUESTBOOK_URL_PATH;
    global $NEW_REPLY_TEXT;
    if (!isset($formTitle)) {
        $formTitle = $ADD_FORM_LEGEND;
    }
    if (!isset($buttonName)) {
        $buttonName = $ADD_FORM_BUTTON_TEXT;
    }
    $ipaddress = $_SERVER['REMOTE_ADDR'];
    if (is_banned($ipaddress)) {
        return FALSE;
    }
    $nameValue = "";
    if (isset($_POST['name'])) {
        $nameValue = "value=\"" . htmlspecialchars_default($_POST['name']) . "\" ";
    }
    $emailValue = "";
    if (isset($_POST['email'])) {
        $emailValue = "value=\"" . htmlspecialchars_default($_POST['email']) . "\" ";
    }
    $urlValue = "";
    if (isset($_POST['url'])) {
        $urlValue = "value=\"" . htmlspecialchars_default($_POST['url']) . "\" ";
    }
    $commentsValue = "";
    if (isset($_POST['comments'])) {
        $commentsValue = htmlspecialchars_default($_POST['comments']);
    }
    ?>
<br>
<div style="width: 200px; margin: auto;">
	<a id="post_new_link" href="#"><b>
		<?php 
    echo htmlspecialchars_default($NEW_REPLY_TEXT);
    ?>
	</b></a>
</div>
<div id="error"><?php 
    show_errors();
    ?>
</div>
<form id="post_new" method="post" action="<?php 
    echo urlencode($GUESTBOOK_URL_PATH);
    ?>
">
<fieldset>
<?php 
    //<legend><?_php echo htmlspecialchars_default($formTitle); ?_></legend>
    ?>
<p>



<label for="name"><?php 
    echo htmlspecialchars_default($NAME_FIELD_NAME);
    ?>
:</label>
<input type="text" name="name" id="name" maxlength="<?php 
    echo htmlspecialchars_default($MAX_NAME_LENGTH);
    ?>
" class="inputText" <?php 
    echo $nameValue;
    ?>
/>
<br />

<?php 
    if ($ENABLE_EMAIL_FIELD === TRUE) {
        ?>
<label for="email"><?php 
        echo htmlspecialchars_default($EMAIL_FIELD_NAME);
        ?>
:</label>
<input type="text" name="email" id="email" maxlength="<?php 
        echo htmlspecialchars_default($MAX_EMAIL_LENGTH);
        ?>
" class="inputText" <?php 
        echo $emailValue;
        ?>
/>
<br />
<?php 
    }
    ?>
	
<?php 
    if ($ENABLE_URL_FIELD === TRUE) {
        ?>
<label for="url"><?php 
        echo htmlspecialchars_default($URL_FIELD_NAME);
        ?>
:</label>
<input type="text" name="url" id="url" maxlength="<?php 
        echo htmlspecialchars_default($MAX_URL_LENGTH);
        ?>
" class="inputText" <?php 
        echo $urlValue;
        ?>
/>
<br />
<?php 
    }
    ?>

<?php 
    if ($ENABLE_COMMENT_FIELD === TRUE) {
        ?>
<label for="comments"><?php 
        echo htmlspecialchars_default($COMMENTS_FIELD_NAME);
        ?>
:</label>
<textarea name="comments" id="comments" cols="40" rows="4" class="inputTextArea">
<?php 
        echo $commentsValue;
        ?>
</textarea>
<br />
<?php 
    }
    ?>

<?php 
    global $CHALLENGE_ENABLED;
    if ($CHALLENGE_ENABLED === TRUE) {
        // Create the challenge string and store in the session
        createChallengeString();
        ?>
<label for="<?php 
        echo htmlspecialchars_default($CHALLENGE_FIELD_PARAM_NAME);
        ?>
"><?php 
        echo htmlspecialchars_default($CHALLENGE_FIELD_NAME);
        ?>
:</label>
<input type="text" name="<?php 
        echo htmlspecialchars_default($CHALLENGE_FIELD_PARAM_NAME);
        ?>
" id="<?php 
        echo htmlspecialchars_default($CHALLENGE_FIELD_PARAM_NAME);
        ?>
" maxlength="<?php 
        echo htmlspecialchars_default($CHALLENGE_STRING_LENGTH);
        ?>
" size="<?php 
        echo htmlspecialchars_default($CHALLENGE_STRING_LENGTH);
        ?>
" class="inputText" />
<img src="<?php 
        echo urlencode($GUESTBOOK_URL_PATH);
        ?>
?action=challengeimage" alt="Challenge Image" class="challengeImage" />
<br />
<?php 
    }
    ?>

</p>
<input type="hidden" name="action" value="add" />
<input type="submit" value="<?php 
    echo htmlspecialchars_default($buttonName);
    ?>
" class="submit" />
</fieldset>  
</form>
<?php 
}
예제 #9
0
 function index()
 {
     // Try to get the user's id on Facebook
     $userId = $this->facebook->getUser();
     // If user is not yet authenticated, the id will be zero
     if ($userId == 0) {
         // Generate a login url
         $data['url'] = $this->facebook->getLoginUrl(array('scope' => 'email'));
         redirect($data['url']);
     } else {
         // Get user's data and print it
         $user = $this->facebook->api('/me');
         $this->load->model('auth_model');
         $row = $this->auth_model->register_user_if_not_exists($user);
         $enable_pricing = get_settings('realestate_settings', 'enable_pricing', 'Yes');
         $current_package = get_user_meta($row['id'], 'current_package', '0');
         if ($enable_pricing == 'Yes' && $this->session->userdata('from') == 'signup') {
             $user_id = $row['id'];
             $this->load->model('user/user_model');
             $this->load->helper('date');
             $datestring = "%Y-%m-%d";
             $time = time();
             $request_date = mdate($datestring, $time);
             $this->load->model('admin/package_model');
             if ($this->session->userdata('package_id') == '') {
                 $this->session->set_userdata('from', 'facebook');
                 redirect(site_url('account/signup'));
             }
             $package = $this->package_model->get_package_by_id($this->session->userdata('package_id'));
             $payment_data = array();
             $payment_data['unique_id'] = uniqid();
             $payment_data['user_id'] = $user_id;
             $payment_data['package_id'] = $package->id;
             $payment_data['amount'] = $package->price;
             $payment_data['request_date'] = $request_date;
             $payment_data['is_active'] = 2;
             #pending
             $payment_data['status'] = 1;
             #active
             $payment_data['payment_medium'] = 'paypal';
             $unique_id = $this->user_model->insert_payment_data($payment_data);
             if ($payment_data['amount'] <= 0) {
                 $uniqid = $unique_id;
                 #$this->send_notification_mail('within update');
                 $this->load->model('user/user_model');
                 $package = $this->package_model->get_package_by_id($package->id);
                 $datestring = "%Y-%m-%d";
                 $time = time();
                 $activation_date = mdate($datestring, $time);
                 $expirtion_date = strtotime('+' . $package->expiration_time . ' days', $time);
                 $expirtion_date = mdate($datestring, $expirtion_date);
                 $data = array();
                 $data['is_active'] = 1;
                 $data['activation_date'] = $activation_date;
                 $data['expirtion_date'] = $expirtion_date;
                 $data['response_log'] = '';
                 $this->user_model->update_user_payment_data_by_unique_id($data, $uniqid);
                 add_user_meta($user_id, 'current_package', $package->id);
                 add_user_meta($user_id, 'expirtion_date', $expirtion_date);
                 add_user_meta($user_id, 'active_order_id', $uniqid);
                 add_user_meta($user_id, 'post_count', 0);
                 $this->login($row);
             } else {
                 $this->session->set_userdata('unique_id', $unique_id);
                 $this->session->set_userdata('amount', $package->price);
                 $this->send_signup_notification_email($row, $unique_id);
                 redirect(site_url('account/confirmation'));
             }
         }
         if ($enable_pricing == 'Yes' && $current_package == 0) {
             $this->session->set_userdata('from', 'facebook');
             redirect(site_url('account/signup'));
         }
         if (is_banned($row['user_email'])) {
             $msg = '<div class="alert alert-danger"><button data-dismiss="alert" class="close" type="button">×</button><strong>User banned</div>';
             $this->session->set_flashdata('msg', $msg);
             redirect(site_url('account/trylogin'));
         } else {
             $this->login($row);
         }
     }
 }
예제 #10
0
파일: guestbook.php 프로젝트: nellka/mebel
function guestbook_entries_action($idArray, $banip = FALSE, $action)
{
    global $dbs_error;
    global $guestbook_fp;
    // Get raw data from file
    if (guestbook_open_for_read() === FALSE) {
        // Acquires shared lock on guestbook file
        die("Unable to open guestbook file for reading.");
    }
    $raw_entries = @file(guestbook_file_path());
    guestbook_close();
    // Releases shared lock
    if ($raw_entries === FALSE) {
        die("Unable to get entries from guestbook.");
    }
    // Split entries into components
    $entries = array_map('entry_explode', $raw_entries);
    // Get mapping between indices and ids
    $id_to_idx = getIdToIdxMap($entries);
    // Remove entries by id
    foreach ($idArray as $id) {
        // Validate ID
        if (!isset($id_to_idx[$id])) {
            die("Invalid entry ID.");
        }
        // Get array index of entry from id
        $idx = $id_to_idx[$id];
        if ($idx === 0 || !empty($idx)) {
            $entry_components = $entries[$idx];
            $entry_components = array_map('rawurldecode', $entry_components);
            // Handle IP ban
            if ($banip) {
                // Get IP address
                if (isset($entry_components[6])) {
                    $ipAddress = $entry_components[6];
                    // If not empty and not already banned, add to ban list
                    if (!empty($ipAddress) && !is_banned($ipAddress)) {
                        ban_add($ipAddress);
                    }
                }
            }
            if ($action === 'delete') {
                // Delete entry from raw entries list
                unset($raw_entries[$idx]);
            } else {
                if ($action === 'approve' && isset($entry_components[7]) && $entry_components[7] === 'false') {
                    // Set to approved
                    $entry_components[7] = 'true';
                    // Reencode and set update entries array
                    $entry_components = array_map('rawurlencode', $entry_components);
                    $raw_entries[$idx] = implode('|', $entry_components) . "\n";
                }
            }
        }
    }
    // Create flat data for file
    $raw_entries_flat = implode("", $raw_entries);
    unset($raw_entries);
    // Free memory
    if (guestbook_open_for_writing() === FALSE) {
        die("Unable to open guestbook file for writing.");
    }
    // Rewrite data to file
    fputs($guestbook_fp, $raw_entries_flat);
    unset($raw_entries_flat);
    // Free memory
    guestbook_close();
    // Update entry count
    set_guestbook_entries_count();
}
예제 #11
0
파일: index.php 프로젝트: nellka/mebel
    switch ($action) {
        case "challengeimage":
            outputChallengeImage();
            break;
        default:
            die("Invalid request.");
            break;
    }
} else {
    if (isset($_POST["action"])) {
        $action = $_POST["action"];
        switch ($action) {
            case "add":
                // Undo magic_quotes
                if (get_magic_quotes_gpc()) {
                    $_POST = stripslashes_recursive($_POST);
                }
                if (!is_banned($_SERVER['REMOTE_ADDR']) && guestbook_add($_POST)) {
                    include_from_template('added.php');
                } else {
                    show_entries_page();
                }
                break;
            default:
                show_entries_page();
                break;
        }
    } else {
        show_entries_page();
    }
}
예제 #12
0
function del_mod($uname, $s, $comment = null)
{
    if (!($u = get_user($uname))) {
        apologize("Invalid username.");
    }
    if (is_banned($u)) {
        apologize("User is banned from the site.");
    }
    $ustatus = soc_rel($s, $u["user_id"]);
    if (!$ustatus["mod"]) {
        apologize("User is not a moderator of " . $s["soc_name"] . ".");
    }
    if (!am_mod($s) || $ustatus["creator"] && $u["user_id"] == $_SESSION["user_id"]) {
        apologize("Access Denied.");
    }
    return tquery("\t\n\t\t\t\t\t\tdelete from soc_mods\n\t\t\t\t\t\twhere user_id = ?\n\t\t\t\t\t\tand   soc_id  = ?;\n\t\t\t\t\t\t\n\t\t\t\t\t\tinsert into user_control_mod_log(user_id, mod_id, soc_id, action, comment)\n\t\t\t\t\t\tvalues(?, ?, ?, ?, ?);", [$u["user_id"], $s["soc_id"]], [$u["user_id"], $_SESSION["user"]["user_id"], $s["soc_id"], "DEMOD", $comment]);
}
예제 #13
0
/**
 * Проверяет туда ли попал пользователь и есть ли у него на это право.
 * Возвращает адрес переброски пользователя, если он не туда попал,
 * и если не NULL, то надо будет вызвать header().
 * Если NULL, но $error не пуст, то надо будет выдать страницу ошибок __COMMUNES__ERROR и
 * прекратить операцию.
 * Заодно заполняет необходимые переменные.
 *
 * @global $uid    Ид пользователя
 * @global $id     Ид сообщения
 * @global $top_id Ид вкладки ТОП
 * @global $site   Сайт
 * @global $action Действие для данной функции при отсылке данных (submit)
 * 
 * @param string  $error Возвращает сообщение об ошибке
 * @param array   $comm  Возвращает данные по комментариям
 * @param array   $top   Возвращает популярные сообщения
 * @param integer $restrict_type  Возвращает тип пользования
 * @param integer $user_mod Возвращает битовую маску прав пользователя
 * @return string если не null, название страницы куда перенести пользователя
 */
function __commShaolin(&$error, &$comm, &$top, &$restrict_type, &$user_mod)
{
    global $uid, $id, $top_id, $site, $action, $draft_id;
    $comm = NULL;
    $user_mod = 0;
    if ($uid) {
        $user_mod = commune::MOD_ADMIN * hasPermissions('communes');
        $user_mod |= commune::MOD_MODER * ($user_mod & commune::MOD_ADMIN || hasPermissions('communes'));
        $user_mod |= commune::MOD_PRO * (payed::CheckPro(get_login($uid)) ? 1 : 0);
        $user_mod |= commune::MOD_EMPLOYER * (int) is_emp();
        $user_mod |= commune::MOD_BANNED * is_banned($uid);
    }
    if (!$id) {
        if (!$site) {
            return NULL;
        }
        if ($site == 'Create') {
            if (!$uid) {
                return '/fbd.php';
            }
            if (!($user_mod & (commune::MOD_PRO | commune::MOD_ADMIN))) {
                /*if ($user_mod & commune::MOD_EMPLOYER)
                  return '/payed-emp/';*/
                return '/proonly.php';
            }
            if (($limit = commune::GetUserCommunesLimits($uid)) && $limit['user_communes_count']) {
                if ($limit['user_communes_count'] >= commune::MAX_COUNT) {
                    $error['name'] = 'Создание вашего сообщества';
                    $error['message'] = 'Вы уже создали максимальное количество сообществ.';
                    return NULL;
                }
                $seconds = $limit['seconds_passed_since_user_created_his_last_commune'];
                if ($seconds < commune::CREATION_INTERVAL) {
                    $error['name'] = 'Создание вашего сообщества';
                    $wait = commune::CREATION_INTERVAL - $seconds;
                    $error['message'] = "Подождите {$wait} " . getSymbolicName($wait, 'second') . '.';
                    return NULL;
                }
            }
        } else {
            return '/404.php';
        }
        return NULL;
    }
    if (!($comm = commune::GetCommune($id, !$uid ? NULL : $uid, $user_mod))) {
        return '/commune/';
    }
    if (!$uid) {
        if ($action) {
            return "/commune/?id={$id}";
        }
        if ($site == 'Topic') {
        } else {
            if ($site == 'Join') {
                return '/fbd.php';
            } else {
                if ($site == 'Members') {
                    return '/fbd.php';
                } else {
                    if ($site) {
                        return "/commune/?id={$id}";
                    }
                }
            }
        }
    } else {
        if ($uStatus = commune::GetUserCommuneRel($id, $uid)) {
            $user_mod |= commune::MOD_COMM_MODERATOR * $uStatus['is_moderator'];
            $user_mod |= commune::MOD_COMM_MANAGER * $uStatus['is_manager'];
            $user_mod |= commune::MOD_COMM_ADMIN * ($uStatus['is_admin'] || $uStatus['is_moderator'] || $uStatus['is_manager']);
            $user_mod |= commune::MOD_COMM_AUTHOR * $uStatus['is_author'];
            $user_mod |= commune::MOD_COMM_ASKED * $uStatus['is_asked'];
            $user_mod |= commune::MOD_COMM_ACCEPTED * ($uStatus['is_accepted'] || $user_mod & commune::MOD_COMM_ADMIN);
            $user_mod |= commune::MOD_COMM_BANNED * $uStatus['is_banned'];
        }
    }
    if ($comm['is_blocked'] && !($user_mod & commune::MOD_MODER)) {
        if ($comm['author_id'] != $uid || $comm['author_id'] == $uid && ($site && $site != 'Members' || $action)) {
            return '/commune/';
        }
    }
    if ($user_mod & commune::MOD_COMM_BANNED && !hasPermissions('communes') && $comm['restrict_type'] != '00') {
        $error['name'] = 'Нет доступа в сообщество';
        $error['message'] = 'Вы находитесь в бан-листе этой группы. Вы можете обратиться к создателю группы:<br/><br/>' . '<div style="float:left">' . __commPrntUsrAvtr($comm, 'author_') . '</div>' . '<div style="padding-left:10px;float:left">' . __commPrntUsrInfo($comm, 'author_') . '</div>';
        return NULL;
    }
    $restrict_type = bitStr2Int($comm['restrict_type']);
    if ($restrict_type & commune::RESTRICT_READ_MASK) {
        if ($site != 'Join' && $action != 'Join' && !($user_mod & (commune::MOD_COMM_AUTHOR | commune::MOD_COMM_ACCEPTED | commune::MOD_ADMIN | commune::MOD_MODER))) {
            $error['name'] = 'Нет доступа в сообщество';
            if ($user_mod & commune::MOD_COMM_ASKED) {
                $error['message'] = "&nbsp;Администратор сообщества <b>&laquo;{$comm['name']}&raquo;</b> еще не рассмотрел вашу заявку. Просмотр этого сообщества вам не доступен.<br/><br/>" . __commPrntJoinButton($comm, $uid);
            } else {
                $error['message'] = "&nbsp;Вы не являетесь членом сообщества <b>&laquo;{$comm['name']}&raquo;</b>. Просмотр этого сообщества вам не доступен.<br/><br/>" . __commPrntJoinButton($comm, $uid);
            }
            return NULL;
        }
    }
    switch ($site) {
        case 'Join':
            //        if ( $user_mod & commune::MOD_COMM_AUTHOR )
            //          return "/commune/?id={$id}";
            //        if ( $user_mod & commune::MOD_COMM_ASKED )
            //          return "/commune/?id={$id}";
            break;
        case 'Create':
            if ($id) {
                return "/commune/?id={$id}";
            }
            break;
        case 'Edit':
            if (!($user_mod & (commune::MOD_ADMIN | commune::MOD_COMM_AUTHOR))) {
                return "/commune/?id={$id}";
            }
            break;
        case 'Admin':
            if (!($user_mod & (commune::MOD_ADMIN | commune::MOD_COMM_AUTHOR))) {
                if ($user_mod & commune::MOD_COMM_MANAGER) {
                    return "/commune/?id={$id}&site=Admin.members";
                }
                return "/commune/?id={$id}";
            }
            break;
        case 'Admin.members':
            if (!($user_mod & (commune::MOD_ADMIN | commune::MOD_COMM_AUTHOR | commune::MOD_COMM_MANAGER) || hasPermissions('communes'))) {
                return "/commune/?id={$id}";
            }
            break;
        case 'Topic':
            if ($action && $action != 'do.Edit.post' && $action != 'do.Create.post' && $action != 'add_comment' && $action != 'edit_comment' && $action != 'wysiwygUploadImage') {
                //if ($action && $action != 'Edit.post')
                return "/404.php";
            }
            if (!$top_id || !($top = commune::GetTopMessageByAnyOther($top_id, $uid, $user_mod, TRUE)) || $top['member_is_banned'] && $comm['restrict_type'] != '00' && ($action != 'do.Edit.post' && $action != 'do.Create.post') && !($user_mod & (commune::MOD_ADMIN | commune::MOD_COMM_AUTHOR | commune::MOD_COMM_MANAGER)) || $top['is_private'] == 't' && $top['user_id'] != $uid && !($user_mod & (commune::MOD_ADMIN | commune::MOD_COMM_AUTHOR | commune::MOD_COMM_MANAGER)) || $top['deleted_id'] && !hasPermissions('communes')) {
                return "/404.php";
            }
            break;
        case 'Members':
            break;
        case 'Newtopic':
            if (commune::isBannedCommune($user_mod)) {
                $error['name'] = 'Нет доступа';
                $error['message'] = 'Вы находитесь в бан-листе этой группы. Вы можете обратиться к создателю группы:<br/><br/>' . '<div style="float:left">' . __commPrntUsrAvtr($comm, 'author_') . '</div>' . '<div style="padding-left:10px;float:left">' . __commPrntUsrInfo($comm, 'author_') . '</div>';
                return NULL;
            }
            if (!($user_mod & commune::MOD_COMM_AUTHOR && !$comm['is_blocked']) && !($user_mod & (commune::MOD_ADMIN | commune::MOD_MODER | commune::MOD_COMM_ACCEPTED | commune::MOD_COMM_ADMIN | commune::MOD_COMM_MODERATOR | commune::MOD_COMM_ADMIN))) {
                return getFriendlyURL('commune_commune', $comm['id']);
            }
            break;
        case 'Editdraft':
            require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/drafts.php";
            $draftData = drafts::getDraft($draft_id, get_uid(false), 4);
            if (!$draftData) {
                return getFriendlyURL('commune_commune', $comm['id']);
            }
            break;
        case 'Edittopic':
            break;
        default:
            if ($site) {
                return "/404.php";
            }
            break;
    }
    if ($action) {
        if ($action == 'Delete' && !($user_mod & commune::MOD_ADMIN)) {
            return "/commune/?id={$id}";
        }
        if (!$site) {
            if (($action == 'do.Edit.post' || $action == 'do.Create.post') && $user_mod & (commune::MOD_ADMIN | commune::MOD_COMM_AUTHOR | commune::MOD_COMM_ACCEPTED)) {
                return NULL;
            }
            if ($action == 'Join') {
                return NULL;
            }
            return "/commune/?id={$id}";
        }
    }
    return NULL;
}