function process($user, $mensaje) { global $users, $users_exp; $string_instruccion = unwrap($mensaje); $_data_instruccion = explode(" ", $string_instruccion); $accion = $_data_instruccion[0]; say("< " . $accion); switch ($accion) { case "Bitacora": //Caso en que el usuario avisa que abrió la Bitácora de la experiencia "x" //->Mensaje enviado por el cliente: "Bitácora x" $experiencia = $_data_instruccion[1]; $ultima_experiencia = $user->experiencia_activa; if ($ultima_experiencia) { //Si el usuario ya tenia una bitácora activa asociada if ($ultima_experiencia != $experiencia) { //y diferente a la experiencia entrante, eliminarlo del arreglo respectivo say("Experiencia asociada al cliente distinta de la entrante"); $_array_exp_anterior = $users_exp[$ultima_experiencia]; //Obtiene el arreglo de usuarios que pertenecían a la experiencia anterior de aquel usuario que envió el mensaje if (($indice = array_search($user->id, $_array_exp_anterior)) !== false) { unset($_array_exp_anterior[$indice]); //Borra el id del socket del cliente del arreglo de clientes de la experiencia anterior $users_exp[$ultima_experiencia] = array_values($_array_exp_anterior); //Normaliza los indices numericos asociados al arreglo de clientes, //para mantener el orden correlativo despues de haber borrado el elemento say("Cliente borrado de la experiencia " . $ultima_experiencia); } } else { //En caso de que la nueva experiencia informada por el cliente sea la misma a la anterior, no debe cambiar nada say("El usuario ya estaba asociado a la experiencia " . $ultima_experiencia); break; } } if (!array_key_exists($experiencia, $users_exp)) { //En caso de que sea el primer cliente que ingresa a la bitácora de una cierta experiencia say("Primer cliente asociado a la experiencia id " . $experiencia); $users_exp[$experiencia] = array(); //Crea un arreglo de clientes para dicha experiencia } array_push($users_exp[$experiencia], $user->id); //Agrega el id del socket del cliente al arreglo de clientes de la experiencia $user->experiencia_activa = $experiencia; //Asocia la nueva experiencia como experiencia activa $users[$user->id] = $user; break; case "Actividad": $experiencia = $_data_instruccion[1]; //$id_usuario=$_data_instruccion[2]; $id_sesion = $_data_instruccion[2]; //Código agregado por Jordan Barría el 13-12-14 $tipo_bitacora = $_data_instruccion[3]; //multiCastMsjeActividadBitacora("Actividad ".$id_usuario." ".$tipo_bitacora." ".$experiencia,$experiencia,$tipo_bitacora); multiCastMsjeActividadBitacora("Actividad " . $id_sesion . " " . $tipo_bitacora . " " . $experiencia, $experiencia, $tipo_bitacora); //Código agregado por Jordan Barría el 13-12-14 break; default: break; } }
function process($user, $msg) { $action = unwrap($msg); say("< " . $action); switch ($action) { case "hello": send($user->socket, "hello human"); break; case "hi": send($user->socket, "zup human"); break; case "name": send($user->socket, "my name is Multivac, silly I know"); break; case "age": send($user->socket, "I am older than time itself"); break; case "date": send($user->socket, "today is " . date("Y.m.d")); break; case "time": send($user->socket, "server time is " . date("H:i:s")); break; case "thanks": send($user->socket, "you're welcome"); break; case "bye": send($user->socket, "bye"); break; default: send($user->socket, $action . " not understood"); break; } }
function process($user, $msg) { $action = unwrap($msg); $key = $action[0]; say("\$ < " . $action); global $users; switch ($key) { case 'c': broadcast($user, $action); break; case 'm': broadcast($user, $action); break; case 'd': broadcast(null, $action); break; case 'g': send($user->socket, $user->id); break; case 'a': send($user->socket, count($users)); break; case 'u': broadcast($user, $action); break; default: // if it is not a specific command then just relay it to all users say('Command "' . $action . '" not recognised'); break; } //switch ($key) }
function process($user, $msg) { $msg = unwrap($msg); // remove chr(0) and chr(255) say("< " . $msg); $parts = explode("|", $msg); // CHAT|NICK|MESSAGE $action = strtoupper($parts[0]); switch ($action) { case "HELO": welcome($user, $parts[1], $parts[2]); break; // HELO|NICK|AVATAR // HELO|NICK|AVATAR case "CHAT": chat($user, $parts[2]); break; // CHAT|NICK|MESSAGE // CHAT|NICK|MESSAGE case "PRIV": break; // TODO: private chat // TODO: private chat case "EXIT": goodbye($user); break; // EXIT|NICK // EXIT|NICK default: console($action . " not understood"); break; } }
function process($user_sent, $msg) { global $sockets, $users; $ms = unwrap($msg); $obj = json_decode($ms); $action = $obj->msg; say("< " . $action); foreach ($users as &$user) { if ($user != $user_sent) { send($user->socket, $action); } } }
function process($user, $msg) { $this->console($msg); if ($user->version == 8) { $action = decodeFrame($msg); } else { $action = unwrap($msg); } $this->say("< " . $action); switch ($action) { case "hello": $response = "hello human"; break; case "hi": $response = "zup human"; break; case "name": $response = "my name is Multivac, silly I know"; break; case "age": $response = "I am older than time itself"; break; case "date": $response = "today is " . date("Y.m.d"); break; case "time": $response = "server time is " . date("H:i:s"); break; case "thanks": $response = "you're welcome"; break; case "bye": $response = "bye"; break; default: $response = $action . " not understood"; break; } if ($user->version == 8) { $response = $this->encodeFrame($response); } $this->send($user->socket, $response); }
<?php include 'session.php'; include_once "connection.php"; include_once "database.php"; include_once "function.php"; $date_diff = ''; $contestant_user_id = $election_id_here = $joined = ""; $key = $_GET['key']; $contestant_user_id = unwrap($key); $election_id_here = $_SESSION["election_id_view"]; $sql1 = $connection1->prepare("SELECT contestant_id, picture_name, citation_name, post_id, nickname, election_id FROM contestants WHERE user_id='{$contestant_user_id}' AND election_id='{$election_id_here}'"); $sql1->execute(); $result1 = $sql1->setFetchMode(PDO::FETCH_ASSOC); $result1 = $sql1->fetchAll(); $joined = joined_id(user_id($myemail), $election_id_here); if (empty($result1) && strlen($_SESSION["election_id"]) != 1) { header("Location:postnews.php?key=" . $_SESSION["election_id"]); } elseif (empty($result1) && strlen($_SESSION["election_id"]) == 1) { header("Location:election_detailsNews.php?key=" . $_SESSION["election_key"]); } //Declaring images and citation directory $images_dir = "../images/contestants/"; $citation_dir = "../contestant_citation/"; //Declaring variables $contestant_fullname = $contestant_election_name = ""; $contestant_id = $contestant_nickname = $contestant_email = $contestant_phoneno = $contestant_post = $contestant_picture = $contestant_post_id = $contestant_citation = ""; $manifestos = array(); $sql = $connection1->prepare("SELECT fname, lname, email, phone FROM users WHERE user_id='{$contestant_user_id}'"); $sql->execute(); $result = $sql->setFetchMode(PDO::FETCH_ASSOC);
function process($user, $msg) { global $users; $user->last_message_time = time(); $umsg = unwrap($msg); console("< " . $umsg); $msg_obj = json_decode($umsg, true); $msg_obj['slot'] = $user->id; $type = $msg_obj['type']; switch ($type) { case 'KEEPALIVE': if (rand(0, 1000) & 1) { console('running keep alive checks ...'); $time = time(); foreach ($users as $u) { if ($time - $u->last_message_time > 35) { disconnect($u->socket); } } } break; case 'JOIN': // JOIN <WHITEBOARD_ID> $init = $user->id == null; $user->whiteboard_id = $msg_obj['key']; $ids = array(); foreach ($users as $u) { if ($u->whiteboard_id == $user->whiteboard_id && $u !== $user) { send($user->socket, json_encode(array('type' => 'JOIN', 'name' => $u->name, 'slot' => $u->id))); array_push($ids, $u->id); } } sort($ids); $user->id = 0; foreach ($ids as $id) { if ($id == $user->id) { $user->id += 1; } else { break; } } if ($user->name == 'Guest') { $user->name = "Guest-{$user->id}"; } send($user->socket, json_encode(array('type' => 'JOINED', 'slot' => $user->id))); $query = sprintf("SELECT * FROM `boards` WHERE `wb_id` = '%s' ORDER BY `index`", $user->whiteboard_id); $result = mysql_query($query); while ($row = mysql_fetch_assoc($result)) { send($user->socket, json_encode(array('type' => 'JCREATE', 'obj' => $row['obj'], 'slot' => $user->id))); } if ($init == true) { broadcast($user, json_encode(array('type' => 'JOIN', 'name' => $user->name, 'slot' => $user->id))); } break; default: if ($type == 'DELETE' || $type == 'UCREATE') { $obj = json_decode($msg_obj['obj'], true); $query = sprintf("DELETE FROM `boards` WHERE `wb_id` = '%s' AND `obj_id` = '%s';", mysql_real_escape_string($user->whiteboard_id), mysql_real_escape_string($obj['id'])); } else { if ($type == 'CLEAR') { $query = sprintf("DELETE FROM `boards` WHERE `wb_id` = '%s';", mysql_real_escape_string($user->whiteboard_id)); } else { $json = $msg_obj['obj']; $obj = json_decode($json, true); $query = sprintf("REPLACE INTO `boards` (`wb_id`, `obj_id`, `usr_id`, `obj`, `index`) VALUES ('%s', '%s', '%s', '%s', '%s');", mysql_real_escape_string($user->whiteboard_id), mysql_real_escape_string($obj['id']), mysql_real_escape_string($user->id), mysql_real_escape_string($json), mysql_real_escape_string($obj['index'])); } } $result = mysql_query($query); if (!$result) { say('Error inserting: ' . mysql_error()); } broadcast($user, json_encode($msg_obj)); break; } }
<?php /** * Created by PhpStorm. * User: gabriel * Date: 2/24/16 * Time: 3:38 PM */ include_once '../php/session.php'; include_once '../php/connection.php'; include_once "../php/database.php"; include_once '../php/photo.php'; require_once '../php/function.php'; include_once '../php/public.php'; $this_admin = $submit = $admin_picture = ''; //get election_id $election_id = unwrap($_GET['key']); //check if the election exists and public $check = $connection1->prepare("SELECT * FROM election WHERE election_id='{$election_id}' AND (privacy='11' OR privacy='12')"); $check->execute(); $check->setFetchMode(PDO::FETCH_ASSOC); $this_election = $check->fetchAll(); if (empty($this_election) && $error_msg == '') { //redirect to maindashboard header("Location:maindashboard.php"); } else { $this_election = $this_election[0]; $privacy_degree = $this_election['privacy']; $_SESSION['election_id'] = $this_election['election_id']; //get user_id $user_id = user_id($myemail); $_SESSION['user_id'] = $user_id;
print_time(); $result = Co::wait([curl('/rest', ['id' => 1, 'sleep' => 7]), function () { // Wait 4 sec print_r((yield [curl('/rest', ['id' => 2, 'sleep' => 3]), curl('/rest', ['id' => 3, 'sleep' => 4])])); print_time(); // Wait 2 sec print_r((yield [function () { // Wait 1 sec echo (yield curl('/rest', ['id' => 4, 'sleep' => 1])), "\n"; print_time(); return curl('/rest', ['id' => 5, 'sleep' => 1]); }, function () { // Wait 0 sec echo unwrap((yield CO::SAFE => curl('/invalid'))), "\n"; print_time(); try { // Wait 0 sec (yield curl('/invalid')); } catch (CURLException $e) { echo unwrap($e), "\n"; print_time(); } return ['x' => ['y' => function () { return (yield curl('/rest', ['id' => 6, 'sleep' => 2])); }]]; }])); print_time(); return curl('/rest', ['id' => 7, 'sleep' => 1]); }]); print_r($result); print_time();
if (!$updateErr) { $query_delete = "DELETE FROM news WHERE news_id='{$news_id}'"; if ($connection1->query($query_delete)) { header("Location:postnews.php?key=" . $key); } else { } } } if (!empty($_POST['cancel_delete_news']) && isset($_POST['cancel_delete_news'])) { header("Location:postnews.php?key=" . $key); } //fetching to the view contestant page $election_id = ""; if (isset($_GET['key'])) { $view_election_id = $_GET['key']; $election_id = unwrap($view_election_id); $_SESSION['election_id_view'] = $election_id; } //querying for news $view_posted_news = ""; $row1 = getAllMembers("users", ["fname", "lname", "picture_name"], ["user_id", "=", $user_id])[0]; $view_news_query = $connection1->prepare("SELECT * FROM news WHERE election_id = '{$election_id}' ORDER BY date_created DESC"); $view_news_query->execute(); $view_news_query->setFetchMode(PDO::FETCH_ASSOC); $row = $view_news_query->fetchAll(); for ($i = 0; $i < count($row); $i++) { $adminPhoto = $images_dir . $row1['picture_name']; $date_time1 = explode(" ", $row[$i]['date_created']); $date1 = getDateInterval($date_time1[0]); $time1 = timeString($date_time1[1]); $view_posted_news .= "<div class='me' style='margin-bottom:10px; ' >" . "<br>\n <label style='overflow:hidden;text-overflow:ellipsis;'>" . $row[$i]['news'] . "</label>\n <br>" . $date1 . " " . $time1 . "<br></div>";
function process($socket, $msg) { $action = unwrap($msg); say("< " . $action); //向客户端发送处理结果 send($socket, $msg); //$action }
function process($user, $msg) { $action = unwrap($msg); say("< " . $action); $request_body = json_decode($action, true); if (empty($request_body)) { say("ERROR: invalid request body"); return; } if (!array_key_exists("method", $request_body) || !array_key_exists("resource", $request_body) || !array_key_exists("msg_id", $request_body)) { say("ERROR: missing mandatory property"); return; } $method = $request_body["method"]; $resource = $request_body["resource"]; $result = NULL; if ($method == "POST" && $resource == "/user") { $result = do_signup($request_body); } else { if ($method == "POST" && $resource == "/contact") { say("process login"); $result = do_login($request_body, $user); } else { if ($method == "GET" && $resource == "/contact") { say("process whoisonline"); $result = do_whoisonline($user); } else { if ($method == "DELETE" && $resource == "/contact") { say("process logout"); $result = do_logout($user); } else { if ($method == "NOTIFY" && $resource == "/contact") { say("process notify"); $result = do_notify($request_body, $user); } else { if ($resource != "/user" && $resource != "/contact") { if ($method == "POST") { $result = do_post_resource($request_body, $user); } else { if ($method == "PUT") { $result = do_put_resource($request_body, $user); } else { if ($method == "GET") { $result = do_get_resource($request_body, $user); } else { if ($method == "DELETE") { $result = do_delete_resource($request_body, $user); } else { if ($method == "SUBSCRIBE") { $result = do_subscribe_resource($request_body, $user); } else { if ($method == "NOTIFY") { $result = do_publish_resource($request_body, $user); } } } } } } } else { // this is an unknown request $result = array("code" => "failed", "reason" => "unknown command " . $method . " " . $resource); } } } } } } $result['msg_id'] = $request_body['msg_id']; header("Content-type: application/json"); $param = json_encode($result); send($user->socket, $param); }
/** * Created by PhpStorm. * User: gabriel * Date: 2/17/16 * Time: 3:01 PM */ //include('session.php'); include '../php/connection.php'; include_once '../php/session.php'; include_once '../php/function.php'; include_once '../php/database.php'; $name_of_electionErr = $start_date_of_electionErr = $new_post_Err = $end_date_of_electionErr = $time_of_election_fromErr = $time_of_election_toErr = $messaging = $message2 = $post1 = $pin1 = $status_string = ""; $name_of_election = $name_of_election_temp = $start_date_of_election = $start_date_of_election1 = $end_date_of_election = $end_date_of_election1 = $time_of_election_from = $time_of_election_to = $election_pin = $result_display = ""; $dummy1 = $dummy2 = $dummy3 = $dummy4 = ""; $election_id = unwrap($_SESSION['election_id']); $this_election = getAllMembers("election", ["*"], ["election_id", "=", $election_id])[0]; //get all post and there corresponding pin $old_posts = array(); $post_pin = getAllMembers("posts", ["post_id,post_key,post"], ["election_id", "=", $election_id]); $post_string = '<div class="" style="text-align:left"><b>Post(s)</b><br>'; $pin_string = '<div class="" style="text-align:left"><b>Pin(s)</b><br>'; for ($i = 0; $i < count($post_pin); $i++) { array_push($old_posts, ucwords($post_pin[$i]["post"])); $post_id = $post_pin[$i]["post_id"]; $post_string .= $post_pin[$i]["post"] . '<br>'; $pin_string .= $post_pin[$i]["post_key"] . '<br>'; } $post_string .= '</div>'; $pin_string .= '</div>'; //get current date and current time
<?php include_once "connection.php"; include_once "database.php"; include_once 'function.php'; //session_start(); $election_id = $result1 = ""; include_once 'session.php'; if (isset($_GET["key"])) { $key = $_GET['key']; $election_id = unwrap($key); $_SESSION["election_id_view"] = $election_id; } if (empty($_SESSION["election_id_view"])) { header("Location:maindashboard.php"); } $election_id_here = $_SESSION["election_id_view"]; $sql1 = $connection1->prepare("SELECT * FROM contestants WHERE election_id ='{$election_id_here}'"); $sql1->execute(); $result1 = $sql1->setFetchMode(PDO::FETCH_ASSOC); $result1 = $sql1->fetchAll(); $images_dir = "../images/contestants/"; $contestants_id = $picture_names = $contestants_user_ids = array(); $contestants_post_id = array(); if (!empty($result1)) { for ($i = 0; $i < count($result1); $i++) { $contestants_id[$i] = $result1[$i]["contestant_id"]; $picture_names[$i] = $images_dir . $result1[$i]["picture_name"]; $contestants_user_ids[$i] = $result1[$i]["user_id"]; $contestants_post_id[$i] = $result1[$i]["post_id"]; }
echo (yield curl('/rest', ['id' => 3, 'sleep' => 1])), "\n"; print_time(); echo unwrap((yield Co::SAFE => function () { yield; throw new \RuntimeException('02'); })) . "\n"; (yield function () { yield; throw new \RuntimeException('03'); }); return 'Unreachable'; }, function () { echo unwrap((yield Co::SAFE => function () { yield; throw new \RuntimeException('04'); })) . "\n"; (yield function () { yield; throw new \RuntimeException('05'); }); return 'Unreachable'; }]))); echo unwrap((yield Co::SAFE => function () { (yield curl('/invalid')); return 'Unreachable'; })) . "\n"; // Wait 1 sec return curl('/rest', ['id' => 4, 'sleep' => 1]); }]); print_r($result); print_time();
while (($buffer = fgets($handle, 4096)) !== false) { if ($i++ == 0) { // Skip header // ISIN;Tipologia;Emittente;Descrizione;"Data di scadenza";"Valuta di negoziazione";S&P;"Q.tà Acquisto";"Prezzo Acquisto";"Prezzo Vendita";"Q.tà Vendita";"Prezzo ultimo contratto";"Rendimento effettivo a scadenza lordo";Sospeso continue; } $details = explode(';', $buffer); // print_r($details); $stock = new Stock(); if (!$stock->find_by_id($details[0])) { echo 'New stock'; $stock->isin = $details[0]; $stock->tipo = 'obbligazione'; $stock->title = unwrap($details[3]); $stock->divisa = $details[5]; $stock->rating = unwrap($details[6]); $stock->mercato = 'eurotlx'; $stock->_force_create = TRUE; print_r($stock); $stock->save(); } else { if ($stock->mercato == 'ita') { echo "Updating mercato for {$stock->isin}"; $stock->mercato = 'eurotlx'; $stock->save(); } } } if (!feof($handle)) { echo "Error: unexpected fgets() fail\n"; }
<?php error_reporting(0); include_once '../php/session.php'; include_once '../php/function.php'; if (isset($_SESSION['election_id'])) { $id = $_SESSION['election_id']; $election_id = unwrap($id); } else { header('Location: maindashboard.php'); } require_once '../php/add_edit.php'; require_once '../php/photo.php'; ?> <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>E-voting | Edit Participants</title> <link href="../images/logo.png" rel="icon"> <!-- Bootstrap Core CSS --> <link href="../css/bootstrap.min.css" rel="stylesheet">
function process($user, $msg) { $action = unwrap($msg); $obj = json_decode($action); if ($obj->data->method == "server") { //say("<".$user->socket." & ".$user->peer.": ".$action); $user->state = $obj->data->state; $user->prefer = $obj->data->prefer; $user->username = $obj->data->username; $enemy = getuserbysocket($user->peer); if ($user->state == 1 && $enemy->state == 1) { global $link; $myName = $user->username; $enemyName = $enemy->username; $result = mysql_query("SELECT * FROM user WHERE username='******'", $link) or die("Error in query:" . mysql_error()); if ($rows = mysql_fetch_array($result, MYSQL_ASSOC)) { $nickname = $rows['nickname']; } $result1 = mysql_query("SELECT * FROM user WHERE username='******'", $link) or die("Error in query:" . mysql_error()); if ($rows = mysql_fetch_array($result1, MYSQL_ASSOC)) { $nickname1 = $rows['nickname']; } $jsonData = '{"data":{"state" : 1,"nickname": "' . $nickname1 . '","prefer" : "' . $enemy->prefer . '","method":"server"}}'; $action = '{"data":{"state" : 1,"nickname": "' . $nickname . '","prefer" : "' . $user->prefer . '","method":"server"}}'; // //$jsonData = '{"data":{"state" : 1,"prefer" : "'.$enemy->prefer.'","method":"server"}}'; send($user->socket, $jsonData); send($user->peer, $action); } } else { switch ($obj->data->method) { case "ball": send($user->peer, $action); $obj->data->fromMe = 1; $actionNew = json_encode($obj); send($user->socket, $actionNew); break; case "ballin": getuserbysocket($user->peer)->score++; $scoreSelf = $user->score; $enemy = getuserbysocket($user->peer); $scoreEnemy = $enemy->score; send($user->socket, jsonEncode($scoreSelf, $scoreEnemy, 0)); send($user->peer, jsonEncode($scoreEnemy, $scoreSelf, 1)); if ($scoreSelf == 3 || $scoreEnemy == 3) { $jsonDataW = '{"data":{"state" :4,"systemMsg" : "Win","method":"system"}}'; $jsonDataL = '{"data":{"state" : 4,"systemMsg" : "Lose","method":"system"}}'; if ($scoreSelf == 3) { send($user->socket, $jsonDataW); send($user->peer, $jsonDataL); gameSet($user, $enemy, 1, -1); } if ($scoreEnemy == 3) { send($user->socket, $jsonDataL); send($user->peer, $jsonDataW); gameSet($user, $enemy, -1, 1); } $user->score = 0; getuserbysocket($user->peer)->score = 0; } break; default: say("<" . $user->socket . " 2 " . $user->peer . ": \n " . $action); sendPeer($user->socket, $action); } } }
function require_method($Method, $Target = false) { // A simple way to enforce usage of the intended HTTP method for a given page if (strcasecmp($_SERVER['REQUEST_METHOD'], $Method) === 0) { return; } error_log("Rejected non-{$Method} request for {$_SERVER['REQUEST_URI']}. \$_SERVER=" . unwrap(var_export(array_filter_keys($_SERVER, array("HTTP_REFERER", 'HTTP_USER_AGENT', 'HTTP_HOST', 'REQUEST_METHOD', 'REQUEST_URI', 'QUERY_STRING')), true))); redirect($Target); }
function process_multiple($user, $msg) { if ($user->version) { $user->pending_msg = $user->pending_msg . $msg; while ($user->pending_msg) { $m = $user->pending_msg; $opcode = ord($m[0]) & 0xf; $len = ord($m[1]) & 0x7f; # TODO: ignore the has-mask field and assume it to be 1. #say('opcode ' . $opcode . ' len ' . $len . ' raw ' . bin2hex($m)); if ($opcode != 0x1) { say('ERROR: only text opcode is supported'); return; } if ($len === 126) { $l1 = unpack('n', substr($m, 2, 2)); $len = $l1[1]; $masks = substr($m, 4, 4); $offset = 8; } else { if ($len === 127) { $l1 = unpack('N', substr($m, 2, 4)); $l2 = unpack('N', substr($m, 6, 4)); $len = $l1[1] * pow(2, 32) + $l2[1]; $masks = substr($m, 10, 4); $offset = 14; } else { $masks = substr($m, 2, 4); $offset = 6; } } say('offset ' . $offset . ' len ' . $len); if (strlen($m) < $offset + $len) { # not enough data yet say('ERROR: incomplete message.'); return; } $decoded = ""; $data = substr($m, $offset, $len); $user->pending_msg = substr($m, $offset + $len); for ($index = 0; $index < strlen($data); $index++) { $decoded .= $data[$index] ^ $masks[$index % 4]; } #say('decoded '. $opcode . ' ' . $decoded . ' raw ' . $data . ' offset ' . $offset . ' len ' . $len); if ($decoded) { process($user, $decoded); } } } else { $user->pending_msg = $user->pending_msg . $msg; if ($user->pending_msg[strlen($user->pending_msg) - 1] != chr(255)) { say("ERROR: incomplete message."); return; } $msg = $user->pending_msg; $user->pending_msg = ""; $first = 0; $last = 0; while ($last < strlen($msg)) { $first = strpos($msg, chr(0), $last); $last = strpos($msg, chr(255), $first) + 1; process($user, unwrap(substr($msg, $first, $last - $first))); } } }