public function ProcessLiveEvents()
 {
     static $sql = "SELECT *, (moment <= NOW()) AS active FROM {poker_scheduler} WHERE uid IN (SELECT uid FROM {polling_users}) AND uid IN (SELECT uid FROM {poker_user_ext} WHERE dirty_flags) AND (`moment` <= NOW() OR `visible` = 1) AND (`trigger` like '%\"live\"%' OR (`trigger` like '%\"inbox\"%' AND NOT is_read)) ORDER BY moment ASC";
     //Gather all pending live events and unread ibox messages tasks
     $results = db_query($sql);
     $tasks = array();
     while ($task = db_fetch_object($results)) {
         $triggers = json_decode($task->trigger);
         if (is_array($triggers)) {
             $task->trigger = $triggers;
             foreach ($triggers as $trigger) {
                 $tasks[$task->uid][$trigger][$task->id_task] = $task;
             }
         }
     }
     //Process all tasks for each user
     foreach ($tasks as $uid => $user_tasks) {
         $this->ClearNewTask($uid);
         $user = CUserManager::instance()->User($uid, TRUE);
         //Trigger 'live' and 'inbox'
         $this->TriggerHelper('live', $user, $user_tasks);
         $this->TriggerHelper('inbox', $user, $user_tasks);
         //Check for unread inbox messages
         $mboxsize = count($user_tasks['inbox']);
         if ($mboxsize) {
             //Add messages if there is unread messages
             CMessageSpool::instance()->PushMsg($user, array("type" => "os_poker_messagebox", "body" => array("inbox" => $mboxsize, "picture" => $base_path . drupal_get_path('module', 'os_poker') . "/images/mailbox.png")));
         }
     }
 }
Example #2
0
 public static function GiveItem($item_id, $targets, $debug = FALSE)
 {
     require_once drupal_get_path('module', 'os_poker') . "/scheduler.class.php";
     require_once drupal_get_path('module', 'os_poker') . "/user.class.php";
     $user = CUserManager::instance()->CurrentUser();
     try {
         if (!is_array($targets) || count($targets) == 0) {
             throw new Exception(t('Bad parameter: !cause', array('!cause' => is_array($targets) ? t('$target is empty') : t('$targer is not an array'))));
         }
         $rawTargets = CUserManager::instance()->UserList($targets);
         $targets = array_filter($rawTargets, "_os_poker_user_accepts_gifts");
         $ntargets = count($targets);
         if ($ntargets == 0) {
             throw new Exception(t('No one of targets accepts gifts'));
         }
         $item = new CItem($item_id);
         //check if the item really exists
         /*
          ** User must pay !
          */
         $nchips = $user->Chips();
         $price = $item->price * $ntargets;
         if (bccomp($nchips, $price) < 0) {
             throw new Exception(t('User doesn\'t have enough money (!uc vs !cn needed).', array('!uc' => $nchips, '!cn' => $price)));
         }
         $sql = "INSERT INTO `{poker_operation}`\n\t\t\t\t   (`id_item`, `uid`, `source_uid`, `tstamp`)\n\t\t\t\t   VALUES ";
         foreach ($targets as $target) {
             $fields[] = "(%d, %d, %d, %s)";
             $values[] = $item->id_item;
             $values[] = $target->uid;
             $values[] = $user->uid;
             $values[] = "NOW()";
         }
         $sql .= implode(", ", $fields);
         $res = db_query($sql, $values);
         if ($res == FALSE) {
             throw new Exception(t('DB error : !message', array("!message" => db_error())));
         }
         /*
          ** Expiry
          */
         $operation_id = db_last_insert_id("{poker_operation}", "id_operation");
         $ttl = $item->ttl;
         if ($operation_id && !empty($ttl)) {
             //$operation_id -= (count($targets) - 1);
             foreach ($targets as $target) {
                 $gift = array('item' => $item->name, 'receiver' => $target->uid, 'sender' => $user->uid);
                 if ($target->ActiveItem() <= 0) {
                     $target->ActivateItem($operation_id, $gift);
                 } else {
                     //Send gift notification, even if the item is not activated
                     foreach ($target->Tables() as $table) {
                         foreach (CPoker::UsersAtTable($table->serial) as $notified_uid) {
                             CScheduler::instance()->RegisterTask(new CGiftNotificationMessage(), $notified_uid, array('live'), "-1 day", $gift);
                         }
                     }
                 }
                 CScheduler::instance()->RegisterTask(new CItemExpiry(), $target->uid, 'live', $ttl, array("id_operation" => $operation_id));
                 ++$operation_id;
                 $args["symbol"] = $item->picture;
                 $args["text"] = t("You just receive a !gift from !user", array("!gift" => substr($item->name, 0, 30), "!user" => $user->profile_nickname));
                 if (_os_poker_user_accepts_gifts($user)) {
                     $args["links"] = l(t("Send a gift in return"), "poker/shop/shop/1/buddy/" . $user->uid);
                 }
                 CMessageSpool::instance()->SendMessage($target->uid, $args);
             }
         }
         /*
          ** User must pay !
          */
         $user->SubChips($price);
         $user->Save();
     } catch (Exception $e) {
         if ($debug == TRUE) {
             throw $e;
         }
         return FALSE;
     }
     return TRUE;
 }
