6 Based on MSN class ver 2.0 by Tommy Wu, Ricky Su
\r
9 Documentation on the MSN protocol can be found at: http://msnpiki.msnfanatic.com/index.php/Main_Page
\r
11 This class uses MSNP15.
\r
13 In addition to PHP5, the additional php modules required are:
\r
14 curl pcre mhash mcrypt bcmath
\r
19 const PROTOCOL = 'MSNP15';
\r
20 const PASSPORT_URL = 'https://login.live.com/RST.srf';
\r
21 const BUILDVER = '8.1.0178';
\r
22 const PROD_KEY = 'PK}_A_0N_K%O?A9S';
\r
23 const PROD_ID = 'PROD0114ES4Z%Q5W';
\r
24 const LOGIN_METHOD = 'SSO';
\r
26 const OIM_SEND_URL = 'https://ows.messenger.msn.com/OimWS/oim.asmx';
\r
27 const OIM_SEND_SOAP = 'http://messenger.live.com/ws/2006/09/oim/Store2';
\r
29 const OIM_MAILDATA_URL = 'https://rsi.hotmail.com/rsi/rsi.asmx';
\r
30 const OIM_MAILDATA_SOAP = 'http://www.hotmail.msn.com/ws/2004/09/oim/rsi/GetMetadata';
\r
31 const OIM_READ_URL = 'https://rsi.hotmail.com/rsi/rsi.asmx';
\r
32 const OIM_READ_SOAP = 'http://www.hotmail.msn.com/ws/2004/09/oim/rsi/GetMessage';
\r
33 const OIM_DEL_URL = 'https://rsi.hotmail.com/rsi/rsi.asmx';
\r
34 const OIM_DEL_SOAP = 'http://www.hotmail.msn.com/ws/2004/09/oim/rsi/DeleteMessages';
\r
36 const MEMBERSHIP_URL = 'https://contacts.msn.com/abservice/SharingService.asmx';
\r
37 const MEMBERSHIP_SOAP = 'http://www.msn.com/webservices/AddressBook/FindMembership';
\r
39 const ADDMEMBER_URL = 'https://contacts.msn.com/abservice/SharingService.asmx';
\r
40 const ADDMEMBER_SOAP = 'http://www.msn.com/webservices/AddressBook/AddMember';
\r
42 const DELMEMBER_URL = 'https://contacts.msn.com/abservice/SharingService.asmx';
\r
43 const DELMEMBER_SOAP = 'http://www.msn.com/webservices/AddressBook/DeleteMember';
\r
45 // the message length (include header) is limited (maybe since WLM 8.5 released)
\r
46 // for WLM: 1664 bytes
\r
47 // for YIM: 518 bytes
\r
48 const MAX_MSN_MESSAGE_LEN = 1664;
\r
49 const MAX_YAHOO_MESSAGE_LEN = 518;
\r
57 private $password = '';
\r
58 private $NSfp = false;
\r
59 private $passport_policy = '';
\r
62 private $retry_wait;
\r
63 private $update_pending;
\r
64 private $PhotoStickerFile = false;
\r
65 private $Emotions = false;
\r
66 private $XFRReqTimeout = 60;
\r
67 private $SBStreamTimeout = 2;
\r
68 private $MsnObjArray = array();
\r
69 private $MsnObjMap = array();
\r
70 private $ABAuthHeader;
\r
74 private $server = 'messenger.hotmail.com';
\r
75 private $port = 1863;
\r
77 private $clientid = '';
\r
79 private $error = '';
\r
81 private $authed = false;
\r
83 private $oim_try = 3;
\r
85 private $font_fn = 'Arial';
\r
86 private $font_co = '333333';
\r
87 private $font_ef = '';
\r
89 // Begin added for StatusNet
\r
91 private $aContactList = array();
\r
92 private $aADL = array();
\r
95 * Holds session information indexed by screenname if
\r
96 * session has no socket or socket if socket present
\r
100 private $switchBoardSessions = array();
\r
103 * Holds sockets indexed by screenname
\r
107 private $switchBoardSessionLookup = array();
\r
110 * Holds references to sessions waiting for XFR
\r
114 private $waitingForXFR = array();
\r
117 * Event Handler Functions
\r
119 private $myEventHandlers = array();
\r
121 // End added for StatusNet
\r
124 * Constructor method
\r
126 * @param array $Configs Array of configuration options
\r
127 * 'user' - Username
\r
128 * 'password' - Password
\r
129 * 'alias' - Bot nickname
\r
130 * 'psm' - Bot personal status message
\r
131 * 'retry_wait' - Time to wait before trying to reconnect
\r
132 * 'update_pending' - Whether to update pending contacts
\r
133 * 'PhotoSticker' - Photo file to use (?)
\r
134 * 'debug' - Enable/Disable debugging mode
\r
135 * @param integer $timeout Connection timeout
\r
136 * @param integer $client_id Client id (hexadecimal)
\r
139 public function __construct ($Configs = array(), $timeout = 15, $client_id = 0x7000800C) {
\r
140 $this->user = $Configs['user'];
\r
141 $this->password = $Configs['password'];
\r
142 $this->alias = isset($Configs['alias']) ? $Configs['alias'] : '';
\r
143 $this->psm = isset($Configs['psm']) ? $Configs['psm'] : '';
\r
144 $this->retry_wait = isset($Configs['retry_wait']) ? $Configs['retry_wait'] : 30;
\r
145 $this->update_pending = isset($Configs['update_pending']) ? $Configs['update_pending'] : true;
\r
146 $this->PhotoStickerFile=isset($Configs['PhotoSticker']) ? $Configs['PhotoSticker'] : false;
\r
148 if ($this->Emotions = isset($Configs['Emotions']) ? $Configs['Emotions']:false) {
\r
149 foreach($this->Emotions as $EmotionFilePath)
\r
150 $this->MsnObj($EmotionFilePath,$Type=2);
\r
152 $this->debug = isset($Configs['debug']) ? $Configs['debug'] : false;
\r
153 $this->timeout = $timeout;
\r
156 if (!function_exists('curl_init')) throw new Exception("curl module not found!\n");
\r
157 if (!function_exists('preg_match')) throw new Exception("pcre module not found!\n");
\r
158 if (!function_exists('mhash')) throw new Exception("mhash module not found!\n");
\r
159 if (!function_exists('mcrypt_cbc')) throw new Exception("mcrypt module not found!\n");
\r
160 if (!function_exists('bcmod')) throw new Exception("bcmath module not found!\n");
\r
163 http://msnpiki.msnfanatic.com/index.php/Client_ID
\r
165 normal MSN 8.1 clientid is:
\r
166 01110110 01001100 11000000 00101100
\r
169 we just use following:
\r
170 * 0x04: Your client can send/receive Ink (GIF format)
\r
171 * 0x08: Your client can send/recieve Ink (ISF format)
\r
172 * 0x8000: This means you support Winks receiving (If not set the official Client will warn with 'contact has an older client and is not capable of receiving Winks')
\r
173 * 0x70000000: This is the value for MSNC7 (WL Msgr 8.1)
\r
176 $this->clientid = $client_id;
\r
177 $this->ABService = new SoapClient(realpath(dirname(__FILE__)).'/soap/msnab_sharingservice.wsdl', array('trace' => 1));
\r
185 * Connect to the NS server
\r
187 * @param String $user Username
\r
188 * @param String $password Password
\r
189 * @param String $redirect_server Redirect server
\r
190 * @param Integer $redirect_port Redirect port
\r
191 * @return Boolean Returns true if successful
\r
193 private function connect($user, $password, $redirect_server = '', $redirect_port = 1863) {
\r
195 if ($redirect_server === '') {
\r
196 $this->NSfp = @fsockopen($this->server, $this->port, $errno, $errstr, $this->timeout);
\r
197 if (!$this->NSfp) {
\r
198 $this->error = "!!! Could not connect to $this->server:$this->port, error => $errno, $errstr";
\r
203 $this->NSfp = @fsockopen($redirect_server, $redirect_port, $errno, $errstr, $this->timeout);
\r
204 if (!$this->NSfp) {
\r
205 $this->error = "!!! Could not connect to $redirect_server:$redirect_port, error => $errno, $errstr";
\r
209 $this->authed = false;
\r
211 // NS: >> VER {id} MSNP9 CVR0
\r
213 // NS: >>> VER {id} MSNP15 CVR0
\r
214 $this->ns_writeln("VER $this->id ".self::PROTOCOL.' CVR0');
\r
216 $start_tm = time();
\r
217 while (!self::socketcheck($this->NSfp)) {
\r
218 $data = $this->ns_readln();
\r
220 if ($data === false) {
\r
223 $this->ns_writeln("OUT");
\r
224 @fclose($this->NSfp);
\r
225 $this->error = 'Timeout, maybe protocol changed!';
\r
229 $code = substr($data, 0, 3);
\r
230 $start_tm = time();
\r
235 // NS: <<< VER {id} MSNP9 CVR0
\r
236 // NS: >>> CVR {id} 0x0409 winnt 5.1 i386 MSMSGS 6.0.0602 msmsgs {user}
\r
238 // NS: <<< VER {id} MSNP15 CVR0
\r
239 // NS: >>> CVR {id} 0x0409 winnt 5.1 i386 MSMSGS 8.1.0178 msmsgs {user}
\r
240 $this->ns_writeln("CVR $this->id 0x0409 winnt 5.1 i386 MSMSGS ".self::BUILDVER." msmsgs $user");
\r
245 // NS: <<< CVR {id} {ver_list} {download_serve} ....
\r
246 // NS: >>> USR {id} TWN I {user}
\r
248 // NS: <<< CVR {id} {ver_list} {download_serve} ....
\r
249 // NS: >>> USR {id} SSO I {user}
\r
250 $this->ns_writeln("USR $this->id ".self::LOGIN_METHOD." I $user");
\r
254 // already login for passport site, finish the login process now.
\r
255 // NS: <<< USR {id} OK {user} {verify} 0
\r
256 if ($this->authed) return true;
\r
257 // max. 16 digits for password
\r
258 if (strlen($password) > 16)
\r
259 $password = substr($password, 0, 16);
\r
261 $this->user = $user;
\r
262 $this->password = $password;
\r
263 // NS: <<< USR {id} SSO S {policy} {nonce}
\r
264 @list(/* USR */, /* id */, /* SSO */, /* S */, $policy, $nonce,) = @explode(' ', $data);
\r
266 $this->passport_policy = $policy;
\r
267 $aTickets = $this->get_passport_ticket();
\r
268 if (!$aTickets || !is_array($aTickets)) {
\r
271 $this->ns_writeln("OUT");
\r
272 @fclose($this->NSfp);
\r
273 $this->error = 'Passport authenticated fail!';
\r
277 $ticket = $aTickets['ticket'];
\r
278 $secret = $aTickets['secret'];
\r
279 $this->ticket = $aTickets;
\r
280 $login_code = $this->generateLoginBLOB($secret, $nonce);
\r
282 // NS: >>> USR {id} SSO S {ticket} {login_code}
\r
283 $this->ns_writeln("USR $this->id ".self::LOGIN_METHOD." S $ticket $login_code");
\r
284 $this->authed = true;
\r
288 // main login server will redirect to anther NS after USR command
\r
290 // NS: <<< XFR {id} NS {server} 0 {server}
\r
292 // NS: <<< XFR {id} NS {server} U D
\r
293 @list(/* XFR */, /* id */, $Type, $server, /* ... */) = @explode(' ', $data);
\r
294 if ($Type!='NS') break;
\r
295 @list($ip, $port) = @explode(':', $server);
\r
296 // this connection will close after XFR
\r
297 @fclose($this->NSfp);
\r
299 $this->NSfp = @fsockopen($ip, $port, $errno, $errstr, $this->timeout);
\r
300 if (!$this->NSfp) {
\r
301 $this->error = "Can't connect to $ip:$port, error => $errno, $errstr";
\r
306 // NS: >> VER {id} MSNP9 CVR0
\r
308 // NS: >>> VER {id} MSNP15 CVR0
\r
309 $this->ns_writeln("VER $this->id ".self::PROTOCOL.' CVR0');
\r
313 // return some policy data after 'USR {id} SSO I {user}' command
\r
314 // NS: <<< GCF 0 {size}
\r
315 @list(/* GCF */, /* 0 */, $size,) = @explode(' ', $data);
\r
316 // we don't need the data, just read it and drop
\r
317 if (is_numeric($size) && $size > 0)
\r
318 $this->ns_readdata($size);
\r
322 // we'll quit if got any error
\r
323 if (is_numeric($code)) {
\r
326 $this->ns_writeln("OUT");
\r
327 @fclose($this->NSfp);
\r
328 $this->error = "Error code: $code, please check the detail information from: http://msnpiki.msnfanatic.com/index.php/Reference:Error_List";
\r
331 // unknown response from server, just ignore it
\r
339 * Sign onto the NS server and retrieve the address book
\r
343 public function signon() {
\r
344 /* FIXME Don't implement the signon as a loop or we could hang
\r
345 * the queue handler! */
\r
346 $this->debug_message('*** Trying to connect to MSN network');
\r
350 if (!$this->connect($this->user, $this->password)) {
\r
351 $this->signonFailure("!!! Could not connect to server: $this->error");
\r
356 if ($this->UpdateContacts() === false) continue;
\r
358 // Get membership lists
\r
359 if (($this->aContactList = $this->getMembershipList()) === false) {
\r
360 $this->signonFailure('!!! Get membership list failed');
\r
364 if ($this->update_pending) {
\r
365 if (is_array($this->aContactList)) {
\r
366 $pending = 'Pending';
\r
367 foreach ($this->aContactList as $u_domain => $aUserList) {
\r
368 foreach ($aUserList as $u_name => $aNetworks) {
\r
369 foreach ($aNetworks as $network => $aData) {
\r
370 if (isset($aData[$pending])) {
\r
373 foreach (array('Allow', 'Reverse') as $list) {
\r
374 if (isset($aData[$list]))
\r
377 if ($this->addMemberToList($u_name.'@'.$u_domain, $network, $list)) {
\r
378 $this->aContactList[$u_domain][$u_name][$network][$list] = false;
\r
384 $id = $aData[$pending];
\r
385 // we can delete it from pending now
\r
386 if ($this->delMemberFromList($id, $u_name.'@'.$u_domain, $network, $pending))
\r
387 unset($this->aContactList[$u_domain][$u_name][$network][$pending]);
\r
392 foreach (array('Allow', 'Reverse') as $list) {
\r
393 if (!isset($aData[$list])) {
\r
394 if ($this->addMemberToList($u_name.'@'.$u_domain, $network, $list))
\r
395 $this->aContactList[$u_domain][$u_name][$network][$list] = false;
\r
407 if (is_array($this->aContactList)) {
\r
408 foreach ($this->aContactList as $u_domain => $aUserList) {
\r
409 $str = '<d n="'.$u_domain.'">';
\r
410 $len += strlen($str);
\r
412 $this->aADL[$n] = '<ml l="1">'.$sList.'</ml>';
\r
415 $len = strlen($str);
\r
418 foreach ($aUserList as $u_name => $aNetworks) {
\r
419 foreach ($aNetworks as $network => $status) {
\r
420 $str = '<c n="'.$u_name.'" l="3" t="'.$network.'" />';
\r
421 $len += strlen($str);
\r
422 // max: 7500, but <ml l="1"></d></ml> is 19,
\r
426 $this->aADL[$n] = '<ml l="1">'.$sList.'</ml>';
\r
428 $sList = '<d n="'.$u_domain.'">'.$str;
\r
429 $len = strlen($sList);
\r
438 $this->aADL[$n] = '<ml l="1">'.$sList.'</ml>';
\r
439 // NS: >>> BLP {id} BL
\r
440 $this->ns_writeln("BLP $this->id BL");
\r
441 foreach ($this->aADL as $str) {
\r
442 $len = strlen($str);
\r
443 // NS: >>> ADL {id} {size}
\r
444 $this->ns_writeln("ADL $this->id $len");
\r
445 $this->ns_writedata($str);
\r
447 // NS: >>> PRP {id} MFN name
\r
448 if ($this->alias == '') $this->alias = $user;
\r
449 $aliasname = rawurlencode($this->alias);
\r
450 $this->ns_writeln("PRP $this->id MFN $aliasname");
\r
451 //è¨å®šå€‹äººå¤§é è²¼
\r
452 //$MsnObj=$this->PhotoStckObj();
\r
453 // NS: >>> CHG {id} {status} {clientid} {msnobj}
\r
454 $this->ns_writeln("CHG $this->id NLN $this->clientid");
\r
455 if ($this->PhotoStickerFile !== false)
\r
456 $this->ns_writeln("CHG $this->id NLN $this->clientid ".rawurlencode($this->MsnObj($this->PhotoStickerFile)));
\r
457 // NS: >>> UUX {id} length
\r
458 $str = '<Data><PSM>'.htmlspecialchars($this->psm).'</PSM><CurrentMedia></CurrentMedia><MachineGuid></MachineGuid></Data>';
\r
459 $len = strlen($str);
\r
460 $this->ns_writeln("UUX $this->id $len");
\r
461 $this->ns_writedata($str);
\r
462 if (!self::socketcheck($this->NSfp)) {
\r
463 $this->debug_message('*** Connected, waiting for commands');
\r
466 $this->NSRetryWait($this->retry_wait);
\r
472 * Called if there is an error during signon
\r
474 * @param string $message Error message to log
\r
477 private function signonFailure($message) {
\r
478 $this->debug_message($message);
\r
479 $this->callHandler('ConnectFailed');
\r
480 $this->NSRetryWait($this->retry_wait);
\r
484 * Log out and close the NS connection
\r
488 private function nsLogout() {
\r
489 if (is_resource($this->NSfp) && !feof($this->NSfp)) {
\r
492 $this->ns_writeln("OUT");
\r
493 fclose($this->NSfp);
\r
494 $this->NSfp = false;
\r
495 $this->debug_message("*** Logged out");
\r
500 * NS and SB command handling methods
\r
504 * Read and handle incoming command from NS
\r
508 private function nsReceive() {
\r
509 // Sign in again if not signed in or socket failed
\r
510 if (!is_resource($this->NSfp) || self::socketcheck($this->NSfp)) {
\r
511 $this->callHandler('Reconnect');
\r
512 $this->NSRetryWait($this->retry_wait);
\r
517 $data = $this->ns_readln();
\r
518 if ($data === false) {
\r
519 // There was no data / an error when reading from the socket so reconnect
\r
520 $this->callHandler('Reconnect');
\r
521 $this->NSRetryWait($this->retry_wait);
\r
526 switch (substr($data, 0, 3)) {
\r
528 // after 'USR {id} OK {user} {verify} 0' response, the server will send SBS and profile to us
\r
529 // NS: <<< SBS 0 null
\r
535 // refresh ADL, so we re-send it again
\r
536 if (is_array($this->aADL)) {
\r
537 foreach ($this->aADL as $str) {
\r
538 $len = strlen($str);
\r
539 // NS: >>> ADL {id} {size}
\r
540 $this->ns_writeln("ADL $this->id $len");
\r
541 $this->ns_writedata($str);
\r
547 // NS: <<< LST {email} {alias} 11 0
\r
548 @list(/* LST */, $email, /* alias */,) = @explode(' ', $data);
\r
549 @list($u_name, $u_domain) = @explode('@', $email);
\r
550 if (!isset($this->aContactList[$u_domain][$u_name][1])) {
\r
551 $this->aContactList[$u_domain][$u_name][1]['Allow'] = 'Allow';
\r
552 $this->debug_message("*** Added to contact list: $u_name@$u_domain");
\r
557 // randomly, we get ADL command, someone add us to their contact list for MSNP15
\r
558 // NS: <<< ADL 0 {size}
\r
559 @list(/* ADL */, /* 0 */, $size,) = @explode(' ', $data);
\r
560 if (is_numeric($size) && $size > 0) {
\r
561 $data = $this->ns_readdata($size);
\r
562 preg_match('#<ml><d n="([^"]+)"><c n="([^"]+)"(.*) t="(\d*)"(.*) /></d></ml>#', $data, $matches);
\r
563 if (is_array($matches) && count($matches) > 0) {
\r
564 $u_domain = $matches[1];
\r
565 $u_name = $matches[2];
\r
566 $network = $matches[4];
\r
567 if (isset($this->aContactList[$u_domain][$u_name][$network]))
\r
568 $this->debug_message("*** Someone (network: $network) added us to their list (but already in our list): $u_name@$u_domain");
\r
572 foreach (array('Allow', 'Reverse') as $list) {
\r
573 if (!$this->addMemberToList($u_name.'@'.$u_domain, $network, $list)) {
\r
575 $this->debug_message("*** Could not add $u_name@$u_domain (network: $network) to $list list");
\r
578 $aTickets = $this->get_passport_ticket();
\r
579 if (!$aTickets || !is_array($aTickets)) {
\r
580 // failed to login? ignore it
\r
581 $this->debug_message("*** Could not re-login, something wrong here");
\r
582 $this->debug_message("*** Could not add $u_name@$u_domain (network: $network) to $list list");
\r
586 $this->ticket = $aTickets;
\r
587 $this->debug_message("**** Got new ticket, trying again");
\r
588 if (!$this->addMemberToList($u_name.'@'.$u_domain, $network, $list)) {
\r
589 $this->debug_message("*** Could not add $u_name@$u_domain (network: $network) to $list list");
\r
593 $this->aContactList[$u_domain][$u_name][$network][$list] = false;
\r
596 $this->debug_message("*** Someone (network: $network) added us to their list: $u_name@$u_domain");
\r
598 $str = '<ml l="1"><d n="'.$u_domain.'"><c n="'.$u_name.'" l="3" t="'.$network.'" /></d></ml>';
\r
599 $len = strlen($str);
\r
601 $this->callHandler('AddedToList', array('screenname' => $u_name.'@'.$u_domain, 'network' => $network));
\r
604 $this->debug_message("*** Someone added us to their list: $data");
\r
609 // randomly, we get RML command, someome remove us to their contact list for MSNP15
\r
610 // NS: <<< RML 0 {size}
\r
611 @list(/* RML */, /* 0 */, $size,) = @explode(' ', $data);
\r
612 if (is_numeric($size) && $size > 0) {
\r
613 $data = $this->ns_readdata($size);
\r
614 preg_match('#<ml><d n="([^"]+)"><c n="([^"]+)"(.*) t="(\d*)"(.*) /></d></ml>#', $data, $matches);
\r
615 if (is_array($matches) && count($matches) > 0) {
\r
616 $u_domain = $matches[1];
\r
617 $u_name = $matches[2];
\r
618 $network = $matches[4];
\r
619 if (isset($this->aContactList[$u_domain][$u_name][$network])) {
\r
620 $aData = $this->aContactList[$u_domain][$u_name][$network];
\r
622 foreach ($aData as $list => $id)
\r
623 $this->delMemberFromList($id, $u_name.'@'.$u_domain, $network, $list);
\r
625 unset($this->aContactList[$u_domain][$u_name][$network]);
\r
626 $this->debug_message("*** Someone (network: $network) removed us from their list: $u_name@$u_domain");
\r
629 $this->debug_message("*** Someone (network: $network) removed us from their list (but not in our list): $u_name@$u_domain");
\r
631 $this->callHandler('RemovedFromList', array('screenname' => $u_name.'@'.$u_domain, 'network' => $network));
\r
634 $this->debug_message("*** Someone removed us from their list: $data");
\r
639 // randomly, we get MSG notification from server
\r
640 // NS: <<< MSG Hotmail Hotmail {size}
\r
641 @list(/* MSG */, /* Hotmail */, /* Hotmail */, $size,) = @explode(' ', $data);
\r
642 if (is_numeric($size) && $size > 0) {
\r
643 $data = $this->ns_readdata($size);
\r
644 $aLines = @explode("\n", $data);
\r
648 foreach ($aLines as $line) {
\r
649 $line = rtrim($line);
\r
651 if ($line === '') {
\r
655 if (strncasecmp($line, 'Content-Type:', 13) == 0) {
\r
656 if (strpos($line, 'text/x-msmsgsinitialmdatanotification') === false && strpos($line, 'text/x-msmsgsoimnotification') === false) {
\r
657 // we just need text/x-msmsgsinitialmdatanotification
\r
658 // or text/x-msmsgsoimnotification
\r
665 if (strncasecmp($line, 'Mail-Data:', 10) == 0) {
\r
666 $maildata = trim(substr($line, 10));
\r
671 $this->debug_message("*** Ignoring MSG for: $line");
\r
674 if ($maildata == '') {
\r
675 $this->debug_message("*** Ignoring MSG not for OIM");
\r
679 if (strcasecmp($maildata, 'too-large') == 0) {
\r
680 $this->debug_message("*** Large mail-data, need to get the data via SOAP");
\r
681 $maildata = $this->getOIM_maildata();
\r
682 if ($maildata === false) {
\r
683 $this->debug_message("*** Could not get mail-data via SOAP");
\r
685 // maybe we need to re-login again
\r
686 $aTickets = $this->get_passport_ticket();
\r
687 if (!$aTickets || !is_array($aTickets)) {
\r
688 // failed to login? ignore it
\r
689 $this->debug_message("*** Could not re-login, something wrong here, ignoring this OIM");
\r
693 $this->ticket = $aTickets;
\r
694 $this->debug_message("*** Got new ticket, trying again");
\r
695 $maildata = $this->getOIM_maildata();
\r
696 if ($maildata === false) {
\r
697 $this->debug_message("*** Could not get mail-data via SOAP, and re-login already attempted, ignoring this OIM");
\r
702 // could be a lots of <M>...</M>, so we can't use preg_match here
\r
706 $start = strpos($p, '<M>');
\r
707 $end = strpos($p, '</M>');
\r
708 if ($start === false || $end === false || $start > $end) break;
\r
710 $sOIM = substr($p, $start, $end - $start);
\r
712 $p = substr($p, $end);
\r
714 if (count($aOIMs) == 0) {
\r
715 $this->debug_message("*** Ignoring empty OIM");
\r
718 foreach ($aOIMs as $maildata) {
\r
719 // T: 11 for MSN, 13 for Yahoo
\r
720 // S: 6 for MSN, 7 for Yahoo
\r
721 // RT: the datetime received by server
\r
722 // RS: already read or not
\r
723 // SZ: size of message
\r
726 // F: always 00000000-0000-0000-0000-000000000009
\r
728 preg_match('#<T>(.*)</T>#', $maildata, $matches);
\r
729 if (count($matches) == 0) {
\r
730 $this->debug_message("*** Ignoring OIM maildata without <T>type</T>");
\r
733 $oim_type = $matches[1];
\r
734 if ($oim_type = 13)
\r
738 preg_match('#<E>(.*)</E>#', $maildata, $matches);
\r
739 if (count($matches) == 0) {
\r
740 $this->debug_message("*** Ignoring OIM maildata without <E>sender</E>");
\r
743 $oim_sender = $matches[1];
\r
744 preg_match('#<I>(.*)</I>#', $maildata, $matches);
\r
745 if (count($matches) == 0) {
\r
746 $this->debug_message("*** Ignoring OIM maildata without <I>msgid</I>");
\r
749 $oim_msgid = $matches[1];
\r
750 preg_match('#<SZ>(.*)</SZ>#', $maildata, $matches);
\r
751 $oim_size = (count($matches) == 0) ? 0 : $matches[1];
\r
752 preg_match('#<RT>(.*)</RT>#', $maildata, $matches);
\r
753 $oim_time = (count($matches) == 0) ? 0 : $matches[1];
\r
754 $this->debug_message("*** OIM received from $oim_sender, Time: $oim_time, MSGID: $oim_msgid, size: $oim_size");
\r
755 $sMsg = $this->getOIM_message($oim_msgid);
\r
756 if ($sMsg === false) {
\r
757 $this->debug_message("*** Could not get OIM, msgid = $oim_msgid");
\r
759 $this->debug_message("*** Could not get OIM via SOAP, and re-login already attempted, ignoring this OIM");
\r
762 $aTickets = $this->get_passport_ticket();
\r
763 if (!$aTickets || !is_array($aTickets)) {
\r
764 // failed to login? ignore it
\r
765 $this->debug_message("*** Could not re-login, something wrong here, ignoring this OIM");
\r
769 $this->ticket = $aTickets;
\r
770 $this->debug_message("*** get new ticket, try it again");
\r
771 $sMsg = $this->getOIM_message($oim_msgid);
\r
772 if ($sMsg === false) {
\r
773 $this->debug_message("*** Could not get OIM via SOAP, and re-login already attempted, ignoring this OIM");
\r
777 $this->debug_message("*** MSG (Offline) from $oim_sender (network: $network): $sMsg");
\r
778 $this->callHandler('IMin', array('sender' => $oim_sender, 'message' => $sMsg, 'network' => $network, 'offline' => true));
\r
784 // randomly, we get UBM, this is the message from other network, like Yahoo!
\r
785 // NS: <<< UBM {email} $network $type {size}
\r
786 @list(/* UBM */, $from_email, $network, $type, $size,) = @explode(' ', $data);
\r
787 if (is_numeric($size) && $size > 0) {
\r
788 $data = $this->ns_readdata($size);
\r
789 $aLines = @explode("\n", $data);
\r
793 foreach ($aLines as $line) {
\r
794 $line = rtrim($line);
\r
796 if ($line === '') {
\r
800 if (strncasecmp($line, 'TypingUser:', 11) == 0) {
\r
806 $aSubLines = @explode("\r", $line);
\r
807 foreach ($aSubLines as $str) {
\r
814 $this->debug_message("*** Ignoring message from $from_email: $line");
\r
817 $this->debug_message("*** MSG from $from_email (network: $network): $sMsg");
\r
818 $this->callHandler('IMin', array('sender' => $from_email, 'message' => $sMsg, 'network' => $network, 'offline' => false));
\r
823 // randomly, we get UBX notification from server
\r
824 // NS: <<< UBX email {network} {size}
\r
825 @list(/* UBX */, /* email */, /* network */, $size,) = @explode(' ', $data);
\r
826 // we don't need the notification data, so just ignore it
\r
827 if (is_numeric($size) && $size > 0)
\r
828 $this->ns_readdata($size);
\r
832 // randomly, we'll get challenge from server
\r
833 // NS: <<< CHL 0 {code}
\r
834 @list(/* CHL */, /* 0 */, $chl_code,) = @explode(' ', $data);
\r
835 $fingerprint = $this->getChallenge($chl_code);
\r
836 // NS: >>> QRY {id} {product_id} 32
\r
837 // NS: >>> fingerprint
\r
838 $this->ns_writeln("QRY $this->id ".self::PROD_ID.' 32');
\r
839 $this->ns_writedata($fingerprint);
\r
840 $this->ns_writeln("CHG $this->id NLN $this->clientid");
\r
841 if ($this->PhotoStickerFile !== false)
\r
842 $this->ns_writeln("CHG $this->id NLN $this->clientid ".rawurlencode($this->MsnObj($this->PhotoStickerFile)));
\r
845 // NS: <<< CHG {id} {status} {code}
\r
847 // change our status to online first
\r
851 // sometimes, NS will redirect to another NS
\r
853 // NS: <<< XFR {id} NS {server} 0 {server}
\r
855 // NS: <<< XFR {id} NS {server} U D
\r
856 // for normal switchboard XFR
\r
857 // NS: <<< XFR {id} SB {server} CKI {cki} U messenger.msn.com 0
\r
858 @list(/* XFR */, /* {id} */, $server_type, $server, /* CKI */, $cki_code, /* ... */) = @explode(' ', $data);
\r
859 @list($ip, $port) = @explode(':', $server);
\r
860 if ($server_type != 'SB') {
\r
862 // this connection will close after XFR
\r
867 $this->debug_message("NS: <<< XFR SB");
\r
868 $user = array_shift($this->waitingForXFR);
\r
869 $bSBresult = $this->switchboard_control($ip, $port, $cki_code, $User, $Message);
\r
871 $bSBresult = $this->switchboard_control($ip, $port, $cki_code, $aMSNUsers[$nCurrentUser], $sMessage);
\r
872 if ($bSBresult === false) {
\r
873 // error for switchboard
\r
874 $this->debug_message("!!! error for sending message to ".$aMSNUsers[$nCurrentUser]);
\r
875 $aOfflineUsers[] = $aMSNUsers[$nCurrentUser];
\r
879 // NS: <<< QNG {time}
\r
880 @list(/* QNG */, $ping_wait) = @explode(' ', $data);
\r
881 $this->callHandler('Pong', $ping_wait);
\r
885 if ($this->PhotoStickerFile !== false)
\r
886 $this->ns_writeln("CHG $this->id NLN $this->clientid ".rawurlencode($this->MsnObj($this->PhotoStickerFile)));
\r
888 $this->ns_writeln("CHG $this->id NLN $this->clientid");
\r
889 // someone is trying to talk to us
\r
890 // NS: <<< RNG {session_id} {server} {auth_type} {ticket} {email} {alias} U {client} 0
\r
891 $this->debug_message("NS: <<< RNG $data");
\r
892 @list(/* RNG */, $sid, $server, /* auth_type */, $ticket, $email, $name, ) = @explode(' ', $data);
\r
893 @list($sb_ip, $sb_port) = @explode(':', $server);
\r
894 $this->debug_message("*** RING from $email, $sb_ip:$sb_port");
\r
895 $this->addContact($email, 1, $email, true);
\r
896 $this->connectToSBSession('Passive', $sb_ip, $sb_port, $email, array('sid' => $sid, 'ticket' => $ticket));
\r
899 // force logout from NS
\r
901 $this->debug_message("*** LOGOUT from NS");
\r
902 return $this->nsLogout();
\r
905 $code = substr($data,0,3);
\r
906 if (is_numeric($code)) {
\r
907 $this->error = "Error code: $code, please check the detail information from: http://msnpiki.msnfanatic.com/index.php/Reference:Error_List";
\r
908 $this->debug_message("*** NS: $this->error");
\r
910 return $this->nsLogout();
\r
917 * Read and handle incoming command/message from
\r
918 * a switchboard session socket
\r
920 private function sbReceive($socket) {
\r
921 $intsocket = (int) $socket;
\r
922 $session = &$this->switchBoardSessions[$intsocket];
\r
924 if (feof($socket)) {
\r
925 // Unset session lookup value
\r
926 unset($this->switchBoardSessionLookup[$session['to']]);
\r
928 // Unset session itself
\r
929 unset($this->switchBoardSessions[$intsocket]);
\r
933 $id = &$session['id'];
\r
935 $data = $this->sb_readln($socket);
\r
936 $code = substr($data, 0, 3);
\r
939 // SB: <<< IRO {id} {rooster} {roostercount} {email} {alias} {clientid}
\r
940 @list(/* IRO */, /* id */, $cur_num, $total, $email, $alias, $clientid) = @explode(' ', $data);
\r
941 $this->debug_message("*** $email joined session");
\r
942 $session['joined'] = true;
\r
945 $this->debug_message("*** Quit for BYE");
\r
946 $this->endSBSession();
\r
949 // SB: <<< USR {id} OK {user} {alias}
\r
950 // we don't need the data, just ignore it
\r
951 // request user to join this switchboard
\r
952 // SB: >>> CAL {id} {user}
\r
953 $this->sb_writeln($socket, $id, "CAL $this->id $user");
\r
956 // SB: <<< CAL {id} RINGING {?}
\r
957 // we don't need this, just ignore, and wait for other response
\r
961 // SB: <<< JOI {user} {alias} {clientid?}
\r
963 // we don't need the data, just ignore it
\r
964 // no more user here
\r
965 $session['joined'] = true;
\r
968 // SB: <<< MSG {email} {alias} {len}
\r
969 @list(/* MSG */, $from_email, /* alias */, $len, ) = @explode(' ', $data);
\r
971 $data = $this->sb_readdata($socket, $len);
\r
972 $aLines = @explode("\n", $data);
\r
977 foreach ($aLines as $line) {
\r
978 $line = rtrim($line);
\r
980 if ($line === '') {
\r
984 if (strncasecmp($line, 'TypingUser:', 11) == 0) {
\r
985 // typing notification, just ignore
\r
989 if (strncasecmp($line, 'Chunk:', 6) == 0) {
\r
990 // we don't handle any split message, just ignore
\r
994 if (strncasecmp($line, 'Content-Type: application/x-msnmsgrp2p', 38) == 0) {
\r
995 // p2p message, ignore it, but we need to send acknowledgement for it...
\r
997 $p = strstr($data, "\n\n");
\r
999 if ($p === false) {
\r
1000 $p = strstr($data, "\r\n\r\n");
\r
1002 $sMsg = substr($p, 4);
\r
1005 $sMsg = substr($p, 2);
\r
1008 if (strncasecmp($line, 'Content-Type: application/x-', 28) == 0) {
\r
1009 // ignore all application/x-... message
\r
1011 // application/x-ms-ink => ink message
\r
1015 if (strncasecmp($line, 'Content-Type: text/x-', 21) == 0) {
\r
1016 // ignore all text/x-... message
\r
1018 // text/x-msnmsgr-datacast => nudge, voice clip....
\r
1019 // text/x-mms-animemoticon => customized animemotion word
\r
1030 $this->debug_message("*** Ignoring SB data from $from_email: $line");
\r
1034 // we will ignore any p2p message after sending acknowledgement
\r
1036 $len = strlen($sMsg);
\r
1037 $this->debug_message("*** p2p message from $from_email, size $len");
\r
1038 // header = 48 bytes
\r
1039 // content >= 0 bytes
\r
1040 // footer = 4 bytes
\r
1041 // so it need to >= 52 bytes
\r
1042 /*if ($len < 52) {
\r
1043 $this->debug_message("*** p2p: size error, less than 52!");
\r
1046 $aDwords = @unpack("V12dword", $sMsg);
\r
1047 if (!is_array($aDwords)) {
\r
1048 $this->debug_message("*** p2p: header unpack error!");
\r
1051 $this->debug_message("*** p2p: dump received message:\n".$this->dump_binary($sMsg));
\r
1052 $hdr_SessionID = $aDwords['dword1'];
\r
1053 $hdr_Identifier = $aDwords['dword2'];
\r
1054 $hdr_DataOffsetLow = $aDwords['dword3'];
\r
1055 $hdr_DataOffsetHigh = $aDwords['dword4'];
\r
1056 $hdr_TotalDataSizeLow = $aDwords['dword5'];
\r
1057 $hdr_TotalDataSizeHigh = $aDwords['dword6'];
\r
1058 $hdr_MessageLength = $aDwords['dword7'];
\r
1059 $hdr_Flag = $aDwords['dword8'];
\r
1060 $hdr_AckID = $aDwords['dword9'];
\r
1061 $hdr_AckUID = $aDwords['dword10'];
\r
1062 $hdr_AckSizeLow = $aDwords['dword11'];
\r
1063 $hdr_AckSizeHigh = $aDwords['dword12'];
\r
1064 $this->debug_message("*** p2p: header SessionID = $hdr_SessionID");
\r
1065 $this->debug_message("*** p2p: header Inentifier = $hdr_Identifier");
\r
1066 $this->debug_message("*** p2p: header Data Offset Low = $hdr_DataOffsetLow");
\r
1067 $this->debug_message("*** p2p: header Data Offset High = $hdr_DataOffsetHigh");
\r
1068 $this->debug_message("*** p2p: header Total Data Size Low = $hdr_TotalDataSizeLow");
\r
1069 $this->debug_message("*** p2p: header Total Data Size High = $hdr_TotalDataSizeHigh");
\r
1070 $this->debug_message("*** p2p: header MessageLength = $hdr_MessageLength");
\r
1071 $this->debug_message("*** p2p: header Flag = $hdr_Flag");
\r
1072 $this->debug_message("*** p2p: header AckID = $hdr_AckID");
\r
1073 $this->debug_message("*** p2p: header AckUID = $hdr_AckUID");
\r
1074 $this->debug_message("*** p2p: header AckSize Low = $hdr_AckSizeLow");
\r
1075 $this->debug_message("*** p2p: header AckSize High = $hdr_AckSizeHigh");
\r
1076 if ($hdr_Flag == 2) {
\r
1077 //This is an ACK from SB ignore....
\r
1078 $this->debug_message("*** p2p: //This is an ACK from SB ignore....:\n");
\r
1081 $MsgBody = $this->linetoArray(substr($sMsg, 48, -4));
\r
1082 $this->debug_message("*** p2p: body".print_r($MsgBody, true));
\r
1083 if (($MsgBody['EUF-GUID']=='{A4268EEC-FEC5-49E5-95C3-F126696BDBF6}')&&($PictureFilePath=$this->GetPictureFilePath($MsgBody['Context']))) {
\r
1085 if ($this->sb_readln($socket) === false) break;
\r
1087 $this->debug_message("*** p2p: Inv hdr:\n".$this->dump_binary(substr($sMsg, 0, 48)));
\r
1088 preg_match('/{([0-9A-F\-]*)}/i', $MsgBody['Via'], $Matches);
\r
1089 $BranchGUID = $Matches[1];
\r
1090 //it's an invite to send a display picture.
\r
1091 $new_id = ~$hdr_Identifier;
\r
1093 "LLLLLLLLLLLL", $hdr_SessionID,
\r
1096 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1101 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh
\r
1103 $footer = pack("L", 0);
\r
1104 $message = "MIME-Version: 1.0\r\nContent-Type: application/x-msnmsgrp2p\r\nP2P-Dest: $from_email\r\n\r\n$hdr$footer";
\r
1105 $len = strlen($message);
\r
1106 $this->sb_writeln($socket, $id, "MSG $this->id D $len");
\r
1107 $this->sb_writedata($socket, $message);
\r
1108 $this->debug_message("*** p2p: send display picture acknowledgement for $hdr_SessionID");
\r
1109 $this->debug_message("*** p2p: Invite ACK message:\n".$this->dump_binary($message));
\r
1110 $this->sb_readln($socket); // Read ACK;
\r
1111 $this->debug_message("*** p2p: Invite ACK Hdr:\n".$this->dump_binary($hdr));
\r
1113 //Send 200 OK message
\r
1114 $MessageContent="SessionID: ".$MsgBody['SessionID']."\r\n\r\n".pack("C", 0);
\r
1116 "MSNSLP/1.0 200 OK\r\n".
\r
1117 "To: <msnmsgr:".$from_email.">\r\n".
\r
1118 "From: <msnmsgr:".$this->user.">\r\n".
\r
1119 "Via: ".$MsgBody['Via']."\r\n".
\r
1120 "CSeq: ".($MsgBody['CSeq']+1)."\r\n".
\r
1121 "Call-ID: ".$MsgBody['Call-ID']."\r\n".
\r
1122 "Max-Forwards: 0\r\n".
\r
1123 "Content-Type: application/x-msnmsgr-sessionreqbody\r\n".
\r
1124 "Content-Length: ".strlen($MessageContent)."\r\n\r\n".
\r
1126 $hdr_TotalDataSizeLow=strlen($MessagePayload);
\r
1127 $hdr_TotalDataSizeHigh=0;
\r
1129 "LLLLLLLLLLLL", $hdr_SessionID,
\r
1132 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1133 strlen($MessagePayload),
\r
1141 "MIME-Version: 1.0\r\n".
\r
1142 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1143 "P2P-Dest: $from_email\r\n\r\n$hdr$MessagePayload$footer";
\r
1144 $this->sb_writeln($socket, $id, "MSG $this->id D ".strlen($message));
\r
1145 $this->sb_writedata($socket, $message);
\r
1146 $this->debug_message("*** p2p: dump 200 ok message:\n".$this->dump_binary($message));
\r
1147 $this->sb_readln($socket); // Read ACK;
\r
1149 $this->debug_message("*** p2p: 200 ok:\n".$this->dump_binary($hdr));
\r
1150 // send data preparation message
\r
1151 // send 4 null bytes as data
\r
1152 $hdr_TotalDataSizeLow = 4;
\r
1153 $hdr_TotalDataSizeHigh = 0 ;
\r
1157 $MsgBody['SessionID'],
\r
1160 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1161 $hdr_TotalDataSizeLow,
\r
1168 "MIME-Version: 1.0\r\n".
\r
1169 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1170 "P2P-Dest: $from_email\r\n\r\n$hdr".pack('L', 0)."$footer";
\r
1171 $this->sb_writeln($socket, $id, "MSG $this->id D ".strlen($message));
\r
1172 $this->sb_writedata($socket, $message);
\r
1173 $this->debug_message("*** p2p: dump send Data preparation message:\n".$this->dump_binary($message));
\r
1174 $this->debug_message("*** p2p: Data Prepare Hdr:\n".$this->dump_binary($hdr));
\r
1175 $this->sb_readln($socket); // Read ACK;
\r
1177 // send Data Content..
\r
1178 $footer=pack('N',1);
\r
1180 $FileSize=filesize($PictureFilePath);
\r
1181 if ($hTitle=fopen($PictureFilePath,'rb')) {
\r
1184 while (!feof($hTitle)) {
\r
1185 $FileContent = fread($hTitle, 1024);
\r
1186 $FileContentSize = strlen($FileContent);
\r
1189 $MsgBody['SessionID'],
\r
1200 "MIME-Version: 1.0\r\n".
\r
1201 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1202 "P2P-Dest: $from_email\r\n\r\n$hdr$FileContent$footer";
\r
1203 $this->sb_writeln($socket, $id, "MSG $this->id D ".strlen($message));
\r
1204 $this->sb_writedata($socket, $message);
\r
1205 $this->debug_message("*** p2p: dump send Data Content message $Offset / $FileSize :\n".$this->dump_binary($message));
\r
1206 $this->debug_message("*** p2p: Data Content Hdr:\n".$this->dump_binary($hdr));
\r
1207 //$this->SB_readln($socket);//Read ACK;
\r
1208 $Offset += $FileContentSize;
\r
1213 $MessageContent="\r\n".pack("C", 0);
\r
1215 "BYE MSNMSGR:MSNSLP/1.0\r\n".
\r
1216 "To: <msnmsgr:$from_email>\r\n".
\r
1217 "From: <msnmsgr:".$this->user.">\r\n".
\r
1218 "Via: MSNSLP/1.0/TLP ;branch={".$BranchGUID."}\r\n".
\r
1220 "Call-ID: ".$MsgBody['Call-ID']."\r\n".
\r
1221 "Max-Forwards: 0\r\n".
\r
1222 "Content-Type: application/x-msnmsgr-sessionclosebody\r\n".
\r
1223 "Content-Length: ".strlen($MessageContent)."\r\n\r\n".$MessageContent;
\r
1224 $footer=pack('N',0);
\r
1225 $hdr_TotalDataSizeLow=strlen($MessagePayload);
\r
1226 $hdr_TotalDataSizeHigh=0;
\r
1228 $hdr = pack("LLLLLLLLLLLL",
\r
1232 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1239 "MIME-Version: 1.0\r\n".
\r
1240 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1241 "P2P-Dest: $from_email\r\n\r\n$hdr$MessagePayload$footer";
\r
1242 $this->sb_writeln($socket, $id, "MSG $id D ".strlen($message));
\r
1244 $this->sb_writedata($socket, $message);
\r
1245 $this->debug_message("*** p2p: dump send BYE message :\n".$this->dump_binary($message));
\r
1250 //if ($hdr_Flag == 2) {
\r
1251 // just send ACK...
\r
1252 // $this->sb_writeln($socket, $id, "ACK $id");
\r
1255 if ($hdr_SessionID == 4) {
\r
1257 $this->debug_message("*** p2p: ignore flag 4");
\r
1260 $finished = false;
\r
1261 if ($hdr_TotalDataSizeHigh == 0) {
\r
1262 // only 32 bites size
\r
1263 if (($hdr_MessageLength + $hdr_DataOffsetLow) == $hdr_TotalDataSizeLow)
\r
1267 // we won't accept any file transfer
\r
1268 // so I think we won't get any message size need to use 64 bits
\r
1269 // 64 bits size here, can't count directly...
\r
1270 $totalsize = base_convert(sprintf("%X%08X", $hdr_TotalDataSizeHigh, $hdr_TotalDataSizeLow), 16, 10);
\r
1271 $dataoffset = base_convert(sprintf("%X%08X", $hdr_DataOffsetHigh, $hdr_DataOffsetLow), 16, 10);
\r
1272 $messagelength = base_convert(sprintf("%X", $hdr_MessageLength), 16, 10);
\r
1273 $now_size = bcadd($dataoffset, $messagelength);
\r
1274 if (bccomp($now_size, $totalsize) >= 0)
\r
1278 // ignore not finished split packet
\r
1279 $this->debug_message("*** p2p: ignore split packet, not finished");
\r
1282 //$new_id = ~$hdr_Identifier;
\r
1285 $hdr = pack("LLLLLLLLLLLL", $hdr_SessionID,
\r
1288 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1293 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh);
\r
1294 $footer = pack("L", 0);
\r
1295 $message = "MIME-Version: 1.0\r\nContent-Type: application/x-msnmsgrp2p\r\nP2P-Dest: $from_email\r\n\r\n$hdr$footer";
\r
1296 $len = strlen($message);
\r
1297 $this->sb_writeln($socket, $id, "MSG $id D $len");
\r
1299 $this->sb_writedata($socket, $message);
\r
1300 $this->debug_message("*** p2p: send acknowledgement for $hdr_SessionID");
\r
1301 $this->debug_message("*** p2p: dump sent message:\n".$this->dump_binary($hdr.$footer));
\r
1305 $this->debug_message("*** MSG from $from_email: $sMsg");
\r
1306 $this->callHandler('IMin', array('sender' => $from_email, 'message' => $sMsg, 'network' => $network, 'offline' => false));
\r
1309 $this->debug_message("*** User $user is offline. Trying OIM.");
\r
1310 $session['offline'] = true;
\r
1313 if (is_numeric($code)) {
\r
1314 $this->error = "Error code: $code, please check the detail information from: http://msnpiki.msnfanatic.com/index.php/Reference:Error_List";
\r
1315 $this->debug_message("*** SB: $this->error");
\r
1323 * Checks for new data and calls appropriate methods
\r
1325 * This method is usually called in an infinite loop to keep checking for new data
\r
1329 public function receive() {
\r
1330 // First, get an array of sockets that have data that is ready to be read
\r
1332 $ready = $this->getSockets();
\r
1333 $numrdy = stream_select($ready, $w = NULL, $x = NULL, NULL);
\r
1335 // Now that we've waited for something, go through the $ready
\r
1336 // array and read appropriately
\r
1338 foreach ($ready as $socket) {
\r
1339 if ($socket == $this->NSfp) {
\r
1340 $this->nsReceive();
\r
1342 $this->sbReceive($socket);
\r
1348 * Switchboard related methods
\r
1352 * Send a request for a switchboard session
\r
1354 * @param string $to Target email for switchboard session
\r
1356 private function reqSBSession($to) {
\r
1357 $this->debug_message("*** Request SB for $to");
\r
1358 $this->ns_writeln("XFR $this->id SB");
\r
1360 // Add to the queue of those waiting for a switchboard session reponse
\r
1361 $this->switchBoardSessions[$to] = array(
\r
1365 'joined' => false,
\r
1366 'offline' => false,
\r
1367 'XFRReqTime' => time()
\r
1369 $this->waitingForXFR[] = &$this->switchBoardSessions[$to];
\r
1373 * Following an XFR or RNG, connect to the switchboard session
\r
1375 * @param string $mode Mode, either 'Active' (in the case of XFR) or 'Passive' (in the case of RNG)
\r
1376 * @param string $ip IP of Switchboard
\r
1377 * @param integer $port Port of Switchboard
\r
1378 * @param string $to User on other end of Switchboard
\r
1379 * @param array $param Array of parameters - 'cki', 'ticket', 'sid'
\r
1380 * @return boolean true if successful
\r
1382 private function connectToSBSession($mode, $ip, $port, $to, $param) {
\r
1383 $this->debug_message("*** SB: Trying to connect to switchboard server $ip:$port");
\r
1385 $socket = @fsockopen($ip, $port, $errno, $errstr, $this->timeout);
\r
1387 $this->debug_message("*** SB: Can't connect to $ip:$port, error => $errno, $errstr");
\r
1391 // Store the socket in the lookup array
\r
1392 $this->switchBoardSessionLookup[$to] = $socket;
\r
1394 // Store the socket in the sessions array
\r
1395 $intsocket = (int) $socket;
\r
1396 $this->switchBoardSessions[$to] = array(
\r
1398 'socket' => $socket,
\r
1400 'joined' => false,
\r
1401 'offline' => false,
\r
1402 'XFRReqTime' => time()
\r
1405 // Change the index of the session to the socket
\r
1406 $this->switchBoardSessions[$intsocket] = $this->switchBoardSessions[$to];
\r
1407 unset($this->switchBoardSessions[$to]);
\r
1409 $id = &$this->switchBoardSessions[$intsocket]['id'];
\r
1411 if ($mode == 'Active') {
\r
1412 $cki_code = $param['cki'];
\r
1414 // SB: >>> USR {id} {user} {cki}
\r
1415 $this->sb_writeln($socket, $id, "USR $id $this->user $cki_code");
\r
1418 $ticket = $param['ticket'];
\r
1419 $sid = $param['sid'];
\r
1421 // SB: >>> ANS {id} {user} {ticket} {session_id}
\r
1422 $this->sb_writeln($socket, $id, "ANS $id $this->user $ticket $sid");
\r
1427 * Called when we want to end a switchboard session
\r
1428 * or a switchboard session ends
\r
1430 * @param resource $socket Socket
\r
1431 * @param boolean $killsession Whether to delete the session
\r
1434 private function endSBSession($socket) {
\r
1435 if (!self::socketcheck($socket)) {
\r
1436 $this->sb_writeln($socket, $fake = 0, 'OUT');
\r
1440 // Unset session lookup value
\r
1441 $intsocket = (int) $socket;
\r
1442 unset($this->switchBoardSessionLookup[$this->switchBoardSessions[$intsocket]['to']]);
\r
1444 // Unset session itself
\r
1445 unset($this->switchBoardSessions[$intsocket]);
\r
1449 * Send a message via an existing SB session
\r
1451 * @param string $to Recipient for message
\r
1452 * @param string $message Message
\r
1453 * @return boolean true on success
\r
1455 private function sendMessageViaSB($to, $message) {
\r
1456 $socket = $this->switchBoardSessionLookup[$to];
\r
1457 if (self::socketcheck($socket)) {
\r
1461 if (!$this->switchBoardSessions[$to]['joined']) {
\r
1462 // If our participant has not joined the session yet we can't message them!
\r
1466 $intsocket = (int) $socket;
\r
1467 $id = &$this->switchBoardSessions[$intsocket]['id'];
\r
1469 $aMessage = $this->getMessage($Message);
\r
1471 $MsnObjDefine=$this->GetMsnObjDefine($aMessage);
\r
1472 if ($MsnObjDefine !== '') {
\r
1473 $SendString="MIME-Version: 1.0\r\nContent-Type: text/x-mms-emoticon\r\n\r\n$MsnObjDefine";
\r
1474 $len = strlen($SendString);
\r
1475 // TODO handle failure during write to socket
\r
1476 $this->sb_writeln($socket, $id, "MSG $id N $len");
\r
1477 $this->sb_writedata($socket, $SendString);
\r
1479 $len = strlen($aMessage);
\r
1480 // TODO handle failure during write to socket
\r
1481 $this->sb_writeln($socket, $id, "MSG $id N $len");
\r
1482 $this->sb_writedata($socket, $aMessage);
\r
1484 // Don't close the SB session, we might as well leave it open
\r
1490 * Send a message to a user on another network
\r
1492 * @param string $to Intended recipient
\r
1493 * @param string $message Message
\r
1494 * @param integer $network Network
\r
1497 private function sendOtherNetworkMessage($to, $message, $network) {
\r
1498 $message = $this->getMessage($message, $network);
\r
1499 $len = strlen($message);
\r
1500 // TODO Introduce error checking for message sending
\r
1501 $this->ns_writeln("UUM $this->id $to $network 1 $len");
\r
1502 $this->ns_writedata($Message);
\r
1503 $this->debug_message("*** Sent to $to (network: $network):\n$Message");
\r
1510 * @param string $to To address in form user@host.com(@network)
\r
1511 * where network is 1 for MSN, 32 for Yahoo
\r
1512 * and 'Offline' for offline messages
\r
1513 * @param string $message Message
\r
1515 public function sendMessage($to, $message) {
\r
1516 if ($message != '') {
\r
1517 list($name, $host, $network) = explode('@', $to);
\r
1518 $network = $network == '' ? 1 : $network;
\r
1519 $recipient = $name.$host;
\r
1521 if ($network === 1) {
\r
1522 if (!isset($this->switchBoardSessionLookup[$recipient]) && (!isset($this->switchBoardSessions[$recipient])
\r
1523 || time() - $this->switchBoardSessions[$recipient]['XFRReqTime'] > $this->XFRReqTimeout)) {
\r
1524 $this->debug_message("*** No existing SB session or request has timed out");
\r
1525 $this->reqSBSession($recipient);
\r
1528 $socket = $this->switchBoardSessionLookup[$to];
\r
1529 if ($this->switchBoardSessions[(int) $socket]['offline']) {
\r
1530 $this->debug_message("*** Contact ($recipient) offline, sending OIM");
\r
1531 $this->endSBSession($socket);
\r
1532 return $this->sendMessage($recipient.'@Offline', $message);
\r
1534 $this->debug_message("*** Attempting to send message to $recipient using existing SB session");
\r
1536 if ($this->sendMessageViaSB($recipient, $message)) {
\r
1537 $this->debug_message('*** Message sent successfully');
\r
1540 $this->debug_message('*** Message sending failed, requesting new SB session');
\r
1541 $this->reqSBSession($to);
\r
1546 } elseif ($network == 'Offline') {
\r
1548 //FIXME: ä¿®æ£Send OIM
\r
1550 $re_login = false;
\r
1551 for ($i = 0; $i < $this->oim_try; $i++) {
\r
1552 if (($oim_result = $this->sendOIM($recipient, $message, $lockkey)) === true) break;
\r
1553 if (is_array($oim_result) && $oim_result['challenge'] !== false) {
\r
1554 // need challenge lockkey
\r
1555 $this->debug_message("*** Need challenge code for ".$oim_result['challenge']);
\r
1556 $lockkey = $this->getChallenge($oim_result['challenge']);
\r
1559 if ($oim_result === false || $oim_result['auth_policy'] !== false) {
\r
1561 $this->debug_message("*** Can't send OIM, but we already re-logged-in again, so returning false");
\r
1564 $this->debug_message("*** Can't send OIM, maybe ticket expired, trying to login again");
\r
1566 // Maybe we need to re-login again
\r
1567 if (!$this->get_passport_ticket()) {
\r
1568 $this->debug_message("*** Can't re-login, something went wrong here, returning false");
\r
1571 $this->debug_message("*** Getting new ticket and trying again");
\r
1578 return $this->sendOtherNetworkMessage($recipient, $message, $network);
\r
1589 * Get OIM mail data
\r
1591 * @return string mail data or false on failure
\r
1593 function getOIM_maildata() {
\r
1594 preg_match('#t=(.*)&p=(.*)#', $this->ticket['web_ticket'], $matches);
\r
1595 if (count($matches) == 0) {
\r
1596 $this->debug_message('*** No web ticket?');
\r
1599 $t = htmlspecialchars($matches[1]);
\r
1600 $p = htmlspecialchars($matches[2]);
\r
1601 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
1602 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
1603 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
1604 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
\r
1606 <PassportCookie xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1612 <GetMetadata xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi" />
\r
1614 </soap:Envelope>';
\r
1616 $header_array = array(
\r
1617 'SOAPAction: '.self::OIM_MAILDATA_SOAP,
\r
1618 'Content-Type: text/xml; charset=utf-8',
\r
1619 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Messenger '.self::BUILDVER.')'
\r
1622 $this->debug_message('*** URL: '.self::OIM_MAILDATA_URL);
\r
1623 $this->debug_message("*** Sending SOAP:\n$XML");
\r
1624 $curl = curl_init();
\r
1625 curl_setopt($curl, CURLOPT_URL, self::OIM_MAILDATA_URL);
\r
1626 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
1627 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1628 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
1629 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
1630 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1631 curl_setopt($curl, CURLOPT_POST, 1);
\r
1632 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
1633 $data = curl_exec($curl);
\r
1634 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
1635 curl_close($curl);
\r
1636 $this->debug_message("*** Get Result:\n$data");
\r
1638 if ($http_code != 200) {
\r
1639 $this->debug_message("*** Could not get OIM maildata! http code: $http_code");
\r
1643 // <GetMetadataResponse xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">See #XML_Data</GetMetadataResponse>
\r
1644 preg_match('#<GetMetadataResponse([^>]*)>(.*)</GetMetadataResponse>#', $data, $matches);
\r
1645 if (count($matches) == 0) {
\r
1646 $this->debug_message('*** Could not get OIM maildata');
\r
1649 return $matches[2];
\r
1653 * Fetch OIM message with given id
\r
1655 * @param string $msgid
\r
1656 * @return string Message or false on failure
\r
1658 function getOIM_message($msgid) {
\r
1659 preg_match('#t=(.*)&p=(.*)#', $this->ticket['web_ticket'], $matches);
\r
1660 if (count($matches) == 0) {
\r
1661 $this->debug_message('*** No web ticket?');
\r
1664 $t = htmlspecialchars($matches[1]);
\r
1665 $p = htmlspecialchars($matches[2]);
\r
1668 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
1669 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
1670 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
1671 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
\r
1673 <PassportCookie xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1679 <GetMessage xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1680 <messageId>'.$msgid.'</messageId>
\r
1681 <alsoMarkAsRead>false</alsoMarkAsRead>
\r
1684 </soap:Envelope>';
\r
1686 $header_array = array(
\r
1687 'SOAPAction: '.self::OIM_READ_SOAP,
\r
1688 'Content-Type: text/xml; charset=utf-8',
\r
1689 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Messenger '.self::BUILDVER.')'
\r
1692 $this->debug_message('*** URL: '.self::OIM_READ_URL);
\r
1693 $this->debug_message("*** Sending SOAP:\n$XML");
\r
1694 $curl = curl_init();
\r
1695 curl_setopt($curl, CURLOPT_URL, self::OIM_READ_URL);
\r
1696 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
1697 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1698 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
1699 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
1700 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1701 curl_setopt($curl, CURLOPT_POST, 1);
\r
1702 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
1703 $data = curl_exec($curl);
\r
1704 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
1705 curl_close($curl);
\r
1706 $this->debug_message("*** Get Result:\n$data");
\r
1708 if ($http_code != 200) {
\r
1709 $this->debug_message("*** Can't get OIM: $msgid, http code = $http_code");
\r
1713 // why can't use preg_match('#<GetMessageResult>(.*)</GetMessageResult>#', $data, $matches)?
\r
1715 $start = strpos($data, '<GetMessageResult>');
\r
1716 $end = strpos($data, '</GetMessageResult>');
\r
1717 if ($start === false || $end === false || $start > $end) {
\r
1718 $this->debug_message("*** Can't get OIM: $msgid");
\r
1721 $lines = substr($data, $start + 18, $end - $start);
\r
1722 $aLines = @explode("\n", $lines);
\r
1726 foreach ($aLines as $line) {
\r
1727 $line = rtrim($line);
\r
1729 if ($line === '') {
\r
1735 // stop at empty lines
\r
1736 if ($line === '') break;
\r
1739 $sMsg = base64_decode($sOIM);
\r
1740 //$this->debug_message("*** we get OIM ($msgid): $sMsg");
\r
1743 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
1744 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
1745 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
1746 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
\r
1748 <PassportCookie xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1754 <DeleteMessages xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1756 <messageId>'.$msgid.'</messageId>
\r
1760 </soap:Envelope>';
\r
1762 $header_array = array(
\r
1763 'SOAPAction: '.self::OIM_DEL_SOAP,
\r
1764 'Content-Type: text/xml; charset=utf-8',
\r
1765 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Messenger '.self::BUILDVER.')'
\r
1768 $this->debug_message('*** URL: '.self::OIM_DEL_URL);
\r
1769 $this->debug_message("*** Sending SOAP:\n$XML");
\r
1770 $curl = curl_init();
\r
1771 curl_setopt($curl, CURLOPT_URL, self::OIM_DEL_URL);
\r
1772 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
1773 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1774 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
1775 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
1776 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1777 curl_setopt($curl, CURLOPT_POST, 1);
\r
1778 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
1779 $data = curl_exec($curl);
\r
1780 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
1781 curl_close($curl);
\r
1782 $this->debug_message("*** Get Result:\n$data");
\r
1784 if ($http_code != 200)
\r
1785 $this->debug_message("*** Could not delete OIM: $msgid, http code = $http_code");
\r
1787 $this->debug_message("*** OIM ($msgid) deleted");
\r
1792 * Send offline message
\r
1794 * @param string $to Intended recipient
\r
1795 * @param string $sMessage Message
\r
1796 * @param string $lockkey Lock key
\r
1797 * @return mixed true on success or error data
\r
1799 private function sendOIM($to, $sMessage, $lockkey) {
\r
1800 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
1801 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
1802 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
1803 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
\r
1805 <From memberName="'.$this->user.'"
\r
1806 friendlyName="=?utf-8?B?'.base64_encode($this->user).'?="
\r
1809 xmlns="http://messenger.msn.com/ws/2004/09/oim/"
\r
1810 msnpVer="'.self::PROTOCOL.'"
\r
1811 buildVer="'.self::BUILDVER.'"/>
\r
1812 <To memberName="'.$to.'" xmlns="http://messenger.msn.com/ws/2004/09/oim/"/>
\r
1813 <Ticket passport="'.htmlspecialchars($this->ticket['oim_ticket']).'"
\r
1814 appid="'.self::PROD_ID.'"
\r
1815 lockkey="'.$lockkey.'"
\r
1816 xmlns="http://messenger.msn.com/ws/2004/09/oim/"/>
\r
1817 <Sequence xmlns="http://schemas.xmlsoap.org/ws/2003/03/rm">
\r
1818 <Identifier xmlns="http://schemas.xmlsoap.org/ws/2002/07/utility">http://messenger.msn.com</Identifier>
\r
1819 <MessageNumber>1</MessageNumber>
\r
1823 <MessageType xmlns="http://messenger.msn.com/ws/2004/09/oim/">text</MessageType>
\r
1824 <Content xmlns="http://messenger.msn.com/ws/2004/09/oim/">MIME-Version: 1.0
\r
1825 Content-Type: text/plain; charset=UTF-8
\r
1826 Content-Transfer-Encoding: base64
\r
1827 X-OIM-Message-Type: OfflineMessage
\r
1828 X-OIM-Run-Id: {DAB68CFA-38C9-449B-945E-38AFA51E50A7}
\r
1829 X-OIM-Sequence-Num: 1
\r
1831 '.chunk_split(base64_encode($sMessage)).'
\r
1834 </soap:Envelope>';
\r
1836 $header_array = array(
\r
1837 'SOAPAction: '.self::OIM_SEND_SOAP,
\r
1838 'Content-Type: text/xml',
\r
1839 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Messenger '.self::BUILDVER.')'
\r
1842 $this->debug_message('*** URL: '.self::OIM_SEND_URL);
\r
1843 $this->debug_message("*** Sending SOAP:\n$XML");
\r
1844 $curl = curl_init();
\r
1845 curl_setopt($curl, CURLOPT_URL, self::OIM_SEND_URL);
\r
1846 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
1847 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1848 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
1849 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
1850 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1851 curl_setopt($curl, CURLOPT_POST, 1);
\r
1852 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
1853 $data = curl_exec($curl);
\r
1854 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
1855 curl_close($curl);
\r
1856 $this->debug_message("*** Get Result:\n$data");
\r
1858 if ($http_code == 200) {
\r
1859 $this->debug_message("*** OIM sent for $to");
\r
1863 $challenge = false;
\r
1864 $auth_policy = false;
\r
1865 // the lockkey is invalid, authenticated fail, we need challenge it again
\r
1866 // <LockKeyChallenge xmlns="http://messenger.msn.com/ws/2004/09/oim/">364763969</LockKeyChallenge>
\r
1867 preg_match("#<LockKeyChallenge (.*)>(.*)</LockKeyChallenge>#", $data, $matches);
\r
1868 if (count($matches) != 0) {
\r
1869 // yes, we get new LockKeyChallenge
\r
1870 $challenge = $matches[2];
\r
1871 $this->debug_message("*** OIM need new challenge ($challenge) for $to");
\r
1873 // auth policy error
\r
1874 // <RequiredAuthPolicy xmlns="http://messenger.msn.com/ws/2004/09/oim/">MBI_SSL</RequiredAuthPolicy>
\r
1875 preg_match("#<RequiredAuthPolicy (.*)>(.*)</RequiredAuthPolicy>#", $data, $matches);
\r
1876 if (count($matches) != 0) {
\r
1877 $auth_policy = $matches[2];
\r
1878 $this->debug_message("*** OIM need new auth policy ($auth_policy) for $to");
\r
1880 if ($auth_policy === false && $challenge === false) {
\r
1881 //<faultcode xmlns:q0="http://messenger.msn.com/ws/2004/09/oim/">q0:AuthenticationFailed</faultcode>
\r
1882 preg_match("#<faultcode (.*)>(.*)</faultcode>#", $data, $matches);
\r
1883 if (count($matches) == 0) {
\r
1884 // no error, we assume the OIM is sent
\r
1885 $this->debug_message("*** OIM sent for $to");
\r
1888 $err_code = $matches[2];
\r
1889 //<faultstring>Exception of type 'System.Web.Services.Protocols.SoapException' was thrown.</faultstring>
\r
1890 preg_match("#<faultstring>(.*)</faultstring>#", $data, $matches);
\r
1891 if (count($matches) > 0)
\r
1892 $err_msg = $matches[1];
\r
1895 $this->debug_message("*** OIM failed for $to");
\r
1896 $this->debug_message("*** OIM Error code: $err_code");
\r
1897 $this->debug_message("*** OIM Error Message: $err_msg");
\r
1900 return array('challenge' => $challenge, 'auth_policy' => $auth_policy);
\r
1904 * Contact / Membership list methods
\r
1908 * Fetch contact list
\r
1910 * @return boolean true on success
\r
1912 private function UpdateContacts() {
\r
1913 $ABApplicationHeaderArray = array(
\r
1914 'ABApplicationHeader' => array(
\r
1915 ':' => array('xmlns' => 'http://www.msn.com/webservices/AddressBook'),
\r
1916 'ApplicationId' => 'CFE80F9D-180F-4399-82AB-413F33A1FA11',
\r
1917 'IsMigration' => false,
\r
1918 'PartnerScenario' => 'ContactSave'
\r
1922 $ABApplicationHeader = new SoapHeader('http://www.msn.com/webservices/AddressBook', 'ABApplicationHeader', $this->Array2SoapVar($ABApplicationHeaderArray));
\r
1923 $ABFindAllArray = array(
\r
1924 'ABFindAll' => array(
\r
1925 ':' => array('xmlns'=>'http://www.msn.com/webservices/AddressBook'),
\r
1926 'abId' => '00000000-0000-0000-0000-000000000000',
\r
1927 'abView' => 'Full',
\r
1928 'lastChange' => '0001-01-01T00:00:00.0000000-08:00',
\r
1931 $ABFindAll = new SoapParam($this->Array2SoapVar($ABFindAllArray), 'ABFindAll');
\r
1932 $this->ABService->__setSoapHeaders(array($ABApplicationHeader, $this->ABAuthHeader));
\r
1933 $this->Contacts = array();
\r
1935 $this->debug_message('*** Updating Contacts...');
\r
1936 $Result = $this->ABService->ABFindAll($ABFindAll);
\r
1937 $this->debug_message("*** Result:\n".print_r($Result, true)."\n".$this->ABService->__getLastResponse());
\r
1938 foreach($Result->ABFindAllResult->contacts->Contact as $Contact)
\r
1939 $this->Contacts[$Contact->contactInfo->passportName] = $Contact;
\r
1940 } catch(Exception $e) {
\r
1941 $this->debug_message("*** Update Contacts Error \nRequest:".$this->ABService->__getLastRequest()."\nError:".$e->getMessage());
\r
1950 * @param string $email
\r
1951 * @param integer $network
\r
1952 * @param string $display
\r
1953 * @param boolean $sendADL
\r
1954 * @return boolean true on success
\r
1956 private function addContact($email, $network, $display = '', $sendADL = false) {
\r
1957 if ($network != 1) return true;
\r
1958 if (isset($this->Contacts[$email])) return true;
\r
1960 $ABContactAddArray = array(
\r
1961 'ABContactAdd' => array(
\r
1962 ':' => array('xmlns' => 'http://www.msn.com/webservices/AddressBook'),
\r
1963 'abId' => '00000000-0000-0000-0000-000000000000',
\r
1964 'contacts' => array(
\r
1965 'Contact' => array(
\r
1966 ':' => array('xmlns' => 'http://www.msn.com/webservices/AddressBook'),
\r
1967 'contactInfo' => array(
\r
1968 'contactType' => 'LivePending',
\r
1969 'passportName' => $email,
\r
1970 'isMessengerUser' => true,
\r
1971 'MessengerMemberInfo' => array(
\r
1972 'DisplayName' => $email
\r
1977 'options' => array(
\r
1978 'EnableAllowListManagement' => true
\r
1982 $ABContactAdd = new SoapParam($this->Array2SoapVar($ABContactAddArray), 'ABContactAdd');
\r
1984 $this->debug_message("*** Adding Contact $email...");
\r
1985 $this->ABService->ABContactAdd($ABContactAdd);
\r
1986 } catch(Exception $e) {
\r
1987 $this->debug_message("*** Add Contact Error \nRequest:".$this->ABService->__getLastRequest()."\nError:".$e->getMessage());
\r
1990 if ($sendADL && !feof($this->NSfp)) {
\r
1991 @list($u_name, $u_domain) = @explode('@', $email);
\r
1992 foreach (array('1', '2') as $l) {
\r
1993 $str = '<ml l="1"><d n="'.$u_domain.'"><c n="'.$u_name.'" l="'.$l.'" t="'.$network.'" /></d></ml>';
\r
1994 $len = strlen($str);
\r
1995 // NS: >>> ADL {id} {size}
\r
1996 //TODO introduce error checking
\r
1997 $this->ns_writeln("ADL $this->id $len");
\r
1998 $this->ns_writedata($str);
\r
2001 $this->UpdateContacts();
\r
2006 * Remove contact from list
\r
2008 * @param integer $memberID
\r
2009 * @param string $email
\r
2010 * @param integer $network
\r
2011 * @param string $list
\r
2013 function delMemberFromList($memberID, $email, $network, $list) {
\r
2014 if ($network != 1 && $network != 32) return true;
\r
2015 if ($memberID === false) return true;
\r
2017 $ticket = htmlspecialchars($this->ticket['contact_ticket']);
\r
2018 if ($network == 1)
\r
2019 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2020 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2021 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2022 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2023 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2025 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2026 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2027 <IsMigration>false</IsMigration>
\r
2028 <PartnerScenario>ContactMsgrAPI</PartnerScenario>
\r
2029 </ABApplicationHeader>
\r
2030 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2031 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2032 <TicketToken>'.$ticket.'</TicketToken>
\r
2036 <DeleteMember xmlns="http://www.msn.com/webservices/AddressBook">
\r
2039 <Type>Messenger</Type>
\r
2040 <ForeignId></ForeignId>
\r
2044 <MemberRole>'.$list.'</MemberRole>
\r
2046 <Member xsi:type="PassportMember" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
\r
2047 <Type>Passport</Type>
\r
2048 <MembershipId>'.$memberID.'</MembershipId>
\r
2049 <State>Accepted</State>
\r
2056 </soap:Envelope>';
\r
2058 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2059 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2060 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2061 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2062 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2064 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2065 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2066 <IsMigration>false</IsMigration>
\r
2067 <PartnerScenario>ContactMsgrAPI</PartnerScenario>
\r
2068 </ABApplicationHeader>
\r
2069 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2070 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2071 <TicketToken>'.$ticket.'</TicketToken>
\r
2075 <DeleteMember xmlns="http://www.msn.com/webservices/AddressBook">
\r
2078 <Type>Messenger</Type>
\r
2079 <ForeignId></ForeignId>
\r
2083 <MemberRole>'.$list.'</MemberRole>
\r
2085 <Member xsi:type="EmailMember" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
\r
2086 <Type>Email</Type>
\r
2087 <MembershipId>'.$memberID.'</MembershipId>
\r
2088 <State>Accepted</State>
\r
2095 </soap:Envelope>';
\r
2097 $header_array = array(
\r
2098 'SOAPAction: '.self::DELMEMBER_SOAP,
\r
2099 'Content-Type: text/xml; charset=utf-8',
\r
2100 'User-Agent: MSN Explorer/9.0 (MSN 8.0; TmstmpExt)'
\r
2103 $this->debug_message('*** URL: '.self::DELMEMBER_URL);
\r
2104 $this->debug_message("*** Sending SOAP:\n$XML");
\r
2105 $curl = curl_init();
\r
2106 curl_setopt($curl, CURLOPT_URL, self::DELMEMBER_URL);
\r
2107 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
2108 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
2109 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
2110 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
2111 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
2112 curl_setopt($curl, CURLOPT_POST, 1);
\r
2113 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
2114 $data = curl_exec($curl);
\r
2115 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
2116 curl_close($curl);
\r
2117 $this->debug_message("*** Get Result:\n$data");
\r
2119 if ($http_code != 200) {
\r
2120 preg_match('#<faultcode>(.*)</faultcode><faultstring>(.*)</faultstring>#', $data, $matches);
\r
2121 if (count($matches) == 0) {
\r
2122 $this->debug_message("*** Could not delete member (network: $network) $email ($memberID) from $list list");
\r
2125 $faultcode = trim($matches[1]);
\r
2126 $faultstring = trim($matches[2]);
\r
2127 if (strcasecmp($faultcode, 'soap:Client') || stripos($faultstring, 'Member does not exist') === false) {
\r
2128 $this->debug_message("*** Could not delete member (network: $network) $email ($memberID) from $list list, error code: $faultcode, $faultstring");
\r
2131 $this->debug_message("*** Could not delete member (network: $network) $email ($memberID) from $list list, not present in list");
\r
2134 $this->debug_message("*** Member successfully deleted (network: $network) $email ($memberID) from $list list");
\r
2139 * Add contact to list
\r
2141 * @param string $email
\r
2142 * @param integer $network
\r
2143 * @param string $list
\r
2145 function addMemberToList($email, $network, $list) {
\r
2146 if ($network != 1 && $network != 32) return true;
\r
2147 $ticket = htmlspecialchars($this->ticket['contact_ticket']);
\r
2150 if ($network == 1)
\r
2151 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2152 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2153 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2154 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2155 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2157 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2158 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2159 <IsMigration>false</IsMigration>
\r
2160 <PartnerScenario>ContactMsgrAPI</PartnerScenario>
\r
2161 </ABApplicationHeader>
\r
2162 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2163 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2164 <TicketToken>'.$ticket.'</TicketToken>
\r
2168 <AddMember xmlns="http://www.msn.com/webservices/AddressBook">
\r
2171 <Type>Messenger</Type>
\r
2172 <ForeignId></ForeignId>
\r
2176 <MemberRole>'.$list.'</MemberRole>
\r
2178 <Member xsi:type="PassportMember" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
\r
2179 <Type>Passport</Type>
\r
2180 <State>Accepted</State>
\r
2181 <PassportName>'.$user.'</PassportName>
\r
2188 </soap:Envelope>';
\r
2190 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2191 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2192 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2193 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2194 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2196 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2197 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2198 <IsMigration>false</IsMigration>
\r
2199 <PartnerScenario>ContactMsgrAPI</PartnerScenario>
\r
2200 </ABApplicationHeader>
\r
2201 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2202 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2203 <TicketToken>'.$ticket.'</TicketToken>
\r
2207 <AddMember xmlns="http://www.msn.com/webservices/AddressBook">
\r
2210 <Type>Messenger</Type>
\r
2211 <ForeignId></ForeignId>
\r
2215 <MemberRole>'.$list.'</MemberRole>
\r
2217 <Member xsi:type="EmailMember" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
\r
2218 <Type>Email</Type>
\r
2219 <State>Accepted</State>
\r
2220 <Email>'.$user.'</Email>
\r
2223 <Name>MSN.IM.BuddyType</Name>
\r
2224 <Value>32:YAHOO</Value>
\r
2233 </soap:Envelope>';
\r
2234 $header_array = array(
\r
2235 'SOAPAction: '.self::ADDMEMBER_SOAP,
\r
2236 'Content-Type: text/xml; charset=utf-8',
\r
2237 'User-Agent: MSN Explorer/9.0 (MSN 8.0; TmstmpExt)'
\r
2240 $this->debug_message('*** URL: '.self::ADDMEMBER_URL);
\r
2241 $this->debug_message("*** Sending SOAP:\n$XML");
\r
2242 $curl = curl_init();
\r
2243 curl_setopt($curl, CURLOPT_URL, self::ADDMEMBER_URL);
\r
2244 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
2245 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
2246 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
2247 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
2248 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
2249 curl_setopt($curl, CURLOPT_POST, 1);
\r
2250 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
2251 $data = curl_exec($curl);
\r
2252 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
2253 curl_close($curl);
\r
2254 $this->debug_message("*** Get Result:\n$data");
\r
2256 if ($http_code != 200) {
\r
2257 preg_match('#<faultcode>(.*)</faultcode><faultstring>(.*)</faultstring>#', $data, $matches);
\r
2258 if (count($matches) == 0) {
\r
2259 $this->debug_message("*** Could not add member (network: $network) $email to $list list");
\r
2262 $faultcode = trim($matches[1]);
\r
2263 $faultstring = trim($matches[2]);
\r
2264 if (strcasecmp($faultcode, 'soap:Client') || stripos($faultstring, 'Member already exists') === false) {
\r
2265 $this->debug_message("*** Could not add member (network: $network) $email to $list list, error code: $faultcode, $faultstring");
\r
2268 $this->debug_message("*** Could not add member (network: $network) $email to $list list, already present");
\r
2271 $this->debug_message("*** Member successfully added (network: $network) $email to $list list");
\r
2276 * Get membership lists
\r
2278 * @param mixed $returnData Membership list or false on failure
\r
2280 function getMembershipList($returnData = false) {
\r
2281 $ticket = htmlspecialchars($this->ticket['contact_ticket']);
\r
2282 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2283 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2284 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2285 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2286 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2288 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2289 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2290 <IsMigration>false</IsMigration>
\r
2291 <PartnerScenario>Initial</PartnerScenario>
\r
2292 </ABApplicationHeader>
\r
2293 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2294 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2295 <TicketToken>'.$ticket.'</TicketToken>
\r
2299 <FindMembership xmlns="http://www.msn.com/webservices/AddressBook">
\r
2302 <ServiceType>Messenger</ServiceType>
\r
2303 <ServiceType>Invitation</ServiceType>
\r
2304 <ServiceType>SocialNetwork</ServiceType>
\r
2305 <ServiceType>Space</ServiceType>
\r
2306 <ServiceType>Profile</ServiceType>
\r
2311 </soap:Envelope>';
\r
2312 $header_array = array(
\r
2313 'SOAPAction: '.self::MEMBERSHIP_SOAP,
\r
2314 'Content-Type: text/xml; charset=utf-8',
\r
2315 'User-Agent: MSN Explorer/9.0 (MSN 8.0; TmstmpExt)'
\r
2317 $this->debug_message('*** URL: '.self::MEMBERSHIP_URL);
\r
2318 $this->debug_message("*** Sending SOAP:\n$XML");
\r
2319 $curl = curl_init();
\r
2320 curl_setopt($curl, CURLOPT_URL, self::MEMBERSHIP_URL);
\r
2321 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
2322 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
2323 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
2324 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
2325 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
2326 curl_setopt($curl, CURLOPT_POST, 1);
\r
2327 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
2328 $data = curl_exec($curl);
\r
2329 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
2330 curl_close($curl);
\r
2331 $this->debug_message("*** Get Result:\n$data");
\r
2333 if ($http_code != 200) return false;
\r
2335 $aMemberships = array();
\r
2337 //$this->debug_message("search p = $p");
\r
2338 $start = strpos($p, '<Membership>');
\r
2339 $end = strpos($p, '</Membership>');
\r
2340 if ($start === false || $end === false || $start > $end) break;
\r
2341 //$this->debug_message("start = $start, end = $end");
\r
2343 $sMembership = substr($p, $start, $end - $start);
\r
2344 $aMemberships[] = $sMembership;
\r
2345 //$this->debug_message("add sMembership = $sMembership");
\r
2346 $p = substr($p, $end);
\r
2348 //$this->debug_message("aMemberships = ".var_export($aMemberships, true));
\r
2350 $aContactList = array();
\r
2351 foreach ($aMemberships as $sMembership) {
\r
2352 //$this->debug_message("sMembership = $sMembership");
\r
2353 if (isset($matches)) unset($matches);
\r
2354 preg_match('#<MemberRole>(.*)</MemberRole>#', $sMembership, $matches);
\r
2355 if (count($matches) == 0) continue;
\r
2356 $sMemberRole = $matches[1];
\r
2357 //$this->debug_message("MemberRole = $sMemberRole");
\r
2358 if ($sMemberRole != 'Allow' && $sMemberRole != 'Reverse' && $sMemberRole != 'Pending') continue;
\r
2359 $p = $sMembership;
\r
2360 if (isset($aMembers)) unset($aMembers);
\r
2361 $aMembers = array();
\r
2363 //$this->debug_message("search p = $p");
\r
2364 $start = strpos($p, '<Member xsi:type="');
\r
2365 $end = strpos($p, '</Member>');
\r
2366 if ($start === false || $end === false || $start > $end) break;
\r
2367 //$this->debug_message("start = $start, end = $end");
\r
2369 $sMember = substr($p, $start, $end - $start);
\r
2370 $aMembers[] = $sMember;
\r
2371 //$this->debug_message("add sMember = $sMember");
\r
2372 $p = substr($p, $end);
\r
2374 //$this->debug_message("aMembers = ".var_export($aMembers, true));
\r
2375 foreach ($aMembers as $sMember) {
\r
2376 //$this->debug_message("sMember = $sMember");
\r
2377 if (isset($matches)) unset($matches);
\r
2378 preg_match('#<Member xsi\:type="([^"]*)">#', $sMember, $matches);
\r
2379 if (count($matches) == 0) continue;
\r
2380 $sMemberType = $matches[1];
\r
2381 //$this->debug_message("MemberType = $sMemberType");
\r
2383 preg_match('#<MembershipId>(.*)</MembershipId>#', $sMember, $matches);
\r
2384 if (count($matches) == 0) continue;
\r
2385 $id = $matches[1];
\r
2386 if ($sMemberType == 'PassportMember') {
\r
2387 if (strpos($sMember, '<Type>Passport</Type>') === false) continue;
\r
2389 preg_match('#<PassportName>(.*)</PassportName>#', $sMember, $matches);
\r
2391 else if ($sMemberType == 'EmailMember') {
\r
2392 if (strpos($sMember, '<Type>Email</Type>') === false) continue;
\r
2393 // Value is 32: or 32:YAHOO
\r
2394 preg_match('#<Annotation><Name>MSN.IM.BuddyType</Name><Value>(.*):(.*)</Value></Annotation>#', $sMember, $matches);
\r
2395 if (count($matches) == 0) continue;
\r
2396 if ($matches[1] != 32) continue;
\r
2398 preg_match('#<Email>(.*)</Email>#', $sMember, $matches);
\r
2400 if ($network == -1) continue;
\r
2401 if (count($matches) > 0) {
\r
2402 $email = $matches[1];
\r
2403 @list($u_name, $u_domain) = @explode('@', $email);
\r
2404 if ($u_domain == NULL) continue;
\r
2405 $aContactList[$u_domain][$u_name][$network][$sMemberRole] = $id;
\r
2406 $this->debug_message("*** Adding new contact (network: $network, status: $sMemberRole): $u_name@$u_domain ($id)");
\r
2410 return $aContactList;
\r
2414 * MsnObj related methods
\r
2419 * @param $FilePath 圖檔路徑
\r
2420 * @param $Type 檔案類型 3=>大é è²¼,2表情圖案
\r
2423 private function MsnObj($FilePath, $Type = 3) {
\r
2424 if (!($FileSize=filesize($FilePath))) return '';
\r
2425 $Location = md5($FilePath);
\r
2426 $Friendly = md5($FilePath.$Type);
\r
2427 if (isset($this->MsnObjMap[$Location])) return $this->MsnObjMap[$Location];
\r
2428 $sha1d = base64_encode(sha1(file_get_contents($FilePath), true));
\r
2429 $sha1c = base64_encode(sha1("Creator".$this->user."Size$FileSize"."Type$Type"."Location$Location"."Friendly".$Friendly."SHA1D$sha1d", true));
\r
2430 $this->MsnObjArray[$Location] = $FilePath;
\r
2431 $MsnObj = '<msnobj Creator="'.$this->user.'" Size="'.$FileSize.'" Type="'.$Type.'" Location="'.$Location.'" Friendly="'.$Friendly.'" SHA1D="'.$sha1d.'" SHA1C="'.$sha1c.'"/>';
\r
2432 $this->MsnObjMap[$Location] = $MsnObj;
\r
2433 $this->debug_message("*** p2p: addMsnObj $FilePath::$MsnObj\n");
\r
2437 private function GetPictureFilePath($Context) {
\r
2438 $MsnObj = base64_decode($Context);
\r
2439 if (preg_match('/location="(.*?)"/i', $MsnObj, $Match))
\r
2440 $location = $Match[1];
\r
2441 $this->debug_message("*** p2p: PictureFile[$location] ::All".print_r($this->MsnObjArray,true)."\n");
\r
2442 if ($location && isset($this->MsnObjArray[$location]))
\r
2443 return $this->MsnObjArray[$location];
\r
2447 private function GetMsnObjDefine($Message) {
\r
2448 $DefineString = '';
\r
2449 if (is_array($this->Emotions))
\r
2450 foreach ($this->Emotions as $Pattern => $FilePath) {
\r
2451 if (strpos($Message, $Pattern) !== false)
\r
2452 $DefineString .= "$Pattern\t".$this->MsnObj($FilePath, 2)."\t";
\r
2454 return $DefineString;
\r
2462 * Read data of specified size from NS socket
\r
2464 * @param integer $size Size to read
\r
2465 * @return string Data read
\r
2467 private function ns_readdata($size) {
\r
2470 while (!feof($this->NSfp)) {
\r
2471 $buf = @fread($this->NSfp, $size - $count);
\r
2473 $count += strlen($buf);
\r
2474 if ($count >= $size) break;
\r
2476 $this->debug_message("NS: data ($size/$count) <<<\n$data");
\r
2481 * Read line from the NS socket
\r
2483 * @return string Data read
\r
2485 private function ns_readln() {
\r
2486 $data = @fgets($this->NSfp, 4096);
\r
2487 if ($data !== false) {
\r
2488 $data = trim($data);
\r
2489 $this->debug_message("NS: <<< $data");
\r
2495 * Write line to NS socket
\r
2497 * Also increments id
\r
2499 * @param string $data Line to write to socket
\r
2502 private function ns_writeln($data) {
\r
2503 @fwrite($this->NSfp, $data."\r\n");
\r
2504 $this->debug_message("NS: >>> $data");
\r
2509 * Write data to NS socket
\r
2511 * @param string $data Data to write to socket
\r
2514 private function ns_writedata($data) {
\r
2515 @fwrite($this->NSfp, $data);
\r
2516 $this->debug_message("NS: >>> $data");
\r
2520 * Read data of specified size from given SB socket
\r
2522 * @param resource $socket SB socket
\r
2523 * @param integer $size Size to read
\r
2524 * @return string Data read
\r
2526 private function sb_readdata($socket, $size) {
\r
2529 while (!feof($socket)) {
\r
2530 $buf = @fread($socket, $size - $count);
\r
2532 $count += strlen($buf);
\r
2533 if ($count >= $size) break;
\r
2535 $this->debug_message("SB: data ($size/$count) <<<\n$data");
\r
2540 * Read line from given SB socket
\r
2542 * @param resource $socket SB Socket
\r
2543 * @return string Line read
\r
2545 private function sb_readln($socket) {
\r
2546 $data = @fgets($socket, 4096);
\r
2547 if ($data !== false) {
\r
2548 $data = trim($data);
\r
2549 $this->debug_message("SB: <<< $data");
\r
2555 * Write line to given SB socket
\r
2557 * Also increments id
\r
2559 * @param resource $socket SB socket
\r
2560 * @param integer $id Reference to SB id
\r
2561 * @param string $data Line to write
\r
2564 private function sb_writeln($socket, &$id, $data) {
\r
2565 @fwrite($socket, $data."\r\n");
\r
2566 $this->debug_message("SB: >>> $data");
\r
2571 * Write data to given SB socket
\r
2573 * @param resource $socket SB socket
\r
2574 * @param $data Data to write to socket
\r
2577 private function sb_writedata($socket, $data) {
\r
2578 @fwrite($socket, $data);
\r
2579 $this->debug_message("SB: >>> $data");
\r
2583 * Get all the sockets currently in use
\r
2585 * @return array Array of socket resources
\r
2587 public function getSockets() {
\r
2588 return array_merge(array($this->NSfp), $this->switchBoardSessionLookup);
\r
2592 * Checks socket for end of file
\r
2594 * @param resource $socket Socket to check
\r
2595 * @return boolean true if end of file (socket)
\r
2597 private static function socketcheck($socket){
\r
2598 $info = stream_get_meta_data($socket);
\r
2599 return $info['eof'];
\r
2603 * Key generation methods
\r
2606 private function derive_key($key, $magic) {
\r
2607 $hash1 = mhash(MHASH_SHA1, $magic, $key);
\r
2608 $hash2 = mhash(MHASH_SHA1, $hash1.$magic, $key);
\r
2609 $hash3 = mhash(MHASH_SHA1, $hash1, $key);
\r
2610 $hash4 = mhash(MHASH_SHA1, $hash3.$magic, $key);
\r
2611 return $hash2.substr($hash4, 0, 4);
\r
2614 private function generateLoginBLOB($key, $challenge) {
\r
2615 $key1 = base64_decode($key);
\r
2616 $key2 = $this->derive_key($key1, 'WS-SecureConversationSESSION KEY HASH');
\r
2617 $key3 = $this->derive_key($key1, 'WS-SecureConversationSESSION KEY ENCRYPTION');
\r
2619 // get hash of challenge using key2
\r
2620 $hash = mhash(MHASH_SHA1, $challenge, $key2);
\r
2622 // get 8 bytes random data
\r
2623 $iv = substr(base64_encode(rand(1000,9999).rand(1000,9999)), 2, 8);
\r
2625 $cipher = mcrypt_cbc(MCRYPT_3DES, $key3, $challenge."\x08\x08\x08\x08\x08\x08\x08\x08", MCRYPT_ENCRYPT, $iv);
\r
2627 $blob = pack('LLLLLLL', 28, 1, 0x6603, 0x8004, 8, 20, 72);
\r
2632 return base64_encode($blob);
\r
2636 * Generate challenge response
\r
2638 * @param string $code
\r
2639 * @return string challenge response code
\r
2641 private function getChallenge($code) {
\r
2643 // http://msnpiki.msnfanatic.com/index.php/MSNP11:Challenges
\r
2644 // Step 1: The MD5 Hash
\r
2645 $md5Hash = md5($code.self::PROD_KEY);
\r
2646 $aMD5 = @explode("\0", chunk_split($md5Hash, 8, "\0"));
\r
2647 for ($i = 0; $i < 4; $i++) {
\r
2648 $aMD5[$i] = implode('', array_reverse(@explode("\0", chunk_split($aMD5[$i], 2, "\0"))));
\r
2649 $aMD5[$i] = (0 + base_convert($aMD5[$i], 16, 10)) & 0x7FFFFFFF;
\r
2652 // Step 2: A new string
\r
2653 $chl_id = $code.self::PROD_ID;
\r
2654 $chl_id .= str_repeat('0', 8 - (strlen($chl_id) % 8));
\r
2656 $aID = @explode("\0", substr(chunk_split($chl_id, 4, "\0"), 0, -1));
\r
2657 for ($i = 0; $i < count($aID); $i++) {
\r
2658 $aID[$i] = implode('', array_reverse(@explode("\0", chunk_split($aID[$i], 1, "\0"))));
\r
2659 $aID[$i] = 0 + base_convert(bin2hex($aID[$i]), 16, 10);
\r
2662 // Step 3: The 64 bit key
\r
2663 $magic_num = 0x0E79A9C1;
\r
2664 $str7f = 0x7FFFFFFF;
\r
2667 for ($i = 0; $i < count($aID); $i += 2) {
\r
2669 $temp = bcmod(bcmul($magic_num, $temp), $str7f);
\r
2670 $temp = bcadd($temp, $high);
\r
2671 $temp = bcadd(bcmul($aMD5[0], $temp), $aMD5[1]);
\r
2672 $temp = bcmod($temp, $str7f);
\r
2674 $high = $aID[$i+1];
\r
2675 $high = bcmod(bcadd($high, $temp), $str7f);
\r
2676 $high = bcadd(bcmul($aMD5[2], $high), $aMD5[3]);
\r
2677 $high = bcmod($high, $str7f);
\r
2679 $low = bcadd(bcadd($low, $high), $temp);
\r
2682 $high = bcmod(bcadd($high, $aMD5[1]), $str7f);
\r
2683 $low = bcmod(bcadd($low, $aMD5[3]), $str7f);
\r
2685 $new_high = bcmul($high & 0xFF, 0x1000000);
\r
2686 $new_high = bcadd($new_high, bcmul($high & 0xFF00, 0x100));
\r
2687 $new_high = bcadd($new_high, bcdiv($high & 0xFF0000, 0x100));
\r
2688 $new_high = bcadd($new_high, bcdiv($high & 0xFF000000, 0x1000000));
\r
2689 // we need integer here
\r
2690 $high = 0+$new_high;
\r
2692 $new_low = bcmul($low & 0xFF, 0x1000000);
\r
2693 $new_low = bcadd($new_low, bcmul($low & 0xFF00, 0x100));
\r
2694 $new_low = bcadd($new_low, bcdiv($low & 0xFF0000, 0x100));
\r
2695 $new_low = bcadd($new_low, bcdiv($low & 0xFF000000, 0x1000000));
\r
2696 // we need integer here
\r
2697 $low = 0+$new_low;
\r
2699 // we just use 32 bits integer, don't need the key, just high/low
\r
2700 // $key = bcadd(bcmul($high, 0x100000000), $low);
\r
2702 // Step 4: Using the key
\r
2703 $md5Hash = md5($code.self::PROD_KEY);
\r
2704 $aHash = @explode("\0", chunk_split($md5Hash, 8, "\0"));
\r
2707 $hash .= sprintf("%08x", (0 + base_convert($aHash[0], 16, 10)) ^ $high);
\r
2708 $hash .= sprintf("%08x", (0 + base_convert($aHash[1], 16, 10)) ^ $low);
\r
2709 $hash .= sprintf("%08x", (0 + base_convert($aHash[2], 16, 10)) ^ $high);
\r
2710 $hash .= sprintf("%08x", (0 + base_convert($aHash[3], 16, 10)) ^ $low);
\r
2719 private function Array2SoapVar($Array, $ReturnSoapVarObj = true, $TypeName = null, $TypeNameSpace = null) {
\r
2720 $ArrayString = '';
\r
2721 foreach($Array as $Key => $Val) {
\r
2722 if ($Key{0} == ':') continue;
\r
2724 if (is_array($Val[':'])) {
\r
2725 foreach ($Val[':'] as $AttribName => $AttribVal)
\r
2726 $Attrib .= " $AttribName = '$AttribVal'";
\r
2728 if ($Key{0} == '!') {
\r
2729 //List Type Define
\r
2730 $Key = substr($Key,1);
\r
2731 foreach ($Val as $ListKey => $ListVal) {
\r
2732 if ($ListKey{0} == ':') continue;
\r
2733 if (is_array($ListVal)) $ListVal = $this->Array2SoapVar($ListVal, false);
\r
2734 elseif (is_bool($ListVal)) $ListVal = $ListVal ? 'true' : 'false';
\r
2735 $ArrayString .= "<$Key$Attrib>$ListVal</$Key>";
\r
2739 if (is_array($Val)) $Val = $this->Array2SoapVar($Val, false);
\r
2740 elseif (is_bool($Val)) $Val = $Val ? 'true' : 'false';
\r
2741 $ArrayString .= "<$Key$Attrib>$Val</$Key>";
\r
2743 if ($ReturnSoapVarObj) return new SoapVar($ArrayString, XSD_ANYXML, $TypeName, $TypeNameSpace);
\r
2744 return $ArrayString;
\r
2747 private function linetoArray($lines) {
\r
2748 $lines = str_replace("\r", '', $lines);
\r
2749 $lines = explode("\n", $lines);
\r
2750 foreach ($lines as $line) {
\r
2751 if (!isset($line{3})) continue;
\r
2752 list($Key, $Val) = explode(':', $line);
\r
2753 $Data[trim($Key)] = trim($Val);
\r
2759 * Get Passport ticket
\r
2761 * @param string $url URL string (Optional)
\r
2762 * @return mixed Array of tickets or false on failure
\r
2764 private function get_passport_ticket($url = '') {
\r
2765 $user = $this->user;
\r
2766 $password = htmlspecialchars($this->password);
\r
2769 $passport_url = self::PASSPORT_URL;
\r
2771 $passport_url = $url;
\r
2773 $XML = '<?xml version="1.0" encoding="UTF-8"?>
\r
2774 <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"
\r
2775 xmlns:wsse="http://schemas.xmlsoap.org/ws/2003/06/secext"
\r
2776 xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"
\r
2777 xmlns:wsp="http://schemas.xmlsoap.org/ws/2002/12/policy"
\r
2778 xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
\r
2779 xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/03/addressing"
\r
2780 xmlns:wssc="http://schemas.xmlsoap.org/ws/2004/04/sc"
\r
2781 xmlns:wst="http://schemas.xmlsoap.org/ws/2004/04/trust">
\r
2783 <ps:AuthInfo xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL" Id="PPAuthInfo">
\r
2784 <ps:HostingApp>{7108E71A-9926-4FCB-BCC9-9A9D3F32E423}</ps:HostingApp>
\r
2785 <ps:BinaryVersion>4</ps:BinaryVersion>
\r
2786 <ps:UIVersion>1</ps:UIVersion>
\r
2787 <ps:Cookies></ps:Cookies>
\r
2788 <ps:RequestParams>AQAAAAIAAABsYwQAAAAxMDMz</ps:RequestParams>
\r
2791 <wsse:UsernameToken Id="user">
\r
2792 <wsse:Username>'.$user.'</wsse:Username>
\r
2793 <wsse:Password>'.$password.'</wsse:Password>
\r
2794 </wsse:UsernameToken>
\r
2798 <ps:RequestMultipleSecurityTokens xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL" Id="RSTS">
\r
2799 <wst:RequestSecurityToken Id="RST0">
\r
2800 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2802 <wsa:EndpointReference>
\r
2803 <wsa:Address>http://Passport.NET/tb</wsa:Address>
\r
2804 </wsa:EndpointReference>
\r
2806 </wst:RequestSecurityToken>
\r
2807 <wst:RequestSecurityToken Id="RST1">
\r
2808 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2810 <wsa:EndpointReference>
\r
2811 <wsa:Address>messengerclear.live.com</wsa:Address>
\r
2812 </wsa:EndpointReference>
\r
2814 <wsse:PolicyReference URI="'.$this->passport_policy.'"></wsse:PolicyReference>
\r
2815 </wst:RequestSecurityToken>
\r
2816 <wst:RequestSecurityToken Id="RST2">
\r
2817 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2819 <wsa:EndpointReference>
\r
2820 <wsa:Address>messenger.msn.com</wsa:Address>
\r
2821 </wsa:EndpointReference>
\r
2823 <wsse:PolicyReference URI="?id=507"></wsse:PolicyReference>
\r
2824 </wst:RequestSecurityToken>
\r
2825 <wst:RequestSecurityToken Id="RST3">
\r
2826 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2828 <wsa:EndpointReference>
\r
2829 <wsa:Address>contacts.msn.com</wsa:Address>
\r
2830 </wsa:EndpointReference>
\r
2832 <wsse:PolicyReference URI="MBI"></wsse:PolicyReference>
\r
2833 </wst:RequestSecurityToken>
\r
2834 <wst:RequestSecurityToken Id="RST4">
\r
2835 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2837 <wsa:EndpointReference>
\r
2838 <wsa:Address>messengersecure.live.com</wsa:Address>
\r
2839 </wsa:EndpointReference>
\r
2841 <wsse:PolicyReference URI="MBI_SSL"></wsse:PolicyReference>
\r
2842 </wst:RequestSecurityToken>
\r
2843 <wst:RequestSecurityToken Id="RST5">
\r
2844 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2846 <wsa:EndpointReference>
\r
2847 <wsa:Address>spaces.live.com</wsa:Address>
\r
2848 </wsa:EndpointReference>
\r
2850 <wsse:PolicyReference URI="MBI"></wsse:PolicyReference>
\r
2851 </wst:RequestSecurityToken>
\r
2852 <wst:RequestSecurityToken Id="RST6">
\r
2853 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2855 <wsa:EndpointReference>
\r
2856 <wsa:Address>storage.msn.com</wsa:Address>
\r
2857 </wsa:EndpointReference>
\r
2859 <wsse:PolicyReference URI="MBI"></wsse:PolicyReference>
\r
2860 </wst:RequestSecurityToken>
\r
2861 </ps:RequestMultipleSecurityTokens>
\r
2865 $this->debug_message("*** URL: $passport_url");
\r
2866 $this->debug_message("*** Sending SOAP:\n$XML");
\r
2867 $curl = curl_init();
\r
2868 curl_setopt($curl, CURLOPT_URL, $passport_url);
\r
2869 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
2870 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
2871 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
2872 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
2873 curl_setopt($curl, CURLOPT_POST, 1);
\r
2874 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
2875 $data = curl_exec($curl);
\r
2876 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
2877 curl_close($curl);
\r
2878 $this->debug_message("*** Get Result:\n$data");
\r
2880 if ($http_code != 200) {
\r
2881 // sometimes, redirect to another URL
\r
2883 //<faultcode>psf:Redirect</faultcode>
\r
2884 //<psf:redirectUrl>https://msnia.login.live.com/pp450/RST.srf</psf:redirectUrl>
\r
2885 //<faultstring>Authentication Failure</faultstring>
\r
2886 if (strpos($data, '<faultcode>psf:Redirect</faultcode>') === false) {
\r
2887 $this->debug_message("*** Could not get passport ticket! http code = $http_code");
\r
2890 preg_match("#<psf\:redirectUrl>(.*)</psf\:redirectUrl>#", $data, $matches);
\r
2891 if (count($matches) == 0) {
\r
2892 $this->debug_message('*** Redirected, but could not get redirect URL!');
\r
2895 $redirect_url = $matches[1];
\r
2896 if ($redirect_url == $passport_url) {
\r
2897 $this->debug_message('*** Redirected, but to same URL!');
\r
2900 $this->debug_message("*** Redirected to $redirect_url");
\r
2901 return $this->get_passport_ticket($redirect_url);
\r
2904 // sometimes, redirect to another URL, also return 200
\r
2906 //<faultcode>psf:Redirect</faultcode>
\r
2907 //<psf:redirectUrl>https://msnia.login.live.com/pp450/RST.srf</psf:redirectUrl>
\r
2908 //<faultstring>Authentication Failure</faultstring>
\r
2909 if (strpos($data, '<faultcode>psf:Redirect</faultcode>') !== false) {
\r
2910 preg_match("#<psf\:redirectUrl>(.*)</psf\:redirectUrl>#", $data, $matches);
\r
2911 if (count($matches) != 0) {
\r
2912 $redirect_url = $matches[1];
\r
2913 if ($redirect_url == $passport_url) {
\r
2914 $this->debug_message('*** Redirected, but to same URL!');
\r
2917 $this->debug_message("*** Redirected to $redirect_url");
\r
2918 return $this->get_passport_ticket($redirect_url);
\r
2922 // no Redurect faultcode or URL
\r
2923 // we should get the ticket here
\r
2925 // we need ticket and secret code
\r
2926 // RST1: messengerclear.live.com
\r
2927 // <wsse:BinarySecurityToken Id="Compact1">t=tick&p=</wsse:BinarySecurityToken>
\r
2928 // <wst:BinarySecret>binary secret</wst:BinarySecret>
\r
2929 // RST2: messenger.msn.com
\r
2930 // <wsse:BinarySecurityToken Id="PPToken2">t=tick</wsse:BinarySecurityToken>
\r
2931 // RST3: contacts.msn.com
\r
2932 // <wsse:BinarySecurityToken Id="Compact3">t=tick&p=</wsse:BinarySecurityToken>
\r
2933 // RST4: messengersecure.live.com
\r
2934 // <wsse:BinarySecurityToken Id="Compact4">t=tick&p=</wsse:BinarySecurityToken>
\r
2935 // RST5: spaces.live.com
\r
2936 // <wsse:BinarySecurityToken Id="Compact5">t=tick&p=</wsse:BinarySecurityToken>
\r
2937 // RST6: storage.msn.com
\r
2938 // <wsse:BinarySecurityToken Id="Compact6">t=tick&p=</wsse:BinarySecurityToken>
\r
2940 "<wsse\:BinarySecurityToken Id=\"Compact1\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2941 "<wst\:BinarySecret>(.*)</wst\:BinarySecret>(.*)".
\r
2942 "<wsse\:BinarySecurityToken Id=\"PPToken2\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2943 "<wsse\:BinarySecurityToken Id=\"Compact3\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2944 "<wsse\:BinarySecurityToken Id=\"Compact4\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2945 "<wsse\:BinarySecurityToken Id=\"Compact5\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2946 "<wsse\:BinarySecurityToken Id=\"Compact6\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2950 // no ticket found!
\r
2951 if (count($matches) == 0) {
\r
2952 $this->debug_message('*** Could not get passport ticket!');
\r
2956 //$this->debug_message(var_export($matches, true));
\r
2957 // matches[0]: all data
\r
2958 // matches[1]: RST1 (messengerclear.live.com) ticket
\r
2959 // matches[2]: ...
\r
2960 // matches[3]: RST1 (messengerclear.live.com) binary secret
\r
2961 // matches[4]: ...
\r
2962 // matches[5]: RST2 (messenger.msn.com) ticket
\r
2963 // matches[6]: ...
\r
2964 // matches[7]: RST3 (contacts.msn.com) ticket
\r
2965 // matches[8]: ...
\r
2966 // matches[9]: RST4 (messengersecure.live.com) ticket
\r
2967 // matches[10]: ...
\r
2968 // matches[11]: RST5 (spaces.live.com) ticket
\r
2969 // matches[12]: ...
\r
2970 // matches[13]: RST6 (storage.live.com) ticket
\r
2971 // matches[14]: ...
\r
2974 // ticket => $matches[1]
\r
2975 // secret => $matches[3]
\r
2976 // web_ticket => $matches[5]
\r
2977 // contact_ticket => $matches[7]
\r
2978 // oim_ticket => $matches[9]
\r
2979 // space_ticket => $matches[11]
\r
2980 // storage_ticket => $matches[13]
\r
2982 // yes, we get ticket
\r
2983 $aTickets = array(
\r
2984 'ticket' => html_entity_decode($matches[1]),
\r
2985 'secret' => html_entity_decode($matches[3]),
\r
2986 'web_ticket' => html_entity_decode($matches[5]),
\r
2987 'contact_ticket' => html_entity_decode($matches[7]),
\r
2988 'oim_ticket' => html_entity_decode($matches[9]),
\r
2989 'space_ticket' => html_entity_decode($matches[11]),
\r
2990 'storage_ticket' => html_entity_decode($matches[13])
\r
2992 $this->ticket = $aTickets;
\r
2993 //$this->debug_message(var_export($aTickets, true));
\r
2994 $ABAuthHeaderArray = array(
\r
2995 'ABAuthHeader' => array(
\r
2996 ':' => array('xmlns' => 'http://www.msn.com/webservices/AddressBook'),
\r
2997 'ManagedGroupRequest' => false,
\r
2998 'TicketToken' => htmlspecialchars($this->ticket['contact_ticket']),
\r
3001 $this->ABAuthHeader = new SoapHeader('http://www.msn.com/webservices/AddressBook', 'ABAuthHeader', $this->Array2SoapVar($ABAuthHeaderArray));
\r
3006 * Generate the data to send a message
\r
3008 * @param string $sMessage Message
\r
3009 * @param integer $network Network
\r
3010 * @return string Message data
\r
3012 private function getMessage($sMessage, $network = 1) {
\r
3013 $msg_header = "MIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nX-MMS-IM-Format: FN=$this->font_fn; EF=$this->font_ef; CO=$this->font_co; CS=0; PF=22\r\n\r\n";
\r
3014 $msg_header_len = strlen($msg_header);
\r
3015 if ($network == 1)
\r
3016 $maxlen = self::MAX_MSN_MESSAGE_LEN - $msg_header_len;
\r
3018 $maxlen = self::MAX_YAHOO_MESSAGE_LEN - $msg_header_len;
\r
3019 $sMessage = str_replace("\r", '', $sMessage);
\r
3020 $msg = substr($sMessage, 0, $maxlen);
\r
3021 return $msg_header.$msg;
\r
3025 * Sleep for the given number of seconds
\r
3027 * @param integer $wait Number of seconds to sleep for
\r
3029 private function NSRetryWait($wait) {
\r
3030 $this->debug_message("*** Sleeping for $wait seconds before retrying");
\r
3035 * Sends a ping command
\r
3037 * Should be called about every 50 seconds
\r
3041 public function sendPing() {
\r
3043 $this->ns_writeln("PNG");
\r
3047 * Methods to add / call callbacks
\r
3051 * Calls User Handler
\r
3053 * Calls registered handler for a specific event.
\r
3055 * @param string $event Command (event) name (Rvous etc)
\r
3056 * @param array $data Data
\r
3057 * @see registerHandler
\r
3060 private function callHandler($event, $data = NULL) {
\r
3061 if (isset($this->myEventHandlers[$event])) {
\r
3062 if ($data !== NULL) {
\r
3063 call_user_func($this->myEventHandlers[$event], $data);
\r
3065 call_user_func($this->myEventHandlers[$event]);
\r
3071 * Registers a user handler
\r
3074 * IMIn, Pong, ConnectFailed, Reconnect,
\r
3075 * AddedToList, RemovedFromList
\r
3077 * @param string $event Event name
\r
3078 * @param string $handler User function to call
\r
3079 * @see callHandler
\r
3080 * @return boolean true if successful
\r
3082 public function registerHandler($event, $handler) {
\r
3083 if (is_callable($handler)) {
\r
3084 $this->myEventHandlers[$event] = $handler;
\r
3092 * Debugging methods
\r
3096 * Print message if debugging is enabled
\r
3098 * @param string $str Message to print
\r
3100 private function debug_message($str) {
\r
3101 if (!$this->debug) return;
\r
3106 * Dump binary data
\r
3108 * @param string $str Data string
\r
3109 * @return Binary data
\r
3111 private function dump_binary($str) {
\r
3115 $len = strlen($str);
\r
3116 for ($i = 0; $i < $len; $i++) {
\r
3117 if (($i % 16) == 0) {
\r
3118 if ($buf !== '') {
\r
3119 $buf .= "$h_str $a_str\n";
\r
3121 $buf .= sprintf("%04X:", $i);
\r
3125 $ch = ord($str[$i]);
\r
3129 $a_str .= chr($ch);
\r
3130 $h_str .= sprintf(" %02X", $ch);
\r
3132 if ($h_str !== '')
\r
3133 $buf .= "$h_str $a_str\n";
\r