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
51 private $password = '';
\r
52 private $NSfp = false;
\r
53 private $passport_policy = '';
\r
56 private $retry_wait;
\r
57 private $update_pending;
\r
58 private $PhotoStickerFile = false;
\r
59 private $Emotions = false;
\r
60 private $XFRReqTimeout = 60;
\r
61 private $SBStreamTimeout = 2;
\r
62 private $MsnObjArray = array();
\r
63 private $MsnObjMap = array();
\r
64 private $ABAuthHeader;
\r
68 private $server = 'messenger.hotmail.com';
\r
69 private $port = 1863;
\r
71 private $clientid = '';
\r
73 private $error = '';
\r
75 private $authed = false;
\r
77 private $oim_try = 3;
\r
79 private $font_fn = 'Arial';
\r
80 private $font_co = '333333';
\r
81 private $font_ef = '';
\r
84 // the message length (include header) is limited (maybe since WLM 8.5 released)
\r
85 // for WLM: 1664 bytes
\r
86 // for YIM: 518 bytes
\r
87 const max_msn_message_len = 1664;
\r
88 const max_yahoo_message_len = 518;
\r
90 // Begin added for StatusNet
\r
92 private $aContactList = array();
\r
93 private $aADL = array();
\r
96 * Holds session information indexed by screenname if
\r
97 * session has no socket or socket if socket present
\r
101 private $switchBoardSessions = array();
\r
104 * Holds sockets indexed by screenname
\r
108 private $switchBoardSessionLookup = array();
\r
111 * Holds references to sessions waiting for XFR
\r
115 private $waitingForXFR = array();
\r
118 * Event Handler Functions
\r
120 private $myEventHandlers = array();
\r
122 // End added for StatusNet
\r
125 * Constructor method
\r
127 * @param array $Configs Array of configuration options
\r
128 * 'user' - Username
\r
129 * 'password' - Password
\r
130 * 'alias' - Bot nickname
\r
131 * 'psm' - Bot personal status message
\r
132 * 'retry_wait' - Time to wait before trying to reconnect
\r
133 * 'update_pending' - Whether to update pending contacts
\r
134 * 'PhotoSticker' - Photo file to use (?)
\r
135 * 'debug' - Enable/Disable debugging mode
\r
136 * @param integer $timeout Connection timeout
\r
137 * @param integer $client_id Client id (hexadecimal)
\r
140 public function __construct ($Configs = array(), $timeout = 15, $client_id = 0x7000800C) {
\r
141 $this->user = $Configs['user'];
\r
142 $this->password = $Configs['password'];
\r
143 $this->alias = isset($Configs['alias']) ? $Configs['alias'] : '';
\r
144 $this->psm = isset($Configs['psm']) ? $Configs['psm'] : '';
\r
145 $this->retry_wait = isset($Configs['retry_wait']) ? $Configs['retry_wait'] : 30;
\r
146 $this->update_pending = isset($Configs['update_pending']) ? $Configs['update_pending'] : true;
\r
147 $this->PhotoStickerFile=isset($Configs['PhotoSticker']) ? $Configs['PhotoSticker'] : false;
\r
149 if ($this->Emotions = isset($Configs['Emotions']) ? $Configs['Emotions']:false) {
\r
150 foreach($this->Emotions as $EmotionFilePath)
\r
151 $this->MsnObj($EmotionFilePath,$Type=2);
\r
153 $this->debug = isset($Configs['debug']) ? $Configs['debug'] : false;
\r
154 $this->timeout = $timeout;
\r
157 if (!function_exists('curl_init')) throw new Exception("curl module not found!\n");
\r
158 if (!function_exists('preg_match')) throw new Exception("pcre module not found!\n");
\r
159 if (!function_exists('mhash')) throw new Exception("mhash module not found!\n");
\r
160 if (!function_exists('mcrypt_cbc')) throw new Exception("mcrypt module not found!\n");
\r
161 if (!function_exists('bcmod')) throw new Exception("bcmath module not found!\n");
\r
164 http://msnpiki.msnfanatic.com/index.php/Client_ID
\r
166 normal MSN 8.1 clientid is:
\r
167 01110110 01001100 11000000 00101100
\r
170 we just use following:
\r
171 * 0x04: Your client can send/receive Ink (GIF format)
\r
172 * 0x08: Your client can send/recieve Ink (ISF format)
\r
173 * 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
174 * 0x70000000: This is the value for MSNC7 (WL Msgr 8.1)
\r
177 $this->clientid = $client_id;
\r
178 $this->ABService = new SoapClient(realpath(dirname(__FILE__)).'/soap/msnab_sharingservice.wsdl', array('trace' => 1));
\r
186 * Connect to the NS server
\r
188 * @param String $user Username
\r
189 * @param String $password Password
\r
190 * @param String $redirect_server Redirect server
\r
191 * @param Integer $redirect_port Redirect port
\r
192 * @return Boolean Returns true if successful
\r
194 private function connect($user, $password, $redirect_server = '', $redirect_port = 1863) {
\r
196 if ($redirect_server === '') {
\r
197 $this->NSfp = @fsockopen($this->server, $this->port, $errno, $errstr, $this->timeout);
\r
198 if (!$this->NSfp) {
\r
199 $this->error = "!!! Could not connect to $this->server:$this->port, error => $errno, $errstr";
\r
204 $this->NSfp = @fsockopen($redirect_server, $redirect_port, $errno, $errstr, $this->timeout);
\r
205 if (!$this->NSfp) {
\r
206 $this->error = "!!! Could not connect to $redirect_server:$redirect_port, error => $errno, $errstr";
\r
210 $this->authed = false;
\r
212 // NS: >> VER {id} MSNP9 CVR0
\r
214 // NS: >>> VER {id} MSNP15 CVR0
\r
215 $this->ns_writeln("VER $this->id ".self::PROTOCOL.' CVR0');
\r
217 $start_tm = time();
\r
218 while (!self::socketcheck($this->NSfp)) {
\r
219 $data = $this->ns_readln();
\r
221 if ($data === false) {
\r
224 $this->ns_writeln("OUT");
\r
225 @fclose($this->NSfp);
\r
226 $this->error = 'Timeout, maybe protocol changed!';
\r
230 $code = substr($data, 0, 3);
\r
231 $start_tm = time();
\r
236 // NS: <<< VER {id} MSNP9 CVR0
\r
237 // NS: >>> CVR {id} 0x0409 winnt 5.1 i386 MSMSGS 6.0.0602 msmsgs {user}
\r
239 // NS: <<< VER {id} MSNP15 CVR0
\r
240 // NS: >>> CVR {id} 0x0409 winnt 5.1 i386 MSMSGS 8.1.0178 msmsgs {user}
\r
241 $this->ns_writeln("CVR $this->id 0x0409 winnt 5.1 i386 MSMSGS ".self::BUILDVER." msmsgs $user");
\r
246 // NS: <<< CVR {id} {ver_list} {download_serve} ....
\r
247 // NS: >>> USR {id} TWN I {user}
\r
249 // NS: <<< CVR {id} {ver_list} {download_serve} ....
\r
250 // NS: >>> USR {id} SSO I {user}
\r
251 $this->ns_writeln("USR $this->id ".self::LOGIN_METHOD." I $user");
\r
255 // already login for passport site, finish the login process now.
\r
256 // NS: <<< USR {id} OK {user} {verify} 0
\r
257 if ($this->authed) return true;
\r
258 // max. 16 digits for password
\r
259 if (strlen($password) > 16)
\r
260 $password = substr($password, 0, 16);
\r
262 $this->user = $user;
\r
263 $this->password = $password;
\r
264 // NS: <<< USR {id} SSO S {policy} {nonce}
\r
265 @list(/* USR */, /* id */, /* SSO */, /* S */, $policy, $nonce,) = @explode(' ', $data);
\r
267 $this->passport_policy = $policy;
\r
268 $aTickets = $this->get_passport_ticket();
\r
269 if (!$aTickets || !is_array($aTickets)) {
\r
272 $this->ns_writeln("OUT");
\r
273 @fclose($this->NSfp);
\r
274 $this->error = 'Passport authenticated fail!';
\r
278 $ticket = $aTickets['ticket'];
\r
279 $secret = $aTickets['secret'];
\r
280 $this->ticket = $aTickets;
\r
281 $login_code = $this->generateLoginBLOB($secret, $nonce);
\r
283 // NS: >>> USR {id} SSO S {ticket} {login_code}
\r
284 $this->ns_writeln("USR $this->id ".self::LOGIN_METHOD." S $ticket $login_code");
\r
285 $this->authed = true;
\r
289 // main login server will redirect to anther NS after USR command
\r
291 // NS: <<< XFR {id} NS {server} 0 {server}
\r
293 // NS: <<< XFR {id} NS {server} U D
\r
294 @list(/* XFR */, /* id */, $Type, $server, /* ... */) = @explode(' ', $data);
\r
295 if ($Type!='NS') break;
\r
296 @list($ip, $port) = @explode(':', $server);
\r
297 // this connection will close after XFR
\r
298 @fclose($this->NSfp);
\r
300 $this->NSfp = @fsockopen($ip, $port, $errno, $errstr, $this->timeout);
\r
301 if (!$this->NSfp) {
\r
302 $this->error = "Can't connect to $ip:$port, error => $errno, $errstr";
\r
307 // NS: >> VER {id} MSNP9 CVR0
\r
309 // NS: >>> VER {id} MSNP15 CVR0
\r
310 $this->ns_writeln("VER $this->id ".self::PROTOCOL.' CVR0');
\r
314 // return some policy data after 'USR {id} SSO I {user}' command
\r
315 // NS: <<< GCF 0 {size}
\r
316 @list(/* GCF */, /* 0 */, $size,) = @explode(' ', $data);
\r
317 // we don't need the data, just read it and drop
\r
318 if (is_numeric($size) && $size > 0)
\r
319 $this->ns_readdata($size);
\r
323 // we'll quit if got any error
\r
324 if (is_numeric($code)) {
\r
327 $this->ns_writeln("OUT");
\r
328 @fclose($this->NSfp);
\r
329 $this->error = "Error code: $code, please check the detail information from: http://msnpiki.msnfanatic.com/index.php/Reference:Error_List";
\r
332 // unknown response from server, just ignore it
\r
340 * Sign onto the NS server and retrieve the address book
\r
344 public function signon() {
\r
345 /* FIXME Don't implement the signon as a loop or we could hang
\r
346 * the queue handler! */
\r
347 $this->debug_message('*** Trying to connect to MSN network');
\r
351 if (!$this->connect($this->user, $this->password)) {
\r
352 $this->signonFailure("!!! Could not connect to server: $this->error");
\r
357 if ($this->UpdateContacts() === false) continue;
\r
359 // Get membership lists
\r
360 if (($this->aContactList = $this->getMembershipList()) === false) {
\r
361 $this->signonFailure('!!! Get membership list failed');
\r
365 if ($this->update_pending) {
\r
366 if (is_array($this->aContactList)) {
\r
367 $pending = 'Pending';
\r
368 foreach ($this->aContactList as $u_domain => $aUserList) {
\r
369 foreach ($aUserList as $u_name => $aNetworks) {
\r
370 foreach ($aNetworks as $network => $aData) {
\r
371 if (isset($aData[$pending])) {
\r
374 foreach (array('Allow', 'Reverse') as $list) {
\r
375 if (isset($aData[$list]))
\r
378 if ($this->addMemberToList($u_name.'@'.$u_domain, $network, $list)) {
\r
379 $this->aContactList[$u_domain][$u_name][$network][$list] = false;
\r
385 $id = $aData[$pending];
\r
386 // we can delete it from pending now
\r
387 if ($this->delMemberFromList($id, $u_name.'@'.$u_domain, $network, $pending))
\r
388 unset($this->aContactList[$u_domain][$u_name][$network][$pending]);
\r
393 foreach (array('Allow', 'Reverse') as $list) {
\r
394 if (!isset($aData[$list])) {
\r
395 if ($this->addMemberToList($u_name.'@'.$u_domain, $network, $list))
\r
396 $this->aContactList[$u_domain][$u_name][$network][$list] = false;
\r
408 if (is_array($this->aContactList)) {
\r
409 foreach ($this->aContactList as $u_domain => $aUserList) {
\r
410 $str = '<d n="'.$u_domain.'">';
\r
411 $len += strlen($str);
\r
413 $this->aADL[$n] = '<ml l="1">'.$sList.'</ml>';
\r
416 $len = strlen($str);
\r
419 foreach ($aUserList as $u_name => $aNetworks) {
\r
420 foreach ($aNetworks as $network => $status) {
\r
421 $str = '<c n="'.$u_name.'" l="3" t="'.$network.'" />';
\r
422 $len += strlen($str);
\r
423 // max: 7500, but <ml l="1"></d></ml> is 19,
\r
427 $this->aADL[$n] = '<ml l="1">'.$sList.'</ml>';
\r
429 $sList = '<d n="'.$u_domain.'">'.$str;
\r
430 $len = strlen($sList);
\r
439 $this->aADL[$n] = '<ml l="1">'.$sList.'</ml>';
\r
440 // NS: >>> BLP {id} BL
\r
441 $this->ns_writeln("BLP $this->id BL");
\r
442 foreach ($this->aADL as $str) {
\r
443 $len = strlen($str);
\r
444 // NS: >>> ADL {id} {size}
\r
445 $this->ns_writeln("ADL $this->id $len");
\r
446 $this->ns_writedata($str);
\r
448 // NS: >>> PRP {id} MFN name
\r
449 if ($this->alias == '') $this->alias = $user;
\r
450 $aliasname = rawurlencode($this->alias);
\r
451 $this->ns_writeln("PRP $this->id MFN $aliasname");
\r
452 //è¨å®šå€‹äººå¤§é è²¼
\r
453 //$MsnObj=$this->PhotoStckObj();
\r
454 // NS: >>> CHG {id} {status} {clientid} {msnobj}
\r
455 $this->ns_writeln("CHG $this->id NLN $this->clientid");
\r
456 if ($this->PhotoStickerFile !== false)
\r
457 $this->ns_writeln("CHG $this->id NLN $this->clientid ".rawurlencode($this->MsnObj($this->PhotoStickerFile)));
\r
458 // NS: >>> UUX {id} length
\r
459 $str = '<Data><PSM>'.htmlspecialchars($this->psm).'</PSM><CurrentMedia></CurrentMedia><MachineGuid></MachineGuid></Data>';
\r
460 $len = strlen($str);
\r
461 $this->ns_writeln("UUX $this->id $len");
\r
462 $this->ns_writedata($str);
\r
463 if (!self::socketcheck($this->NSfp)) {
\r
464 $this->debug_message('*** Connected, waiting for commands');
\r
467 $this->NSRetryWait($this->retry_wait);
\r
473 * Called if there is an error during signon
\r
475 * @param string $message Error message to log
\r
478 private function signonFailure($message) {
\r
479 $this->debug_message($message);
\r
480 $this->callHandler('ConnectFailed');
\r
481 $this->NSRetryWait($this->retry_wait);
\r
485 * Log out and close the NS connection
\r
489 private function nsLogout() {
\r
490 if (is_resource($this->NSfp) && !feof($this->NSfp)) {
\r
493 $this->ns_writeln("OUT");
\r
494 fclose($this->NSfp);
\r
495 $this->NSfp = false;
\r
496 $this->debug_message("*** Logged out");
\r
501 * NS and SB command handling methods
\r
505 * Read and handle incoming command from NS
\r
509 private function nsReceive() {
\r
510 // Sign in again if not signed in or socket failed
\r
511 if (!is_resource($this->NSfp) || self::socketcheck($this->NSfp)) {
\r
512 $this->callHandler('Reconnect');
\r
513 $this->NSRetryWait($this->retry_wait);
\r
518 $data = $this->ns_readln();
\r
519 if ($data === false) {
\r
520 // There was no data / an error when reading from the socket so reconnect
\r
521 $this->callHandler('Reconnect');
\r
522 $this->NSRetryWait($this->retry_wait);
\r
527 switch (substr($data, 0, 3)) {
\r
529 // after 'USR {id} OK {user} {verify} 0' response, the server will send SBS and profile to us
\r
530 // NS: <<< SBS 0 null
\r
536 // refresh ADL, so we re-send it again
\r
537 if (is_array($this->aADL)) {
\r
538 foreach ($this->aADL as $str) {
\r
539 $len = strlen($str);
\r
540 // NS: >>> ADL {id} {size}
\r
541 $this->ns_writeln("ADL $this->id $len");
\r
542 $this->ns_writedata($str);
\r
548 // NS: <<< LST {email} {alias} 11 0
\r
549 @list(/* LST */, $email, /* alias */,) = @explode(' ', $data);
\r
550 @list($u_name, $u_domain) = @explode('@', $email);
\r
551 if (!isset($this->aContactList[$u_domain][$u_name][1])) {
\r
552 $this->aContactList[$u_domain][$u_name][1]['Allow'] = 'Allow';
\r
553 $this->debug_message("*** Added to contact list: $u_name@$u_domain");
\r
558 // randomly, we get ADL command, someone add us to their contact list for MSNP15
\r
559 // NS: <<< ADL 0 {size}
\r
560 @list(/* ADL */, /* 0 */, $size,) = @explode(' ', $data);
\r
561 if (is_numeric($size) && $size > 0) {
\r
562 $data = $this->ns_readdata($size);
\r
563 preg_match('#<ml><d n="([^"]+)"><c n="([^"]+)"(.*) t="(\d*)"(.*) /></d></ml>#', $data, $matches);
\r
564 if (is_array($matches) && count($matches) > 0) {
\r
565 $u_domain = $matches[1];
\r
566 $u_name = $matches[2];
\r
567 $network = $matches[4];
\r
568 if (isset($this->aContactList[$u_domain][$u_name][$network]))
\r
569 $this->debug_message("*** Someone (network: $network) added us to their list (but already in our list): $u_name@$u_domain");
\r
573 foreach (array('Allow', 'Reverse') as $list) {
\r
574 if (!$this->addMemberToList($u_name.'@'.$u_domain, $network, $list)) {
\r
576 $this->debug_message("*** Could not add $u_name@$u_domain (network: $network) to $list list");
\r
579 $aTickets = $this->get_passport_ticket();
\r
580 if (!$aTickets || !is_array($aTickets)) {
\r
581 // failed to login? ignore it
\r
582 $this->debug_message("*** Could not re-login, something wrong here");
\r
583 $this->debug_message("*** Could not add $u_name@$u_domain (network: $network) to $list list");
\r
587 $this->ticket = $aTickets;
\r
588 $this->debug_message("**** Got new ticket, trying again");
\r
589 if (!$this->addMemberToList($u_name.'@'.$u_domain, $network, $list)) {
\r
590 $this->debug_message("*** Could not add $u_name@$u_domain (network: $network) to $list list");
\r
594 $this->aContactList[$u_domain][$u_name][$network][$list] = false;
\r
597 $this->debug_message("*** Someone (network: $network) added us to their list: $u_name@$u_domain");
\r
599 $str = '<ml l="1"><d n="'.$u_domain.'"><c n="'.$u_name.'" l="3" t="'.$network.'" /></d></ml>';
\r
600 $len = strlen($str);
\r
602 $this->callHandler('AddedToList', array('screenname' => $u_name.'@'.$u_domain, 'network' => $network));
\r
605 $this->debug_message("*** Someone added us to their list: $data");
\r
610 // randomly, we get RML command, someome remove us to their contact list for MSNP15
\r
611 // NS: <<< RML 0 {size}
\r
612 @list(/* RML */, /* 0 */, $size,) = @explode(' ', $data);
\r
613 if (is_numeric($size) && $size > 0) {
\r
614 $data = $this->ns_readdata($size);
\r
615 preg_match('#<ml><d n="([^"]+)"><c n="([^"]+)"(.*) t="(\d*)"(.*) /></d></ml>#', $data, $matches);
\r
616 if (is_array($matches) && count($matches) > 0) {
\r
617 $u_domain = $matches[1];
\r
618 $u_name = $matches[2];
\r
619 $network = $matches[4];
\r
620 if (isset($this->aContactList[$u_domain][$u_name][$network])) {
\r
621 $aData = $this->aContactList[$u_domain][$u_name][$network];
\r
623 foreach ($aData as $list => $id)
\r
624 $this->delMemberFromList($id, $u_name.'@'.$u_domain, $network, $list);
\r
626 unset($this->aContactList[$u_domain][$u_name][$network]);
\r
627 $this->debug_message("*** Someone (network: $network) removed us from their list: $u_name@$u_domain");
\r
630 $this->debug_message("*** Someone (network: $network) removed us from their list (but not in our list): $u_name@$u_domain");
\r
632 $this->callHandler('RemovedFromList', array('screenname' => $u_name.'@'.$u_domain, 'network' => $network));
\r
635 $this->debug_message("*** Someone removed us from their list: $data");
\r
640 // randomly, we get MSG notification from server
\r
641 // NS: <<< MSG Hotmail Hotmail {size}
\r
642 @list(/* MSG */, /* Hotmail */, /* Hotmail */, $size,) = @explode(' ', $data);
\r
643 if (is_numeric($size) && $size > 0) {
\r
644 $data = $this->ns_readdata($size);
\r
645 $aLines = @explode("\n", $data);
\r
649 foreach ($aLines as $line) {
\r
650 $line = rtrim($line);
\r
652 if ($line === '') {
\r
656 if (strncasecmp($line, 'Content-Type:', 13) == 0) {
\r
657 if (strpos($line, 'text/x-msmsgsinitialmdatanotification') === false && strpos($line, 'text/x-msmsgsoimnotification') === false) {
\r
658 // we just need text/x-msmsgsinitialmdatanotification
\r
659 // or text/x-msmsgsoimnotification
\r
666 if (strncasecmp($line, 'Mail-Data:', 10) == 0) {
\r
667 $maildata = trim(substr($line, 10));
\r
672 $this->debug_message("*** Ignoring MSG for: $line");
\r
675 if ($maildata == '') {
\r
676 $this->debug_message("*** Ignoring MSG not for OIM");
\r
680 if (strcasecmp($maildata, 'too-large') == 0) {
\r
681 $this->debug_message("*** Large mail-data, need to get the data via SOAP");
\r
682 $maildata = $this->getOIM_maildata();
\r
683 if ($maildata === false) {
\r
684 $this->debug_message("*** Could not get mail-data via SOAP");
\r
686 // maybe we need to re-login again
\r
687 $aTickets = $this->get_passport_ticket();
\r
688 if (!$aTickets || !is_array($aTickets)) {
\r
689 // failed to login? ignore it
\r
690 $this->debug_message("*** Could not re-login, something wrong here, ignoring this OIM");
\r
694 $this->ticket = $aTickets;
\r
695 $this->debug_message("*** Got new ticket, trying again");
\r
696 $maildata = $this->getOIM_maildata();
\r
697 if ($maildata === false) {
\r
698 $this->debug_message("*** Could not get mail-data via SOAP, and re-login already attempted, ignoring this OIM");
\r
703 // could be a lots of <M>...</M>, so we can't use preg_match here
\r
707 $start = strpos($p, '<M>');
\r
708 $end = strpos($p, '</M>');
\r
709 if ($start === false || $end === false || $start > $end) break;
\r
711 $sOIM = substr($p, $start, $end - $start);
\r
713 $p = substr($p, $end);
\r
715 if (count($aOIMs) == 0) {
\r
716 $this->debug_message("*** Ignoring empty OIM");
\r
719 foreach ($aOIMs as $maildata) {
\r
720 // T: 11 for MSN, 13 for Yahoo
\r
721 // S: 6 for MSN, 7 for Yahoo
\r
722 // RT: the datetime received by server
\r
723 // RS: already read or not
\r
724 // SZ: size of message
\r
727 // F: always 00000000-0000-0000-0000-000000000009
\r
729 preg_match('#<T>(.*)</T>#', $maildata, $matches);
\r
730 if (count($matches) == 0) {
\r
731 $this->debug_message("*** Ignoring OIM maildata without <T>type</T>");
\r
734 $oim_type = $matches[1];
\r
735 if ($oim_type = 13)
\r
739 preg_match('#<E>(.*)</E>#', $maildata, $matches);
\r
740 if (count($matches) == 0) {
\r
741 $this->debug_message("*** Ignoring OIM maildata without <E>sender</E>");
\r
744 $oim_sender = $matches[1];
\r
745 preg_match('#<I>(.*)</I>#', $maildata, $matches);
\r
746 if (count($matches) == 0) {
\r
747 $this->debug_message("*** Ignoring OIM maildata without <I>msgid</I>");
\r
750 $oim_msgid = $matches[1];
\r
751 preg_match('#<SZ>(.*)</SZ>#', $maildata, $matches);
\r
752 $oim_size = (count($matches) == 0) ? 0 : $matches[1];
\r
753 preg_match('#<RT>(.*)</RT>#', $maildata, $matches);
\r
754 $oim_time = (count($matches) == 0) ? 0 : $matches[1];
\r
755 $this->debug_message("*** OIM received from $oim_sender, Time: $oim_time, MSGID: $oim_msgid, size: $oim_size");
\r
756 $sMsg = $this->getOIM_message($oim_msgid);
\r
757 if ($sMsg === false) {
\r
758 $this->debug_message("*** Could not get OIM, msgid = $oim_msgid");
\r
760 $this->debug_message("*** Could not get OIM via SOAP, and re-login already attempted, ignoring this OIM");
\r
763 $aTickets = $this->get_passport_ticket();
\r
764 if (!$aTickets || !is_array($aTickets)) {
\r
765 // failed to login? ignore it
\r
766 $this->debug_message("*** Could not re-login, something wrong here, ignoring this OIM");
\r
770 $this->ticket = $aTickets;
\r
771 $this->debug_message("*** get new ticket, try it again");
\r
772 $sMsg = $this->getOIM_message($oim_msgid);
\r
773 if ($sMsg === false) {
\r
774 $this->debug_message("*** Could not get OIM via SOAP, and re-login already attempted, ignoring this OIM");
\r
778 $this->debug_message("*** MSG (Offline) from $oim_sender (network: $network): $sMsg");
\r
779 $this->callHandler('IMin', array('sender' => $oim_sender, 'message' => $sMsg, 'network' => $network, 'offline' => true));
\r
785 // randomly, we get UBM, this is the message from other network, like Yahoo!
\r
786 // NS: <<< UBM {email} $network $type {size}
\r
787 @list(/* UBM */, $from_email, $network, $type, $size,) = @explode(' ', $data);
\r
788 if (is_numeric($size) && $size > 0) {
\r
789 $data = $this->ns_readdata($size);
\r
790 $aLines = @explode("\n", $data);
\r
794 foreach ($aLines as $line) {
\r
795 $line = rtrim($line);
\r
797 if ($line === '') {
\r
801 if (strncasecmp($line, 'TypingUser:', 11) == 0) {
\r
807 $aSubLines = @explode("\r", $line);
\r
808 foreach ($aSubLines as $str) {
\r
815 $this->debug_message("*** Ignoring message from $from_email: $line");
\r
818 $this->debug_message("*** MSG from $from_email (network: $network): $sMsg");
\r
819 $this->callHandler('IMin', array('sender' => $from_email, 'message' => $sMsg, 'network' => $network, 'offline' => false));
\r
824 // randomly, we get UBX notification from server
\r
825 // NS: <<< UBX email {network} {size}
\r
826 @list(/* UBX */, /* email */, /* network */, $size,) = @explode(' ', $data);
\r
827 // we don't need the notification data, so just ignore it
\r
828 if (is_numeric($size) && $size > 0)
\r
829 $this->ns_readdata($size);
\r
833 // randomly, we'll get challenge from server
\r
834 // NS: <<< CHL 0 {code}
\r
835 @list(/* CHL */, /* 0 */, $chl_code,) = @explode(' ', $data);
\r
836 $fingerprint = $this->getChallenge($chl_code);
\r
837 // NS: >>> QRY {id} {product_id} 32
\r
838 // NS: >>> fingerprint
\r
839 $this->ns_writeln("QRY $this->id ".self::PROD_ID.' 32');
\r
840 $this->ns_writedata($fingerprint);
\r
841 $this->ns_writeln("CHG $this->id NLN $this->clientid");
\r
842 if ($this->PhotoStickerFile !== false)
\r
843 $this->ns_writeln("CHG $this->id NLN $this->clientid ".rawurlencode($this->MsnObj($this->PhotoStickerFile)));
\r
846 // NS: <<< CHG {id} {status} {code}
\r
848 // change our status to online first
\r
852 // sometimes, NS will redirect to another NS
\r
854 // NS: <<< XFR {id} NS {server} 0 {server}
\r
856 // NS: <<< XFR {id} NS {server} U D
\r
857 // for normal switchboard XFR
\r
858 // NS: <<< XFR {id} SB {server} CKI {cki} U messenger.msn.com 0
\r
859 @list(/* XFR */, /* {id} */, $server_type, $server, /* CKI */, $cki_code, /* ... */) = @explode(' ', $data);
\r
860 @list($ip, $port) = @explode(':', $server);
\r
861 if ($server_type != 'SB') {
\r
863 // this connection will close after XFR
\r
868 $this->debug_message("NS: <<< XFR SB");
\r
869 $user = array_shift($this->waitingForXFR);
\r
870 $bSBresult = $this->switchboard_control($ip, $port, $cki_code, $User, $Message);
\r
872 $bSBresult = $this->switchboard_control($ip, $port, $cki_code, $aMSNUsers[$nCurrentUser], $sMessage);
\r
873 if ($bSBresult === false) {
\r
874 // error for switchboard
\r
875 $this->debug_message("!!! error for sending message to ".$aMSNUsers[$nCurrentUser]);
\r
876 $aOfflineUsers[] = $aMSNUsers[$nCurrentUser];
\r
880 // NS: <<< QNG {time}
\r
881 @list(/* QNG */, $ping_wait) = @explode(' ', $data);
\r
882 $this->callHandler('Pong', $ping_wait);
\r
886 if ($this->PhotoStickerFile !== false)
\r
887 $this->ns_writeln("CHG $this->id NLN $this->clientid ".rawurlencode($this->MsnObj($this->PhotoStickerFile)));
\r
889 $this->ns_writeln("CHG $this->id NLN $this->clientid");
\r
890 // someone is trying to talk to us
\r
891 // NS: <<< RNG {session_id} {server} {auth_type} {ticket} {email} {alias} U {client} 0
\r
892 $this->debug_message("NS: <<< RNG $data");
\r
893 @list(/* RNG */, $sid, $server, /* auth_type */, $ticket, $email, $name, ) = @explode(' ', $data);
\r
894 @list($sb_ip, $sb_port) = @explode(':', $server);
\r
895 $this->debug_message("*** RING from $email, $sb_ip:$sb_port");
\r
896 $this->addContact($email, 1, $email, true);
\r
897 $this->connectToSBSession('Passive', $sb_ip, $sb_port, $email, array('sid' => $sid, 'ticket' => $ticket));
\r
900 // force logout from NS
\r
902 $this->debug_message("*** LOGOUT from NS");
\r
903 return $this->nsLogout();
\r
906 $code = substr($data,0,3);
\r
907 if (is_numeric($code)) {
\r
908 $this->error = "Error code: $code, please check the detail information from: http://msnpiki.msnfanatic.com/index.php/Reference:Error_List";
\r
909 $this->debug_message("*** NS: $this->error");
\r
911 return $this->nsLogout();
\r
918 * Read and handle incoming command/message from
\r
919 * a switchboard session socket
\r
921 private function sbReceive($socket) {
\r
922 $intsocket = (int) $socket;
\r
923 $session = &$this->switchBoardSessions[$intsocket];
\r
925 if (feof($socket)) {
\r
926 // Unset session lookup value
\r
927 unset($this->switchBoardSessionLookup[$session['to']]);
\r
929 // Unset session itself
\r
930 unset($this->switchBoardSessions[$intsocket]);
\r
934 $id = &$session['id'];
\r
936 $data = $this->sb_readln($socket);
\r
937 $code = substr($data, 0, 3);
\r
940 // SB: <<< IRO {id} {rooster} {roostercount} {email} {alias} {clientid}
\r
941 @list(/* IRO */, /* id */, $cur_num, $total, $email, $alias, $clientid) = @explode(' ', $data);
\r
942 $this->debug_message("*** $email joined session");
\r
943 $session['joined'] = true;
\r
946 $this->debug_message("*** Quit for BYE");
\r
947 $this->endSBSession();
\r
950 // SB: <<< USR {id} OK {user} {alias}
\r
951 // we don't need the data, just ignore it
\r
952 // request user to join this switchboard
\r
953 // SB: >>> CAL {id} {user}
\r
954 $this->sb_writeln($socket, $id, "CAL $this->id $user");
\r
957 // SB: <<< CAL {id} RINGING {?}
\r
958 // we don't need this, just ignore, and wait for other response
\r
962 // SB: <<< JOI {user} {alias} {clientid?}
\r
964 // we don't need the data, just ignore it
\r
965 // no more user here
\r
966 $session['joined'] = true;
\r
969 // SB: <<< MSG {email} {alias} {len}
\r
970 @list(/* MSG */, $from_email, /* alias */, $len, ) = @explode(' ', $data);
\r
972 $data = $this->sb_readdata($socket, $len);
\r
973 $aLines = @explode("\n", $data);
\r
978 foreach ($aLines as $line) {
\r
979 $line = rtrim($line);
\r
981 if ($line === '') {
\r
985 if (strncasecmp($line, 'TypingUser:', 11) == 0) {
\r
986 // typing notification, just ignore
\r
990 if (strncasecmp($line, 'Chunk:', 6) == 0) {
\r
991 // we don't handle any split message, just ignore
\r
995 if (strncasecmp($line, 'Content-Type: application/x-msnmsgrp2p', 38) == 0) {
\r
996 // p2p message, ignore it, but we need to send acknowledgement for it...
\r
998 $p = strstr($data, "\n\n");
\r
1000 if ($p === false) {
\r
1001 $p = strstr($data, "\r\n\r\n");
\r
1003 $sMsg = substr($p, 4);
\r
1006 $sMsg = substr($p, 2);
\r
1009 if (strncasecmp($line, 'Content-Type: application/x-', 28) == 0) {
\r
1010 // ignore all application/x-... message
\r
1012 // application/x-ms-ink => ink message
\r
1016 if (strncasecmp($line, 'Content-Type: text/x-', 21) == 0) {
\r
1017 // ignore all text/x-... message
\r
1019 // text/x-msnmsgr-datacast => nudge, voice clip....
\r
1020 // text/x-mms-animemoticon => customized animemotion word
\r
1031 $this->debug_message("*** Ignoring SB data from $from_email: $line");
\r
1035 // we will ignore any p2p message after sending acknowledgement
\r
1037 $len = strlen($sMsg);
\r
1038 $this->debug_message("*** p2p message from $from_email, size $len");
\r
1039 // header = 48 bytes
\r
1040 // content >= 0 bytes
\r
1041 // footer = 4 bytes
\r
1042 // so it need to >= 52 bytes
\r
1043 /*if ($len < 52) {
\r
1044 $this->debug_message("*** p2p: size error, less than 52!");
\r
1047 $aDwords = @unpack("V12dword", $sMsg);
\r
1048 if (!is_array($aDwords)) {
\r
1049 $this->debug_message("*** p2p: header unpack error!");
\r
1052 $this->debug_message("*** p2p: dump received message:\n".$this->dump_binary($sMsg));
\r
1053 $hdr_SessionID = $aDwords['dword1'];
\r
1054 $hdr_Identifier = $aDwords['dword2'];
\r
1055 $hdr_DataOffsetLow = $aDwords['dword3'];
\r
1056 $hdr_DataOffsetHigh = $aDwords['dword4'];
\r
1057 $hdr_TotalDataSizeLow = $aDwords['dword5'];
\r
1058 $hdr_TotalDataSizeHigh = $aDwords['dword6'];
\r
1059 $hdr_MessageLength = $aDwords['dword7'];
\r
1060 $hdr_Flag = $aDwords['dword8'];
\r
1061 $hdr_AckID = $aDwords['dword9'];
\r
1062 $hdr_AckUID = $aDwords['dword10'];
\r
1063 $hdr_AckSizeLow = $aDwords['dword11'];
\r
1064 $hdr_AckSizeHigh = $aDwords['dword12'];
\r
1065 $this->debug_message("*** p2p: header SessionID = $hdr_SessionID");
\r
1066 $this->debug_message("*** p2p: header Inentifier = $hdr_Identifier");
\r
1067 $this->debug_message("*** p2p: header Data Offset Low = $hdr_DataOffsetLow");
\r
1068 $this->debug_message("*** p2p: header Data Offset High = $hdr_DataOffsetHigh");
\r
1069 $this->debug_message("*** p2p: header Total Data Size Low = $hdr_TotalDataSizeLow");
\r
1070 $this->debug_message("*** p2p: header Total Data Size High = $hdr_TotalDataSizeHigh");
\r
1071 $this->debug_message("*** p2p: header MessageLength = $hdr_MessageLength");
\r
1072 $this->debug_message("*** p2p: header Flag = $hdr_Flag");
\r
1073 $this->debug_message("*** p2p: header AckID = $hdr_AckID");
\r
1074 $this->debug_message("*** p2p: header AckUID = $hdr_AckUID");
\r
1075 $this->debug_message("*** p2p: header AckSize Low = $hdr_AckSizeLow");
\r
1076 $this->debug_message("*** p2p: header AckSize High = $hdr_AckSizeHigh");
\r
1077 if ($hdr_Flag == 2) {
\r
1078 //This is an ACK from SB ignore....
\r
1079 $this->debug_message("*** p2p: //This is an ACK from SB ignore....:\n");
\r
1082 $MsgBody = $this->linetoArray(substr($sMsg, 48, -4));
\r
1083 $this->debug_message("*** p2p: body".print_r($MsgBody, true));
\r
1084 if (($MsgBody['EUF-GUID']=='{A4268EEC-FEC5-49E5-95C3-F126696BDBF6}')&&($PictureFilePath=$this->GetPictureFilePath($MsgBody['Context']))) {
\r
1086 if ($this->sb_readln($socket) === false) break;
\r
1088 $this->debug_message("*** p2p: Inv hdr:\n".$this->dump_binary(substr($sMsg, 0, 48)));
\r
1089 preg_match('/{([0-9A-F\-]*)}/i', $MsgBody['Via'], $Matches);
\r
1090 $BranchGUID = $Matches[1];
\r
1091 //it's an invite to send a display picture.
\r
1092 $new_id = ~$hdr_Identifier;
\r
1094 "LLLLLLLLLLLL", $hdr_SessionID,
\r
1097 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1102 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh
\r
1104 $footer = pack("L", 0);
\r
1105 $message = "MIME-Version: 1.0\r\nContent-Type: application/x-msnmsgrp2p\r\nP2P-Dest: $from_email\r\n\r\n$hdr$footer";
\r
1106 $len = strlen($message);
\r
1107 $this->sb_writeln($socket, $id, "MSG $this->id D $len");
\r
1108 $this->sb_writedata($socket, $message);
\r
1109 $this->debug_message("*** p2p: send display picture acknowledgement for $hdr_SessionID");
\r
1110 $this->debug_message("*** p2p: Invite ACK message:\n".$this->dump_binary($message));
\r
1111 $this->sb_readln($socket); // Read ACK;
\r
1112 $this->debug_message("*** p2p: Invite ACK Hdr:\n".$this->dump_binary($hdr));
\r
1114 //Send 200 OK message
\r
1115 $MessageContent="SessionID: ".$MsgBody['SessionID']."\r\n\r\n".pack("C", 0);
\r
1117 "MSNSLP/1.0 200 OK\r\n".
\r
1118 "To: <msnmsgr:".$from_email.">\r\n".
\r
1119 "From: <msnmsgr:".$this->user.">\r\n".
\r
1120 "Via: ".$MsgBody['Via']."\r\n".
\r
1121 "CSeq: ".($MsgBody['CSeq']+1)."\r\n".
\r
1122 "Call-ID: ".$MsgBody['Call-ID']."\r\n".
\r
1123 "Max-Forwards: 0\r\n".
\r
1124 "Content-Type: application/x-msnmsgr-sessionreqbody\r\n".
\r
1125 "Content-Length: ".strlen($MessageContent)."\r\n\r\n".
\r
1127 $hdr_TotalDataSizeLow=strlen($MessagePayload);
\r
1128 $hdr_TotalDataSizeHigh=0;
\r
1130 "LLLLLLLLLLLL", $hdr_SessionID,
\r
1133 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1134 strlen($MessagePayload),
\r
1142 "MIME-Version: 1.0\r\n".
\r
1143 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1144 "P2P-Dest: $from_email\r\n\r\n$hdr$MessagePayload$footer";
\r
1145 $this->sb_writeln($socket, $id, "MSG $this->id D ".strlen($message));
\r
1146 $this->sb_writedata($socket, $message);
\r
1147 $this->debug_message("*** p2p: dump 200 ok message:\n".$this->dump_binary($message));
\r
1148 $this->sb_readln($socket); // Read ACK;
\r
1150 $this->debug_message("*** p2p: 200 ok:\n".$this->dump_binary($hdr));
\r
1151 // send data preparation message
\r
1152 // send 4 null bytes as data
\r
1153 $hdr_TotalDataSizeLow = 4;
\r
1154 $hdr_TotalDataSizeHigh = 0 ;
\r
1158 $MsgBody['SessionID'],
\r
1161 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1162 $hdr_TotalDataSizeLow,
\r
1169 "MIME-Version: 1.0\r\n".
\r
1170 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1171 "P2P-Dest: $from_email\r\n\r\n$hdr".pack('L', 0)."$footer";
\r
1172 $this->sb_writeln($socket, $id, "MSG $this->id D ".strlen($message));
\r
1173 $this->sb_writedata($socket, $message);
\r
1174 $this->debug_message("*** p2p: dump send Data preparation message:\n".$this->dump_binary($message));
\r
1175 $this->debug_message("*** p2p: Data Prepare Hdr:\n".$this->dump_binary($hdr));
\r
1176 $this->sb_readln($socket); // Read ACK;
\r
1178 // send Data Content..
\r
1179 $footer=pack('N',1);
\r
1181 $FileSize=filesize($PictureFilePath);
\r
1182 if ($hTitle=fopen($PictureFilePath,'rb')) {
\r
1185 while (!feof($hTitle)) {
\r
1186 $FileContent = fread($hTitle, 1024);
\r
1187 $FileContentSize = strlen($FileContent);
\r
1190 $MsgBody['SessionID'],
\r
1201 "MIME-Version: 1.0\r\n".
\r
1202 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1203 "P2P-Dest: $from_email\r\n\r\n$hdr$FileContent$footer";
\r
1204 $this->sb_writeln($socket, $id, "MSG $this->id D ".strlen($message));
\r
1205 $this->sb_writedata($socket, $message);
\r
1206 $this->debug_message("*** p2p: dump send Data Content message $Offset / $FileSize :\n".$this->dump_binary($message));
\r
1207 $this->debug_message("*** p2p: Data Content Hdr:\n".$this->dump_binary($hdr));
\r
1208 //$this->SB_readln($socket);//Read ACK;
\r
1209 $Offset += $FileContentSize;
\r
1214 $MessageContent="\r\n".pack("C", 0);
\r
1216 "BYE MSNMSGR:MSNSLP/1.0\r\n".
\r
1217 "To: <msnmsgr:$from_email>\r\n".
\r
1218 "From: <msnmsgr:".$this->user.">\r\n".
\r
1219 "Via: MSNSLP/1.0/TLP ;branch={".$BranchGUID."}\r\n".
\r
1221 "Call-ID: ".$MsgBody['Call-ID']."\r\n".
\r
1222 "Max-Forwards: 0\r\n".
\r
1223 "Content-Type: application/x-msnmsgr-sessionclosebody\r\n".
\r
1224 "Content-Length: ".strlen($MessageContent)."\r\n\r\n".$MessageContent;
\r
1225 $footer=pack('N',0);
\r
1226 $hdr_TotalDataSizeLow=strlen($MessagePayload);
\r
1227 $hdr_TotalDataSizeHigh=0;
\r
1229 $hdr = pack("LLLLLLLLLLLL",
\r
1233 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1240 "MIME-Version: 1.0\r\n".
\r
1241 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1242 "P2P-Dest: $from_email\r\n\r\n$hdr$MessagePayload$footer";
\r
1243 $this->sb_writeln($socket, $id, "MSG $id D ".strlen($message));
\r
1245 $this->sb_writedata($socket, $message);
\r
1246 $this->debug_message("*** p2p: dump send BYE message :\n".$this->dump_binary($message));
\r
1251 //if ($hdr_Flag == 2) {
\r
1252 // just send ACK...
\r
1253 // $this->sb_writeln($socket, $id, "ACK $id");
\r
1256 if ($hdr_SessionID == 4) {
\r
1258 $this->debug_message("*** p2p: ignore flag 4");
\r
1261 $finished = false;
\r
1262 if ($hdr_TotalDataSizeHigh == 0) {
\r
1263 // only 32 bites size
\r
1264 if (($hdr_MessageLength + $hdr_DataOffsetLow) == $hdr_TotalDataSizeLow)
\r
1268 // we won't accept any file transfer
\r
1269 // so I think we won't get any message size need to use 64 bits
\r
1270 // 64 bits size here, can't count directly...
\r
1271 $totalsize = base_convert(sprintf("%X%08X", $hdr_TotalDataSizeHigh, $hdr_TotalDataSizeLow), 16, 10);
\r
1272 $dataoffset = base_convert(sprintf("%X%08X", $hdr_DataOffsetHigh, $hdr_DataOffsetLow), 16, 10);
\r
1273 $messagelength = base_convert(sprintf("%X", $hdr_MessageLength), 16, 10);
\r
1274 $now_size = bcadd($dataoffset, $messagelength);
\r
1275 if (bccomp($now_size, $totalsize) >= 0)
\r
1279 // ignore not finished split packet
\r
1280 $this->debug_message("*** p2p: ignore split packet, not finished");
\r
1283 //$new_id = ~$hdr_Identifier;
\r
1286 $hdr = pack("LLLLLLLLLLLL", $hdr_SessionID,
\r
1289 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1294 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh);
\r
1295 $footer = pack("L", 0);
\r
1296 $message = "MIME-Version: 1.0\r\nContent-Type: application/x-msnmsgrp2p\r\nP2P-Dest: $from_email\r\n\r\n$hdr$footer";
\r
1297 $len = strlen($message);
\r
1298 $this->sb_writeln($socket, $id, "MSG $id D $len");
\r
1300 $this->sb_writedata($socket, $message);
\r
1301 $this->debug_message("*** p2p: send acknowledgement for $hdr_SessionID");
\r
1302 $this->debug_message("*** p2p: dump sent message:\n".$this->dump_binary($hdr.$footer));
\r
1306 $this->debug_message("*** MSG from $from_email: $sMsg");
\r
1307 $this->callHandler('IMin', array('sender' => $from_email, 'message' => $sMsg, 'network' => $network, 'offline' => false));
\r
1310 $this->debug_message("*** User $user is offline. Trying OIM.");
\r
1311 $session['offline'] = true;
\r
1314 if (is_numeric($code)) {
\r
1315 $this->error = "Error code: $code, please check the detail information from: http://msnpiki.msnfanatic.com/index.php/Reference:Error_List";
\r
1316 $this->debug_message("*** SB: $this->error");
\r
1324 * Checks for new data and calls appropriate methods
\r
1326 * This method is usually called in an infinite loop to keep checking for new data
\r
1330 public function receive() {
\r
1331 // First, get an array of sockets that have data that is ready to be read
\r
1333 $ready = $this->getSockets();
\r
1334 $numrdy = stream_select($ready, $w = NULL, $x = NULL, NULL);
\r
1336 // Now that we've waited for something, go through the $ready
\r
1337 // array and read appropriately
\r
1339 foreach ($ready as $socket) {
\r
1340 if ($socket == $this->NSfp) {
\r
1341 $this->nsReceive();
\r
1343 $this->sbReceive($socket);
\r
1349 * Switchboard related methods
\r
1353 * Send a request for a switchboard session
\r
1355 * @param string $to Target email for switchboard session
\r
1357 private function reqSBSession($to) {
\r
1358 $this->debug_message("*** Request SB for $to");
\r
1359 $this->ns_writeln("XFR $this->id SB");
\r
1361 // Add to the queue of those waiting for a switchboard session reponse
\r
1362 $this->switchBoardSessions[$to] = array(
\r
1366 'joined' => false,
\r
1367 'offline' => false,
\r
1368 'XFRReqTime' => time()
\r
1370 $this->waitingForXFR[] = &$this->switchBoardSessions[$to];
\r
1374 * Following an XFR or RNG, connect to the switchboard session
\r
1376 * @param string $mode Mode, either 'Active' (in the case of XFR) or 'Passive' (in the case of RNG)
\r
1377 * @param string $ip IP of Switchboard
\r
1378 * @param integer $port Port of Switchboard
\r
1379 * @param string $to User on other end of Switchboard
\r
1380 * @param array $param Array of parameters - 'cki', 'ticket', 'sid'
\r
1381 * @return boolean true if successful
\r
1383 private function connectToSBSession($mode, $ip, $port, $to, $param) {
\r
1384 $this->debug_message("*** SB: Trying to connect to switchboard server $ip:$port");
\r
1386 $socket = @fsockopen($ip, $port, $errno, $errstr, $this->timeout);
\r
1388 $this->debug_message("*** SB: Can't connect to $ip:$port, error => $errno, $errstr");
\r
1392 // Store the socket in the lookup array
\r
1393 $this->switchBoardSessionLookup[$to] = $socket;
\r
1395 // Store the socket in the sessions array
\r
1396 $intsocket = (int) $socket;
\r
1397 $this->switchBoardSessions[$to] = array(
\r
1399 'socket' => $socket,
\r
1401 'joined' => false,
\r
1402 'offline' => false,
\r
1403 'XFRReqTime' => time()
\r
1406 // Change the index of the session to the socket
\r
1407 $this->switchBoardSessions[$intsocket] = $this->switchBoardSessions[$to];
\r
1408 unset($this->switchBoardSessions[$to]);
\r
1410 $id = &$this->switchBoardSessions[$intsocket]['id'];
\r
1412 if ($mode == 'Active') {
\r
1413 $cki_code = $param['cki'];
\r
1415 // SB: >>> USR {id} {user} {cki}
\r
1416 $this->sb_writeln($socket, $id, "USR $id $this->user $cki_code");
\r
1419 $ticket = $param['ticket'];
\r
1420 $sid = $param['sid'];
\r
1422 // SB: >>> ANS {id} {user} {ticket} {session_id}
\r
1423 $this->sb_writeln($socket, $id, "ANS $id $this->user $ticket $sid");
\r
1428 * Called when we want to end a switchboard session
\r
1429 * or a switchboard session ends
\r
1431 * @param resource $socket Socket
\r
1432 * @param boolean $killsession Whether to delete the session
\r
1435 private function endSBSession($socket, $killsession = false) {
\r
1436 if (!self::socketcheck($socket)) {
\r
1437 $this->sb_writeln($socket, $fake = 0, 'OUT');
\r
1441 // Unset session lookup value
\r
1442 $intsocket = (int) $socket;
\r
1443 unset($this->switchBoardSessionLookup[$this->switchBoardSessions[$intsocket]['to']]);
\r
1445 // Unset session itself
\r
1446 unset($this->switchBoardSessions[$intsocket]);
\r
1450 * Send a message via an existing SB session
\r
1452 * @param string $to Recipient for message
\r
1453 * @param string $message Message
\r
1454 * @return boolean true on success
\r
1456 private function sendMessageViaSB($to, $message) {
\r
1457 $socket = $this->switchBoardSessionLookup[$to];
\r
1458 if (self::socketcheck($socket)) {
\r
1462 if (!$this->switchBoardSessions[$to]['joined']) {
\r
1463 // If our participant has not joined the session yet we can't message them!
\r
1467 $intsocket = (int) $socket;
\r
1468 $id = &$this->switchBoardSessions[$intsocket]['id'];
\r
1470 $aMessage = $this->getMessage($Message);
\r
1472 $MsnObjDefine=$this->GetMsnObjDefine($aMessage);
\r
1473 if ($MsnObjDefine !== '') {
\r
1474 $SendString="MIME-Version: 1.0\r\nContent-Type: text/x-mms-emoticon\r\n\r\n$MsnObjDefine";
\r
1475 $len = strlen($SendString);
\r
1476 // TODO handle failure during write to socket
\r
1477 $this->sb_writeln($socket, $id, "MSG $id N $len");
\r
1478 $this->sb_writedata($socket, $SendString);
\r
1480 $len = strlen($aMessage);
\r
1481 // TODO handle failure during write to socket
\r
1482 $this->sb_writeln($socket, $id, "MSG $id N $len");
\r
1483 $this->sb_writedata($socket, $aMessage);
\r
1485 // Don't close the SB session, we might as well leave it open
\r
1491 * Send a message to a user on another network
\r
1493 * @param string $to Intended recipient
\r
1494 * @param string $message Message
\r
1495 * @param integer $network Network
\r
1498 private function sendOtherNetworkMessage($to, $message, $network) {
\r
1499 $message = $this->getMessage($message, $network);
\r
1500 $len = strlen($message);
\r
1501 // TODO Introduce error checking for message sending
\r
1502 $this->ns_writeln("UUM $this->id $to $network 1 $len");
\r
1503 $this->ns_writedata($Message);
\r
1504 $this->debug_message("*** Sent to $to (network: $network):\n$Message");
\r
1511 * @param string $to To address in form user@host.com(@network)
\r
1512 * where network is 1 for MSN, 32 for Yahoo
\r
1513 * and 'Offline' for offline messages
\r
1514 * @param string $message Message
\r
1516 public function sendMessage($to, $message) {
\r
1517 if ($message != '') {
\r
1518 list($name, $host, $network) = explode('@', $to);
\r
1519 $network = $network == '' ? 1 : $network;
\r
1520 $recipient = $name.$host;
\r
1522 if ($network === 1) {
\r
1523 if (!isset($this->switchBoardSessionLookup[$recipient]) && (!isset($this->switchBoardSessions[$recipient])
\r
1524 || time() - $this->switchBoardSessions[$recipient]['XFRReqTime'] > $this->XFRReqTimeout)) {
\r
1525 $this->debug_message("*** No existing SB session or request has timed out");
\r
1526 $this->reqSBSession($recipient);
\r
1529 $socket = $this->switchBoardSessionLookup[$to];
\r
1530 if ($this->switchBoardSessions[(int) $socket]['offline']) {
\r
1531 $this->debug_message("*** Contact ($recipient) offline, sending OIM");
\r
1532 $this->endSBSession($socket);
\r
1533 return $this->sendMessage($recipient.'@Offline', $message);
\r
1535 $this->debug_message("*** Attempting to send message to $recipient using existing SB session");
\r
1537 if ($this->sendMessageViaSB($recipient, $message)) {
\r
1538 $this->debug_message('*** Message sent successfully');
\r
1541 $this->debug_message('*** Message sending failed, requesting new SB session');
\r
1542 $this->reqSBSession($to);
\r
1547 } elseif ($network == 'Offline') {
\r
1549 //FIXME: ä¿®æ£Send OIM
\r
1551 $re_login = false;
\r
1552 for ($i = 0; $i < $this->oim_try; $i++) {
\r
1553 if (($oim_result = $this->sendOIM($recipient, $message, $lockkey)) === true) break;
\r
1554 if (is_array($oim_result) && $oim_result['challenge'] !== false) {
\r
1555 // need challenge lockkey
\r
1556 $this->debug_message("*** Need challenge code for ".$oim_result['challenge']);
\r
1557 $lockkey = $this->getChallenge($oim_result['challenge']);
\r
1560 if ($oim_result === false || $oim_result['auth_policy'] !== false) {
\r
1562 $this->debug_message("*** Can't send OIM, but we already re-logged-in again, so returning false");
\r
1565 $this->debug_message("*** Can't send OIM, maybe ticket expired, trying to login again");
\r
1567 // Maybe we need to re-login again
\r
1568 if (!$this->get_passport_ticket()) {
\r
1569 $this->debug_message("*** Can't re-login, something went wrong here, returning false");
\r
1572 $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 = $this->max_msn_message_len - $msg_header_len;
\r
3018 $maxlen = $this->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