Example #3
0
 public function DailyGift()
 {
     $result = db_query("INSERT IGNORE INTO {poker_user_ext} (uid, last_gift) VALUES (%d, NOW())", $this->_user->uid);
     if ($result && db_affected_rows() == 0) {
         //No row affected, then the row for the user already exist and should be
         //updated only if (s)he has not sent the gift during the last 86400 seconds.
         $result = db_query("UPDATE {poker_user_ext} SET last_gift = NOW() WHERE uid = %d AND (last_gift IS NULL OR NOW() - last_gift > 86400)", $this->_user->uid);
     }
     //Only proceed if a row was affected by the previous INSERT or UPDATE query.
     if ($result && db_affected_rows() > 0) {
         $buddies = $this->Buddies(TRUE);
         $amount = 100;
         foreach ($buddies as $buddy) {
             $buddy->AddChips($amount);
             $buddy->Save();
             $args["symbol"] = 'chips';
             $args["text"] = t("You just receive a daily gift from !user", array("!user", $this->profile_nickname));
             CMessageSpool::instance()->SendMessage($buddy->uid, $args);
             //drupal_mail('os_poker', 'daily_gift', $buddy->mail, user_preferred_language($buddy->DrupalUser()), array('amount' => $amount, 'sender' => $this->DrupalUser(), 'account' => $buddy->DrupalUser()));
         }
     }
     return $result;
 }
Example #4
0
 public static function ShowReward($name, $player_uid, $prewards)
 {
     $args["symbol"] = $prewards[$name]["picture"];
     $args["text"] = t("You just won reward !name : !desc", array("!name" => $prewards[$name]["name"], "!desc" => $prewards[$name]["desc"]));
     CMessageSpool::instance()->SendSystemMessage($player_uid, $args);
     CMessageSpool::instance()->SendInstantMessage(array('text' => '<div class="poker_reward_' . os_poker_clean_css_identifier($name) . '">' . $args["text"] . '</div>', 'title' => t('Reward')), $player_uid);
     return $args;
 }
Example #5
0
 public function Run($context_user, $arguments)
 {
     if ($arguments) {
         CMessageSpool::instance()->PushMsg($context_user, $arguments);
     }
 }
function _os_poker_process_message_unsafe()
{
    static $poker_server_events = array('NONE', 'HAND', 'TOURNEY', 'BUY_IN', 'REFILL', 'PRIZE', 'REGISTER', 'UNREGISTER', 'LEAVE', 'SEAT', 'TOURNEY_START');
    $current_user = CUserManager::instance()->CurrentUser();
    $resp = array("errorMsg" => NULL, "error" => FALSE, "messages" => array());
    $message_type = trim(isset($_GET["type"]) ? trim($_GET["type"]) : "noop");
    if ($message_type == "os_poker_reward") {
        /* Reward message is a special message which comes without a current user context 
        		   args[0] = reward number
        		   args[1] = player serial
        		   args[2] = time_stamp
        		*/
        $all_rewards = CPoker::GetRewards();
        $params = json_decode($_GET['args'], TRUE);
        CPoker::ShowReward("reward" . $params[0], $params[1], $all_rewards);
        $resp["messages"][] = array("type" => "noop", "body" => NULL);
    }
    if ($current_user && $current_user->uid != 0) {
        switch ($message_type) {
            case "os_poker_sit_down":
                CPoker::CheckRewards("sit", $current_user->uid, json_decode($_GET["players"], TRUE));
                $resp["messages"][] = array("type" => "noop", "body" => NULL);
                break;
            case "os_poker_daily_gift":
                if ($current_user->DailyGift()) {
                    $resp["messages"][] = array('type' => 'os_poker_gift_sent', 'body' => array('text' => t('You have sent !amount free chips to !count buddies', array('!count' => count($current_user->Buddies()), '!amount' => 100))));
                } else {
                    $resp["messages"][] = array("type" => "noop", "body" => NULL);
                }
                break;
            case "os_poker_load_messagebox":
                CScheduler::instance()->Trigger("inbox");
                $mbox = CScheduler::instance()->GetUnreadTasks("inbox");
                $mboxsize = count($mbox);
                if ($_GET["msgcount"] != $mboxsize) {
                    $resp["messages"][] = array("type" => "os_poker_messagebox", "body" => array("inbox" => $mboxsize, "picture" => $base_path . drupal_get_path('module', 'os_poker') . "/images/mailbox.png"));
                } else {
                    $resp["messages"][] = array("type" => "noop", "body" => NULL);
                }
                break;
            case "os_poker_challenge_user":
                //TODO: limit challenge to 1 per sender/receiver
                if (isset($_GET["challengetarget"])) {
                    $target_user = CUserManager::instance()->User($_GET["challengetarget"]);
                    if ($target_user && $target_user->uid != 0 && $current_user->uid != $target_user->uid) {
                        //Wait for symbol, text, link
                        $args["symbol"] = 'chips';
                        $args["text"] = t("You just receive a headsup challenge from !user", array("!user" => $current_user->profile_nickname));
                        $args["links"] = "<a class='noreplace' href='javascript:void(0);' onclick='javascript:parent.os_poker_start_challenge(" . $current_user->uid . ", " . $target_user->uid . ");'>" . t("Accept") . "</a>/<a href='javascript:void(0);' >" . t("Refuse") . "</a>";
                        CMessageSpool::instance()->SendMessage($target_user->uid, $args);
                        $notification = array('text' => t("You just challenged !user", array("!user" => $target_user->profile_nickname ? $target_user->profile_nickname : variable_get('anonymous', t('Anonymous')))), 'title' => t('Challenge'));
                        CMessageSpool::instance()->SendInstantMessage($notification);
                        $resp["messages"][] = array("type" => "os_poker_notify", "body" => $notification);
                    }
                }
                break;
            case "os_poker_activate_item":
                if (isset($_GET["id_item"]) && is_numeric($_GET["id_item"])) {
                    $current_user->ActivateItem($_GET["id_item"]);
                } else {
                    trigger_error(t('Invalid item ID: %item_id', array('%item_id' => isset($_GET["id_item"]) ? $_GET["id_item"] : 'undefined')), E_USER_ERROR);
                }
                break;
            case "os_poker_invite_user":
                if (isset($_GET["target"])) {
                    $target_user = CUserManager::instance()->User($_GET["target"]);
                    if ($target_user && $target_user->uid != 0 && $current_user->uid != $target_user->uid) {
                        $tables = $current_user->Tables();
                        if (count($tables) > 0) {
                            $args["symbol"] = 'chips';
                            $args["text"] = t("!user is playing at table !table come and join", array("!user" => $current_user->profile_nickname, "!table" => $tables[0]->name));
                            //TODO : Check $_GET["online"] to send mail
                            CMessageSpool::instance()->SendMessage($target_user->uid, $args);
                            $notification = array('text' => t("You just invited !user to play", array("!user" => $target_user->profile_nickname ? $target_user->profile_nickname : variable_get('anonymous', t('Anonymous')))), 'title' => t('Invitation'));
                            CMessageSpool::instance()->SendInstantMessage($notification);
                            $resp["messages"][] = array("type" => "os_poker_notify", "body" => $notification);
                        }
                    }
                }
                break;
            case 'os_poker_trigger_error':
                trigger_error("Message triggered error.", E_USER_ERROR);
                break;
            case 'os_poker_trigger_exception':
                throw new Exception('Message triggered exception.');
                break;
            default:
                $resp["messages"][] = array("type" => "noop", "body" => NULL);
                break;
        }
    }
    if (in_array(drupal_strtoupper($message_type), $poker_server_events)) {
        if (preg_match('/\\[([^,]+),([^,]+),([^,]+)\\]/', $_GET['args'], $args)) {
            array_shift($args);
        }
        //Event setn from the poker server
        //TODO Authenticate the request... how ?
        switch ($message_type) {
            case 'BUY_IN':
                list($uid, $game_id, $amount) = $args;
                if (user_load($uid)) {
                    CScheduler::instance()->RegisterTask(new CUpdateUserChipsCount(), $uid, array('live'));
                    $resp["messages"][] = array("type" => "debug", "body" => t('Recevied BUY_IN for user !uid', array('!uid' => $uid)));
                } else {
                    trigger_error(t('Invalid user ID: %uid', array('%uid' => $uid)), E_USER_ERROR);
                }
                break;
            case 'TOURNEY_START':
                list($tourney_serial, $dummy1, $dummy2) = $args;
                $tourney_users = CPoker::TourneyRegisteredUsers($tourney_serial);
                foreach ($tourney_users as $tourney_user) {
                    if (user_load($tourney_user->user_serial)) {
                        CScheduler::instance()->RegisterTask(new CTourneyNotificationMessage(), $tourney_user->user_serial, array('live'), "-1 day", array($tourney_serial, $tourney_user->description_short, $tourney_user->table_serial));
                        $resp["messages"][] = array("type" => "debug", "body" => t('Recevied tourney start notification for user !uid', array('!uid' => $tourney_user->user_serial)));
                    }
                }
                break;
            case 'HAND':
            case 'TOURNEY':
            case 'REFILL':
            case 'PRIZE':
            case 'REGISTER':
            case 'UNREGISTER':
            case 'LEAVE':
            case 'SEAT':
            case 'NONE':
                $resp["messages"][] = array("type" => "noop", "body" => NULL);
                break;
        }
    } else {
        if (!$resp["messages"]) {
            $resp["messages"][] = array("type" => "noop", "body" => NULL);
        }
    }
    _os_poker_process_message_set_header();
    print json_encode($resp);
}