5 Luke Fitzgerald <lw.fitzgerald@googlemail.com>
\r
7 Based on MSN class ver 2.0 by Tommy Wu, Ricky Su
\r
10 Documentation on the MSN protocol can be found at: http://msnpiki.msnfanatic.com/index.php/Main_Page
\r
12 This class uses MSNP15.
\r
14 In addition to PHP5, the additional php modules required are:
\r
15 curl pcre mhash mcrypt bcmath
\r
20 const PROTOCOL = 'MSNP15';
\r
21 const PASSPORT_URL = 'https://login.live.com/RST.srf';
\r
22 const BUILDVER = '8.1.0178';
\r
23 const PROD_KEY = 'PK}_A_0N_K%O?A9S';
\r
24 const PROD_ID = 'PROD0114ES4Z%Q5W';
\r
25 const LOGIN_METHOD = 'SSO';
\r
27 const OIM_SEND_URL = 'https://ows.messenger.msn.com/OimWS/oim.asmx';
\r
28 const OIM_SEND_SOAP = 'http://messenger.live.com/ws/2006/09/oim/Store2';
\r
30 const OIM_MAILDATA_URL = 'https://rsi.hotmail.com/rsi/rsi.asmx';
\r
31 const OIM_MAILDATA_SOAP = 'http://www.hotmail.msn.com/ws/2004/09/oim/rsi/GetMetadata';
\r
32 const OIM_READ_URL = 'https://rsi.hotmail.com/rsi/rsi.asmx';
\r
33 const OIM_READ_SOAP = 'http://www.hotmail.msn.com/ws/2004/09/oim/rsi/GetMessage';
\r
34 const OIM_DEL_URL = 'https://rsi.hotmail.com/rsi/rsi.asmx';
\r
35 const OIM_DEL_SOAP = 'http://www.hotmail.msn.com/ws/2004/09/oim/rsi/DeleteMessages';
\r
37 const MEMBERSHIP_URL = 'https://contacts.msn.com/abservice/SharingService.asmx';
\r
38 const MEMBERSHIP_SOAP = 'http://www.msn.com/webservices/AddressBook/FindMembership';
\r
40 const ADDMEMBER_URL = 'https://contacts.msn.com/abservice/SharingService.asmx';
\r
41 const ADDMEMBER_SOAP = 'http://www.msn.com/webservices/AddressBook/AddMember';
\r
43 const DELMEMBER_URL = 'https://contacts.msn.com/abservice/SharingService.asmx';
\r
44 const DELMEMBER_SOAP = 'http://www.msn.com/webservices/AddressBook/DeleteMember';
\r
46 // the message length (include header) is limited (maybe since WLM 8.5 released)
\r
47 // for WLM: 1664 bytes
\r
48 // for YIM: 518 bytes
\r
49 const MAX_MSN_MESSAGE_LEN = 1664;
\r
50 const MAX_YAHOO_MESSAGE_LEN = 518;
\r
58 private $password = '';
\r
59 private $NSfp = false;
\r
60 private $passport_policy = '';
\r
63 private $retry_wait;
\r
64 private $update_pending;
\r
65 private $PhotoStickerFile = false;
\r
66 private $Emotions = false;
\r
67 private $XFRReqTimeout = 60;
\r
68 private $SBStreamTimeout = 2;
\r
69 private $MsnObjArray = array();
\r
70 private $MsnObjMap = array();
\r
71 private $ABAuthHeader;
\r
75 private $server = 'messenger.hotmail.com';
\r
76 private $port = 1863;
\r
78 private $clientid = '';
\r
80 private $error = '';
\r
82 private $authed = false;
\r
84 private $oim_try = 3;
\r
86 private $font_fn = 'Arial';
\r
87 private $font_co = '333333';
\r
88 private $font_ef = '';
\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 authentication failed!';
\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
349 // Remove any remaining switchboard sessions
\r
350 $this->switchBoardSessions = array();
\r
351 $this->switchBoardSessionLookup = array();
\r
355 if (!$this->connect($this->user, $this->password)) {
\r
356 $this->signonFailure("!!! Could not connect to server: $this->error");
\r
361 if ($this->UpdateContacts() === false) {
\r
362 $this->signonFailure('');
\r
366 // Get membership lists
\r
367 if (($this->aContactList = $this->getMembershipList()) === false) {
\r
368 $this->signonFailure('!!! Get membership list failed');
\r
372 if ($this->update_pending) {
\r
373 if (is_array($this->aContactList)) {
\r
374 $pending = 'Pending';
\r
375 foreach ($this->aContactList as $u_domain => $aUserList) {
\r
376 foreach ($aUserList as $u_name => $aNetworks) {
\r
377 foreach ($aNetworks as $network => $aData) {
\r
378 if (isset($aData[$pending])) {
\r
381 foreach (array('Allow', 'Reverse') as $list) {
\r
382 if (isset($aData[$list]))
\r
385 if ($this->addMemberToList($u_name.'@'.$u_domain, $network, $list)) {
\r
386 $this->aContactList[$u_domain][$u_name][$network][$list] = false;
\r
392 $id = $aData[$pending];
\r
393 // we can delete it from pending now
\r
394 if ($this->delMemberFromList($id, $u_name.'@'.$u_domain, $network, $pending))
\r
395 unset($this->aContactList[$u_domain][$u_name][$network][$pending]);
\r
400 foreach (array('Allow', 'Reverse') as $list) {
\r
401 if (!isset($aData[$list])) {
\r
402 if ($this->addMemberToList($u_name.'@'.$u_domain, $network, $list))
\r
403 $this->aContactList[$u_domain][$u_name][$network][$list] = false;
\r
415 if (is_array($this->aContactList)) {
\r
416 foreach ($this->aContactList as $u_domain => $aUserList) {
\r
417 $str = '<d n="'.$u_domain.'">';
\r
418 $len += strlen($str);
\r
420 $this->aADL[$n] = '<ml l="1">'.$sList.'</ml>';
\r
423 $len = strlen($str);
\r
426 foreach ($aUserList as $u_name => $aNetworks) {
\r
427 foreach ($aNetworks as $network => $status) {
\r
428 $str = '<c n="'.$u_name.'" l="3" t="'.$network.'" />';
\r
429 $len += strlen($str);
\r
430 // max: 7500, but <ml l="1"></d></ml> is 19,
\r
434 $this->aADL[$n] = '<ml l="1">'.$sList.'</ml>';
\r
436 $sList = '<d n="'.$u_domain.'">'.$str;
\r
437 $len = strlen($sList);
\r
446 $this->aADL[$n] = '<ml l="1">'.$sList.'</ml>';
\r
447 // NS: >>> BLP {id} BL
\r
448 $this->ns_writeln("BLP $this->id BL");
\r
449 foreach ($this->aADL as $str) {
\r
450 $len = strlen($str);
\r
451 // NS: >>> ADL {id} {size}
\r
452 $this->ns_writeln("ADL $this->id $len");
\r
453 $this->ns_writedata($str);
\r
455 // NS: >>> PRP {id} MFN name
\r
456 if ($this->alias == '') $this->alias = $user;
\r
457 $aliasname = rawurlencode($this->alias);
\r
458 $this->ns_writeln("PRP $this->id MFN $aliasname");
\r
459 //è¨å®šå€‹äººå¤§é è²¼
\r
460 //$MsnObj=$this->PhotoStckObj();
\r
461 // NS: >>> CHG {id} {status} {clientid} {msnobj}
\r
462 $this->ns_writeln("CHG $this->id NLN $this->clientid");
\r
463 if ($this->PhotoStickerFile !== false)
\r
464 $this->ns_writeln("CHG $this->id NLN $this->clientid ".rawurlencode($this->MsnObj($this->PhotoStickerFile)));
\r
465 // NS: >>> UUX {id} length
\r
466 $str = '<Data><PSM>'.htmlspecialchars($this->psm).'</PSM><CurrentMedia></CurrentMedia><MachineGuid></MachineGuid></Data>';
\r
467 $len = strlen($str);
\r
468 $this->ns_writeln("UUX $this->id $len");
\r
469 $this->ns_writedata($str);
\r
470 if (!self::socketcheck($this->NSfp)) {
\r
471 $this->debug_message('*** Connected, waiting for commands');
\r
474 $this->NSRetryWait($this->retry_wait);
\r
480 * Called if there is an error during signon
\r
482 * @param string $message Error message to log
\r
485 private function signonFailure($message) {
\r
486 if(!empty($message)) {
\r
487 $this->debug_message($message);
\r
489 $this->callHandler('ConnectFailed');
\r
490 $this->NSRetryWait($this->retry_wait);
\r
494 * Log out and close the NS connection
\r
498 private function nsLogout() {
\r
499 if (is_resource($this->NSfp) && !feof($this->NSfp)) {
\r
502 $this->ns_writeln("OUT");
\r
503 fclose($this->NSfp);
\r
504 $this->NSfp = false;
\r
505 $this->debug_message("*** Logged out");
\r
510 * NS and SB command handling methods
\r
514 * Read and handle incoming command from NS
\r
518 private function nsReceive() {
\r
519 // Sign in again if not signed in or socket failed
\r
520 if (!is_resource($this->NSfp) || self::socketcheck($this->NSfp)) {
\r
521 $this->callHandler('Reconnect');
\r
522 $this->NSRetryWait($this->retry_wait);
\r
527 $data = $this->ns_readln();
\r
528 if ($data === false) {
\r
529 // There was no data / an error when reading from the socket so reconnect
\r
530 $this->callHandler('Reconnect');
\r
531 $this->NSRetryWait($this->retry_wait);
\r
536 switch (substr($data, 0, 3)) {
\r
538 // after 'USR {id} OK {user} {verify} 0' response, the server will send SBS and profile to us
\r
539 // NS: <<< SBS 0 null
\r
545 // refresh ADL, so we re-send it again
\r
546 if (is_array($this->aADL)) {
\r
547 foreach ($this->aADL as $str) {
\r
548 $len = strlen($str);
\r
549 // NS: >>> ADL {id} {size}
\r
550 $this->ns_writeln("ADL $this->id $len");
\r
551 $this->ns_writedata($str);
\r
557 // NS: <<< LST {email} {alias} 11 0
\r
558 @list(/* LST */, $email) = @explode(' ', $data);
\r
559 @list($u_name, $u_domain) = @explode('@', $email);
\r
560 if (!isset($this->aContactList[$u_domain][$u_name][1])) {
\r
561 $this->aContactList[$u_domain][$u_name][1]['Allow'] = 'Allow';
\r
562 $this->debug_message("*** Added to contact list: $u_name@$u_domain");
\r
567 // randomly, we get ADL command, someone add us to their contact list for MSNP15
\r
568 // NS: <<< ADL 0 {size}
\r
569 @list(/* ADL */, /* 0 */, $size) = @explode(' ', $data);
\r
570 if (is_numeric($size) && $size > 0) {
\r
571 $data = $this->ns_readdata($size);
\r
572 preg_match('#<ml><d n="([^"]+)"><c n="([^"]+)"(.*) t="(\d*)"(.*) /></d></ml>#', $data, $matches);
\r
573 if (is_array($matches) && count($matches) > 0) {
\r
574 $u_domain = $matches[1];
\r
575 $u_name = $matches[2];
\r
576 $network = $matches[4];
\r
577 if (isset($this->aContactList[$u_domain][$u_name][$network]))
\r
578 $this->debug_message("*** Someone (network: $network) added us to their list (but already in our list): $u_name@$u_domain");
\r
582 foreach (array('Allow', 'Reverse') as $list) {
\r
583 if (!$this->addMemberToList($u_name.'@'.$u_domain, $network, $list)) {
\r
585 $this->debug_message("*** Could not add $u_name@$u_domain (network: $network) to $list list");
\r
588 $aTickets = $this->get_passport_ticket();
\r
589 if (!$aTickets || !is_array($aTickets)) {
\r
590 // failed to login? ignore it
\r
591 $this->debug_message("*** Could not re-login, something wrong here");
\r
592 $this->debug_message("*** Could not add $u_name@$u_domain (network: $network) to $list list");
\r
596 $this->ticket = $aTickets;
\r
597 $this->debug_message("**** Got new ticket, trying again");
\r
598 if (!$this->addMemberToList($u_name.'@'.$u_domain, $network, $list)) {
\r
599 $this->debug_message("*** Could not add $u_name@$u_domain (network: $network) to $list list");
\r
603 $this->aContactList[$u_domain][$u_name][$network][$list] = false;
\r
606 $this->debug_message("*** Someone (network: $network) added us to their list: $u_name@$u_domain");
\r
608 $str = '<ml l="1"><d n="'.$u_domain.'"><c n="'.$u_name.'" l="3" t="'.$network.'" /></d></ml>';
\r
609 $len = strlen($str);
\r
611 $this->callHandler('AddedToList', array('screenname' => $u_name.'@'.$u_domain, 'network' => $network));
\r
614 $this->debug_message("*** Someone added us to their list: $data");
\r
619 // randomly, we get RML command, someome remove us to their contact list for MSNP15
\r
620 // NS: <<< RML 0 {size}
\r
621 @list(/* RML */, /* 0 */, $size) = @explode(' ', $data);
\r
622 if (is_numeric($size) && $size > 0) {
\r
623 $data = $this->ns_readdata($size);
\r
624 preg_match('#<ml><d n="([^"]+)"><c n="([^"]+)"(.*) t="(\d*)"(.*) /></d></ml>#', $data, $matches);
\r
625 if (is_array($matches) && count($matches) > 0) {
\r
626 $u_domain = $matches[1];
\r
627 $u_name = $matches[2];
\r
628 $network = $matches[4];
\r
629 if (isset($this->aContactList[$u_domain][$u_name][$network])) {
\r
630 $aData = $this->aContactList[$u_domain][$u_name][$network];
\r
632 foreach ($aData as $list => $id)
\r
633 $this->delMemberFromList($id, $u_name.'@'.$u_domain, $network, $list);
\r
635 unset($this->aContactList[$u_domain][$u_name][$network]);
\r
636 $this->debug_message("*** Someone (network: $network) removed us from their list: $u_name@$u_domain");
\r
639 $this->debug_message("*** Someone (network: $network) removed us from their list (but not in our list): $u_name@$u_domain");
\r
641 $this->callHandler('RemovedFromList', array('screenname' => $u_name.'@'.$u_domain, 'network' => $network));
\r
644 $this->debug_message("*** Someone removed us from their list: $data");
\r
649 // randomly, we get MSG notification from server
\r
650 // NS: <<< MSG Hotmail Hotmail {size}
\r
651 @list(/* MSG */, /* Hotmail */, /* Hotmail */, $size) = @explode(' ', $data);
\r
652 if (is_numeric($size) && $size > 0) {
\r
653 $data = $this->ns_readdata($size);
\r
654 $aLines = @explode("\n", $data);
\r
658 foreach ($aLines as $line) {
\r
659 $line = rtrim($line);
\r
661 if ($line === '') {
\r
665 if (strncasecmp($line, 'Content-Type:', 13) == 0) {
\r
666 if (strpos($line, 'text/x-msmsgsinitialmdatanotification') === false && strpos($line, 'text/x-msmsgsoimnotification') === false) {
\r
667 // we just need text/x-msmsgsinitialmdatanotification
\r
668 // or text/x-msmsgsoimnotification
\r
675 if (strncasecmp($line, 'Mail-Data:', 10) == 0) {
\r
676 $maildata = trim(substr($line, 10));
\r
681 $this->debug_message("*** Ignoring MSG for: $line");
\r
684 if ($maildata == '') {
\r
685 $this->debug_message("*** Ignoring MSG not for OIM");
\r
689 if (strcasecmp($maildata, 'too-large') == 0) {
\r
690 $this->debug_message("*** Large mail-data, need to get the data via SOAP");
\r
691 $maildata = $this->getOIM_maildata();
\r
692 if ($maildata === false) {
\r
693 $this->debug_message("*** Could not get mail-data via SOAP");
\r
695 // maybe we need to re-login again
\r
696 $aTickets = $this->get_passport_ticket();
\r
697 if (!$aTickets || !is_array($aTickets)) {
\r
698 // failed to login? ignore it
\r
699 $this->debug_message("*** Could not re-login, something wrong here, ignoring this OIM");
\r
703 $this->ticket = $aTickets;
\r
704 $this->debug_message("*** Got new ticket, trying again");
\r
705 $maildata = $this->getOIM_maildata();
\r
706 if ($maildata === false) {
\r
707 $this->debug_message("*** Could not get mail-data via SOAP, and re-login already attempted, ignoring this OIM");
\r
712 // could be a lots of <M>...</M>, so we can't use preg_match here
\r
716 $start = strpos($p, '<M>');
\r
717 $end = strpos($p, '</M>');
\r
718 if ($start === false || $end === false || $start > $end) break;
\r
720 $sOIM = substr($p, $start, $end - $start);
\r
722 $p = substr($p, $end);
\r
724 if (count($aOIMs) == 0) {
\r
725 $this->debug_message("*** Ignoring empty OIM");
\r
728 foreach ($aOIMs as $maildata) {
\r
729 // T: 11 for MSN, 13 for Yahoo
\r
730 // S: 6 for MSN, 7 for Yahoo
\r
731 // RT: the datetime received by server
\r
732 // RS: already read or not
\r
733 // SZ: size of message
\r
736 // F: always 00000000-0000-0000-0000-000000000009
\r
738 preg_match('#<T>(.*)</T>#', $maildata, $matches);
\r
739 if (count($matches) == 0) {
\r
740 $this->debug_message("*** Ignoring OIM maildata without <T>type</T>");
\r
743 $oim_type = $matches[1];
\r
744 if ($oim_type = 13)
\r
748 preg_match('#<E>(.*)</E>#', $maildata, $matches);
\r
749 if (count($matches) == 0) {
\r
750 $this->debug_message("*** Ignoring OIM maildata without <E>sender</E>");
\r
753 $oim_sender = $matches[1];
\r
754 preg_match('#<I>(.*)</I>#', $maildata, $matches);
\r
755 if (count($matches) == 0) {
\r
756 $this->debug_message("*** Ignoring OIM maildata without <I>msgid</I>");
\r
759 $oim_msgid = $matches[1];
\r
760 preg_match('#<SZ>(.*)</SZ>#', $maildata, $matches);
\r
761 $oim_size = (count($matches) == 0) ? 0 : $matches[1];
\r
762 preg_match('#<RT>(.*)</RT>#', $maildata, $matches);
\r
763 $oim_time = (count($matches) == 0) ? 0 : $matches[1];
\r
764 $this->debug_message("*** OIM received from $oim_sender, Time: $oim_time, MSGID: $oim_msgid, size: $oim_size");
\r
765 $sMsg = $this->getOIM_message($oim_msgid);
\r
766 if ($sMsg === false) {
\r
767 $this->debug_message("*** Could not get OIM, msgid = $oim_msgid");
\r
769 $this->debug_message("*** Could not get OIM via SOAP, and re-login already attempted, ignoring this OIM");
\r
772 $aTickets = $this->get_passport_ticket();
\r
773 if (!$aTickets || !is_array($aTickets)) {
\r
774 // failed to login? ignore it
\r
775 $this->debug_message("*** Could not re-login, something wrong here, ignoring this OIM");
\r
779 $this->ticket = $aTickets;
\r
780 $this->debug_message("*** get new ticket, try it again");
\r
781 $sMsg = $this->getOIM_message($oim_msgid);
\r
782 if ($sMsg === false) {
\r
783 $this->debug_message("*** Could not get OIM via SOAP, and re-login already attempted, ignoring this OIM");
\r
787 $this->debug_message("*** MSG (Offline) from $oim_sender (network: $network): $sMsg");
\r
788 $this->callHandler('IMin', array('sender' => $oim_sender, 'message' => $sMsg, 'network' => $network, 'offline' => true));
\r
794 // randomly, we get UBM, this is the message from other network, like Yahoo!
\r
795 // NS: <<< UBM {email} $network $type {size}
\r
796 @list(/* UBM */, $from_email, $network, $type, $size) = @explode(' ', $data);
\r
797 if (is_numeric($size) && $size > 0) {
\r
798 $data = $this->ns_readdata($size);
\r
799 $aLines = @explode("\n", $data);
\r
803 foreach ($aLines as $line) {
\r
804 $line = rtrim($line);
\r
806 if ($line === '') {
\r
810 if (strncasecmp($line, 'TypingUser:', 11) == 0) {
\r
816 $aSubLines = @explode("\r", $line);
\r
817 foreach ($aSubLines as $str) {
\r
824 $this->debug_message("*** Ignoring message from $from_email: $line");
\r
827 $this->debug_message("*** MSG from $from_email (network: $network): $sMsg");
\r
828 $this->callHandler('IMin', array('sender' => $from_email, 'message' => $sMsg, 'network' => $network, 'offline' => false));
\r
833 // randomly, we get UBX notification from server
\r
834 // NS: <<< UBX email {network} {size}
\r
835 @list(/* UBX */, /* email */, /* network */, $size) = @explode(' ', $data);
\r
836 // we don't need the notification data, so just ignore it
\r
837 if (is_numeric($size) && $size > 0)
\r
838 $this->ns_readdata($size);
\r
842 // randomly, we'll get challenge from server
\r
843 // NS: <<< CHL 0 {code}
\r
844 @list(/* CHL */, /* 0 */, $chl_code) = @explode(' ', $data);
\r
845 $fingerprint = $this->getChallenge($chl_code);
\r
846 // NS: >>> QRY {id} {product_id} 32
\r
847 // NS: >>> fingerprint
\r
848 $this->ns_writeln("QRY $this->id ".self::PROD_ID.' 32');
\r
849 $this->ns_writedata($fingerprint);
\r
850 $this->ns_writeln("CHG $this->id NLN $this->clientid");
\r
851 if ($this->PhotoStickerFile !== false)
\r
852 $this->ns_writeln("CHG $this->id NLN $this->clientid ".rawurlencode($this->MsnObj($this->PhotoStickerFile)));
\r
855 // NS: <<< CHG {id} {status} {code}
\r
857 // change our status to online first
\r
861 // sometimes, NS will redirect to another NS
\r
863 // NS: <<< XFR {id} NS {server} 0 {server}
\r
865 // NS: <<< XFR {id} NS {server} U D
\r
866 // for normal switchboard XFR
\r
867 // NS: <<< XFR {id} SB {server} CKI {cki} U messenger.msn.com 0
\r
868 @list(/* XFR */, /* {id} */, $server_type, $server, /* CKI */, $cki_code) = @explode(' ', $data);
\r
869 @list($ip, $port) = @explode(':', $server);
\r
870 if ($server_type != 'SB') {
\r
872 // this connection will close after XFR
\r
877 $this->debug_message("NS: <<< XFR SB");
\r
878 $session = array_shift($this->waitingForXFR);
\r
879 $this->connectToSBSession('Active', $ip, $port, $session['to'], array('cki' => $cki_code));
\r
882 // NS: <<< QNG {time}
\r
883 @list(/* QNG */, $ping_wait) = @explode(' ', $data);
\r
884 $this->callHandler('Pong', $ping_wait);
\r
888 if ($this->PhotoStickerFile !== false)
\r
889 $this->ns_writeln("CHG $this->id NLN $this->clientid ".rawurlencode($this->MsnObj($this->PhotoStickerFile)));
\r
891 $this->ns_writeln("CHG $this->id NLN $this->clientid");
\r
892 // someone is trying to talk to us
\r
893 // NS: <<< RNG {session_id} {server} {auth_type} {ticket} {email} {alias} U {client} 0
\r
894 $this->debug_message("NS: <<< RNG $data");
\r
895 @list(/* RNG */, $sid, $server, /* auth_type */, $ticket, $email, $name) = @explode(' ', $data);
\r
896 @list($sb_ip, $sb_port) = @explode(':', $server);
\r
897 $this->debug_message("*** RING from $email, $sb_ip:$sb_port");
\r
898 $this->addContact($email, 1, $email, true);
\r
899 $this->connectToSBSession('Passive', $sb_ip, $sb_port, $email, array('sid' => $sid, 'ticket' => $ticket));
\r
903 // NS: <<< NLN {status} {email} {networkid} {nickname} {clientid} {dpobj}
\r
904 @list(/* NLN */, $status, $email, $network, $nickname) = @explode(' ', $data);
\r
905 $this->callHandler('StatusChange', array('screenname' => $email, 'status' => $status, 'network' => $network, 'nickname' => $nickname));
\r
909 // force logout from NS
\r
911 $this->debug_message("*** LOGOUT from NS");
\r
912 return $this->nsLogout();
\r
915 $code = substr($data,0,3);
\r
916 if (is_numeric($code)) {
\r
917 $this->error = "Error code: $code, please check the detail information from: http://msnpiki.msnfanatic.com/index.php/Reference:Error_List";
\r
918 $this->debug_message("*** NS: $this->error");
\r
920 return $this->nsLogout();
\r
927 * Read and handle incoming command/message from
\r
928 * a switchboard session socket
\r
930 private function sbReceive($socket) {
\r
931 $intsocket = (int) $socket;
\r
932 $session = &$this->switchBoardSessions[$intsocket];
\r
934 if (feof($socket)) {
\r
935 // Unset session lookup value
\r
936 unset($this->switchBoardSessionLookup[$session['to']]);
\r
938 // Unset session itself
\r
939 unset($this->switchBoardSessions[$intsocket]);
\r
943 $id = &$session['id'];
\r
945 $data = $this->sb_readln($socket);
\r
946 $code = substr($data, 0, 3);
\r
949 // SB: <<< IRO {id} {rooster} {roostercount} {email} {alias} {clientid}
\r
950 @list(/* IRO */, /* id */, $cur_num, $total, $email, $alias, $clientid) = @explode(' ', $data);
\r
951 $this->debug_message("*** $email joined session");
\r
952 $session['joined'] = true;
\r
955 $this->debug_message("*** Quit for BYE");
\r
956 $this->endSBSession($socket);
\r
959 // SB: <<< USR {id} OK {user} {alias}
\r
960 // we don't need the data, just ignore it
\r
961 // request user to join this switchboard
\r
962 // SB: >>> CAL {id} {user}
\r
963 $this->sb_writeln($socket, $id, "CAL $id ".$session['to']);
\r
966 // SB: <<< CAL {id} RINGING {?}
\r
967 // we don't need this, just ignore, and wait for other response
\r
971 // SB: <<< JOI {user} {alias} {clientid?}
\r
973 // we don't need the data, just ignore it
\r
974 // no more user here
\r
975 $session['joined'] = true;
\r
978 // SB: <<< MSG {email} {alias} {len}
\r
979 @list(/* MSG */, $from_email, /* alias */, $len) = @explode(' ', $data);
\r
981 $data = $this->sb_readdata($socket, $len);
\r
982 $aLines = @explode("\n", $data);
\r
987 foreach ($aLines as $line) {
\r
988 $line = rtrim($line);
\r
990 if ($line === '') {
\r
994 if (strncasecmp($line, 'TypingUser:', 11) == 0) {
\r
995 // typing notification, just ignore
\r
999 if (strncasecmp($line, 'Chunk:', 6) == 0) {
\r
1000 // we don't handle any split message, just ignore
\r
1004 if (strncasecmp($line, 'Content-Type: application/x-msnmsgrp2p', 38) == 0) {
\r
1005 // p2p message, ignore it, but we need to send acknowledgement for it...
\r
1007 $p = strstr($data, "\n\n");
\r
1009 if ($p === false) {
\r
1010 $p = strstr($data, "\r\n\r\n");
\r
1012 $sMsg = substr($p, 4);
\r
1015 $sMsg = substr($p, 2);
\r
1018 if (strncasecmp($line, 'Content-Type: application/x-', 28) == 0) {
\r
1019 // ignore all application/x-... message
\r
1021 // application/x-ms-ink => ink message
\r
1025 if (strncasecmp($line, 'Content-Type: text/x-', 21) == 0) {
\r
1026 // ignore all text/x-... message
\r
1028 // text/x-msnmsgr-datacast => nudge, voice clip....
\r
1029 // text/x-mms-animemoticon => customized animemotion word
\r
1040 $this->debug_message("*** Ignoring SB data from $from_email: $line");
\r
1044 // we will ignore any p2p message after sending acknowledgement
\r
1046 $len = strlen($sMsg);
\r
1047 $this->debug_message("*** p2p message from $from_email, size $len");
\r
1048 // header = 48 bytes
\r
1049 // content >= 0 bytes
\r
1050 // footer = 4 bytes
\r
1051 // so it need to >= 52 bytes
\r
1052 /*if ($len < 52) {
\r
1053 $this->debug_message("*** p2p: size error, less than 52!");
\r
1056 $aDwords = @unpack("V12dword", $sMsg);
\r
1057 if (!is_array($aDwords)) {
\r
1058 $this->debug_message("*** p2p: header unpack error!");
\r
1061 $this->debug_message("*** p2p: dump received message:\n".$this->dump_binary($sMsg));
\r
1062 $hdr_SessionID = $aDwords['dword1'];
\r
1063 $hdr_Identifier = $aDwords['dword2'];
\r
1064 $hdr_DataOffsetLow = $aDwords['dword3'];
\r
1065 $hdr_DataOffsetHigh = $aDwords['dword4'];
\r
1066 $hdr_TotalDataSizeLow = $aDwords['dword5'];
\r
1067 $hdr_TotalDataSizeHigh = $aDwords['dword6'];
\r
1068 $hdr_MessageLength = $aDwords['dword7'];
\r
1069 $hdr_Flag = $aDwords['dword8'];
\r
1070 $hdr_AckID = $aDwords['dword9'];
\r
1071 $hdr_AckUID = $aDwords['dword10'];
\r
1072 $hdr_AckSizeLow = $aDwords['dword11'];
\r
1073 $hdr_AckSizeHigh = $aDwords['dword12'];
\r
1074 $this->debug_message("*** p2p: header SessionID = $hdr_SessionID");
\r
1075 $this->debug_message("*** p2p: header Inentifier = $hdr_Identifier");
\r
1076 $this->debug_message("*** p2p: header Data Offset Low = $hdr_DataOffsetLow");
\r
1077 $this->debug_message("*** p2p: header Data Offset High = $hdr_DataOffsetHigh");
\r
1078 $this->debug_message("*** p2p: header Total Data Size Low = $hdr_TotalDataSizeLow");
\r
1079 $this->debug_message("*** p2p: header Total Data Size High = $hdr_TotalDataSizeHigh");
\r
1080 $this->debug_message("*** p2p: header MessageLength = $hdr_MessageLength");
\r
1081 $this->debug_message("*** p2p: header Flag = $hdr_Flag");
\r
1082 $this->debug_message("*** p2p: header AckID = $hdr_AckID");
\r
1083 $this->debug_message("*** p2p: header AckUID = $hdr_AckUID");
\r
1084 $this->debug_message("*** p2p: header AckSize Low = $hdr_AckSizeLow");
\r
1085 $this->debug_message("*** p2p: header AckSize High = $hdr_AckSizeHigh");
\r
1086 if ($hdr_Flag == 2) {
\r
1087 //This is an ACK from SB ignore....
\r
1088 $this->debug_message("*** p2p: //This is an ACK from SB ignore....:\n");
\r
1091 $MsgBody = $this->linetoArray(substr($sMsg, 48, -4));
\r
1092 $this->debug_message("*** p2p: body".print_r($MsgBody, true));
\r
1093 if (($MsgBody['EUF-GUID']=='{A4268EEC-FEC5-49E5-95C3-F126696BDBF6}')&&($PictureFilePath=$this->GetPictureFilePath($MsgBody['Context']))) {
\r
1095 if ($this->sb_readln($socket) === false) break;
\r
1097 $this->debug_message("*** p2p: Inv hdr:\n".$this->dump_binary(substr($sMsg, 0, 48)));
\r
1098 preg_match('/{([0-9A-F\-]*)}/i', $MsgBody['Via'], $Matches);
\r
1099 $BranchGUID = $Matches[1];
\r
1100 //it's an invite to send a display picture.
\r
1101 $new_id = ~$hdr_Identifier;
\r
1103 "LLLLLLLLLLLL", $hdr_SessionID,
\r
1106 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1111 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh
\r
1113 $footer = pack("L", 0);
\r
1114 $message = "MIME-Version: 1.0\r\nContent-Type: application/x-msnmsgrp2p\r\nP2P-Dest: $from_email\r\n\r\n$hdr$footer";
\r
1115 $len = strlen($message);
\r
1116 $this->sb_writeln($socket, $id, "MSG $id D $len");
\r
1117 $this->sb_writedata($socket, $message);
\r
1118 $this->debug_message("*** p2p: send display picture acknowledgement for $hdr_SessionID");
\r
1119 $this->debug_message("*** p2p: Invite ACK message:\n".$this->dump_binary($message));
\r
1120 $this->sb_readln($socket); // Read ACK;
\r
1121 $this->debug_message("*** p2p: Invite ACK Hdr:\n".$this->dump_binary($hdr));
\r
1123 //Send 200 OK message
\r
1124 $MessageContent="SessionID: ".$MsgBody['SessionID']."\r\n\r\n".pack("C", 0);
\r
1126 "MSNSLP/1.0 200 OK\r\n".
\r
1127 "To: <msnmsgr:".$from_email.">\r\n".
\r
1128 "From: <msnmsgr:".$this->user.">\r\n".
\r
1129 "Via: ".$MsgBody['Via']."\r\n".
\r
1130 "CSeq: ".($MsgBody['CSeq']+1)."\r\n".
\r
1131 "Call-ID: ".$MsgBody['Call-ID']."\r\n".
\r
1132 "Max-Forwards: 0\r\n".
\r
1133 "Content-Type: application/x-msnmsgr-sessionreqbody\r\n".
\r
1134 "Content-Length: ".strlen($MessageContent)."\r\n\r\n".
\r
1136 $hdr_TotalDataSizeLow=strlen($MessagePayload);
\r
1137 $hdr_TotalDataSizeHigh=0;
\r
1139 "LLLLLLLLLLLL", $hdr_SessionID,
\r
1142 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1143 strlen($MessagePayload),
\r
1151 "MIME-Version: 1.0\r\n".
\r
1152 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1153 "P2P-Dest: $from_email\r\n\r\n$hdr$MessagePayload$footer";
\r
1154 $this->sb_writeln($socket, $id, "MSG $id D ".strlen($message));
\r
1155 $this->sb_writedata($socket, $message);
\r
1156 $this->debug_message("*** p2p: dump 200 ok message:\n".$this->dump_binary($message));
\r
1157 $this->sb_readln($socket); // Read ACK;
\r
1159 $this->debug_message("*** p2p: 200 ok:\n".$this->dump_binary($hdr));
\r
1160 // send data preparation message
\r
1161 // send 4 null bytes as data
\r
1162 $hdr_TotalDataSizeLow = 4;
\r
1163 $hdr_TotalDataSizeHigh = 0 ;
\r
1167 $MsgBody['SessionID'],
\r
1170 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1171 $hdr_TotalDataSizeLow,
\r
1178 "MIME-Version: 1.0\r\n".
\r
1179 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1180 "P2P-Dest: $from_email\r\n\r\n$hdr".pack('L', 0)."$footer";
\r
1181 $this->sb_writeln($socket, $id, "MSG $id D ".strlen($message));
\r
1182 $this->sb_writedata($socket, $message);
\r
1183 $this->debug_message("*** p2p: dump send Data preparation message:\n".$this->dump_binary($message));
\r
1184 $this->debug_message("*** p2p: Data Prepare Hdr:\n".$this->dump_binary($hdr));
\r
1185 $this->sb_readln($socket); // Read ACK;
\r
1187 // send Data Content..
\r
1188 $footer=pack('N',1);
\r
1190 $FileSize=filesize($PictureFilePath);
\r
1191 if ($hTitle=fopen($PictureFilePath,'rb')) {
\r
1194 while (!feof($hTitle)) {
\r
1195 $FileContent = fread($hTitle, 1024);
\r
1196 $FileContentSize = strlen($FileContent);
\r
1199 $MsgBody['SessionID'],
\r
1210 "MIME-Version: 1.0\r\n".
\r
1211 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1212 "P2P-Dest: $from_email\r\n\r\n$hdr$FileContent$footer";
\r
1213 $this->sb_writeln($socket, $id, "MSG $id D ".strlen($message));
\r
1214 $this->sb_writedata($socket, $message);
\r
1215 $this->debug_message("*** p2p: dump send Data Content message $Offset / $FileSize :\n".$this->dump_binary($message));
\r
1216 $this->debug_message("*** p2p: Data Content Hdr:\n".$this->dump_binary($hdr));
\r
1217 //$this->SB_readln($socket);//Read ACK;
\r
1218 $Offset += $FileContentSize;
\r
1223 $MessageContent="\r\n".pack("C", 0);
\r
1225 "BYE MSNMSGR:MSNSLP/1.0\r\n".
\r
1226 "To: <msnmsgr:$from_email>\r\n".
\r
1227 "From: <msnmsgr:".$this->user.">\r\n".
\r
1228 "Via: MSNSLP/1.0/TLP ;branch={".$BranchGUID."}\r\n".
\r
1230 "Call-ID: ".$MsgBody['Call-ID']."\r\n".
\r
1231 "Max-Forwards: 0\r\n".
\r
1232 "Content-Type: application/x-msnmsgr-sessionclosebody\r\n".
\r
1233 "Content-Length: ".strlen($MessageContent)."\r\n\r\n".$MessageContent;
\r
1234 $footer=pack('N',0);
\r
1235 $hdr_TotalDataSizeLow=strlen($MessagePayload);
\r
1236 $hdr_TotalDataSizeHigh=0;
\r
1238 $hdr = pack("LLLLLLLLLLLL",
\r
1242 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1249 "MIME-Version: 1.0\r\n".
\r
1250 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1251 "P2P-Dest: $from_email\r\n\r\n$hdr$MessagePayload$footer";
\r
1252 $this->sb_writeln($socket, $id, "MSG $id D ".strlen($message));
\r
1254 $this->sb_writedata($socket, $message);
\r
1255 $this->debug_message("*** p2p: dump send BYE message :\n".$this->dump_binary($message));
\r
1260 //if ($hdr_Flag == 2) {
\r
1261 // just send ACK...
\r
1262 // $this->sb_writeln($socket, $id, "ACK $id");
\r
1265 if ($hdr_SessionID == 4) {
\r
1267 $this->debug_message("*** p2p: ignore flag 4");
\r
1270 $finished = false;
\r
1271 if ($hdr_TotalDataSizeHigh == 0) {
\r
1272 // only 32 bites size
\r
1273 if (($hdr_MessageLength + $hdr_DataOffsetLow) == $hdr_TotalDataSizeLow)
\r
1277 // we won't accept any file transfer
\r
1278 // so I think we won't get any message size need to use 64 bits
\r
1279 // 64 bits size here, can't count directly...
\r
1280 $totalsize = base_convert(sprintf("%X%08X", $hdr_TotalDataSizeHigh, $hdr_TotalDataSizeLow), 16, 10);
\r
1281 $dataoffset = base_convert(sprintf("%X%08X", $hdr_DataOffsetHigh, $hdr_DataOffsetLow), 16, 10);
\r
1282 $messagelength = base_convert(sprintf("%X", $hdr_MessageLength), 16, 10);
\r
1283 $now_size = bcadd($dataoffset, $messagelength);
\r
1284 if (bccomp($now_size, $totalsize) >= 0)
\r
1288 // ignore not finished split packet
\r
1289 $this->debug_message("*** p2p: ignore split packet, not finished");
\r
1292 //$new_id = ~$hdr_Identifier;
\r
1295 $hdr = pack("LLLLLLLLLLLL", $hdr_SessionID,
\r
1298 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1303 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh);
\r
1304 $footer = pack("L", 0);
\r
1305 $message = "MIME-Version: 1.0\r\nContent-Type: application/x-msnmsgrp2p\r\nP2P-Dest: $from_email\r\n\r\n$hdr$footer";
\r
1306 $len = strlen($message);
\r
1307 $this->sb_writeln($socket, $id, "MSG $id D $len");
\r
1309 $this->sb_writedata($socket, $message);
\r
1310 $this->debug_message("*** p2p: send acknowledgement for $hdr_SessionID");
\r
1311 $this->debug_message("*** p2p: dump sent message:\n".$this->dump_binary($hdr.$footer));
\r
1315 $this->debug_message("*** MSG from $from_email: $sMsg");
\r
1316 $this->callHandler('IMin', array('sender' => $from_email, 'message' => $sMsg, 'network' => 1, 'offline' => false));
\r
1319 $this->debug_message('*** User '.$session['to'].' is offline. Trying OIM.');
\r
1320 $session['offline'] = true;
\r
1323 if (is_numeric($code)) {
\r
1324 $this->error = "Error code: $code, please check the detail information from: http://msnpiki.msnfanatic.com/index.php/Reference:Error_List";
\r
1325 $this->debug_message("*** SB: $this->error");
\r
1332 * Checks for new data and calls appropriate methods
\r
1334 * This method is usually called in an infinite loop to keep checking for new data
\r
1338 public function receive() {
\r
1339 // First, get an array of sockets that have data that is ready to be read
\r
1341 $ready = $this->getSockets();
\r
1342 $numrdy = stream_select($ready, $w = NULL, $x = NULL, NULL);
\r
1344 // Now that we've waited for something, go through the $ready
\r
1345 // array and read appropriately
\r
1347 foreach ($ready as $socket) {
\r
1348 if ($socket == $this->NSfp) {
\r
1349 $this->nsReceive();
\r
1351 $this->sbReceive($socket);
\r
1357 * Switchboard related methods
\r
1361 * Send a request for a switchboard session
\r
1363 * @param string $to Target email for switchboard session
\r
1365 private function reqSBSession($to) {
\r
1366 $this->debug_message("*** Request SB for $to");
\r
1367 $this->ns_writeln("XFR $this->id SB");
\r
1369 // Add to the queue of those waiting for a switchboard session reponse
\r
1370 $this->switchBoardSessions[$to] = array(
\r
1374 'joined' => false,
\r
1375 'offline' => false,
\r
1376 'XFRReqTime' => time()
\r
1378 $this->waitingForXFR[$to] = &$this->switchBoardSessions[$to];
\r
1382 * Following an XFR or RNG, connect to the switchboard session
\r
1384 * @param string $mode Mode, either 'Active' (in the case of XFR) or 'Passive' (in the case of RNG)
\r
1385 * @param string $ip IP of Switchboard
\r
1386 * @param integer $port Port of Switchboard
\r
1387 * @param string $to User on other end of Switchboard
\r
1388 * @param array $param Array of parameters - 'cki', 'ticket', 'sid'
\r
1389 * @return boolean true if successful
\r
1391 private function connectToSBSession($mode, $ip, $port, $to, $param) {
\r
1392 $this->debug_message("*** SB: Trying to connect to switchboard server $ip:$port");
\r
1394 $socket = @fsockopen($ip, $port, $errno, $errstr, $this->timeout);
\r
1396 $this->debug_message("*** SB: Can't connect to $ip:$port, error => $errno, $errstr");
\r
1400 // Store the socket in the lookup array
\r
1401 $this->switchBoardSessionLookup[$to] = $socket;
\r
1403 // Store the socket in the sessions array
\r
1404 $this->switchBoardSessions[$to] = array(
\r
1406 'socket' => $socket,
\r
1408 'joined' => false,
\r
1409 'offline' => false,
\r
1410 'XFRReqTime' => time()
\r
1413 // Change the index of the session to the socket
\r
1414 $intsocket = (int) $socket;
\r
1415 $this->switchBoardSessions[$intsocket] = $this->switchBoardSessions[$to];
\r
1416 unset($this->switchBoardSessions[$to]);
\r
1418 $id = &$this->switchBoardSessions[$intsocket]['id'];
\r
1420 if ($mode == 'Active') {
\r
1421 $cki_code = $param['cki'];
\r
1423 // SB: >>> USR {id} {user} {cki}
\r
1424 $this->sb_writeln($socket, $id, "USR $id $this->user $cki_code");
\r
1427 $ticket = $param['ticket'];
\r
1428 $sid = $param['sid'];
\r
1430 // SB: >>> ANS {id} {user} {ticket} {session_id}
\r
1431 $this->sb_writeln($socket, $id, "ANS $id $this->user $ticket $sid");
\r
1436 * Called when we want to end a switchboard session
\r
1437 * or a switchboard session ends
\r
1439 * @param resource $socket Socket
\r
1440 * @param boolean $killsession Whether to delete the session
\r
1443 private function endSBSession($socket) {
\r
1444 if (!self::socketcheck($socket)) {
\r
1445 $this->sb_writeln($socket, $fake = 0, 'OUT');
\r
1449 // Unset session lookup value
\r
1450 $intsocket = (int) $socket;
\r
1451 unset($this->switchBoardSessionLookup[$this->switchBoardSessions[$intsocket]['to']]);
\r
1453 // Unset session itself
\r
1454 unset($this->switchBoardSessions[$intsocket]);
\r
1458 * Send a message via an existing SB session
\r
1460 * @param string $to Recipient for message
\r
1461 * @param string $message Message
\r
1462 * @return boolean true on success
\r
1464 private function sendMessageViaSB($to, $message) {
\r
1465 $socket = $this->switchBoardSessionLookup[$to];
\r
1466 if (self::socketcheck($socket)) {
\r
1470 $id = &$this->switchBoardSessions[(int) $socket]['id'];
\r
1472 $aMessage = $this->getMessage($message);
\r
1473 // CheckEmotion...
\r
1474 $MsnObjDefine = $this->GetMsnObjDefine($aMessage);
\r
1475 if ($MsnObjDefine !== '') {
\r
1476 $SendString = "MIME-Version: 1.0\r\nContent-Type: text/x-mms-emoticon\r\n\r\n$MsnObjDefine";
\r
1477 $len = strlen($SendString);
\r
1479 if ($this->sb_writeln($socket, $id, "MSG $id N $len") === false ||
\r
1480 $this->sb_writedata($socket, $SendString) === false) {
\r
1484 $len = strlen($aMessage);
\r
1486 if ($this->sb_writeln($socket, $id, "MSG $id N $len") === false ||
\r
1487 $this->sb_writedata($socket, $aMessage) === false) {
\r
1491 // Don't close the SB session, we might as well leave it open
\r
1496 * Send a message to a user on another network
\r
1498 * @param string $to Intended recipient
\r
1499 * @param string $message Message
\r
1500 * @param integer $network Network
\r
1503 private function sendOtherNetworkMessage($to, $message, $network) {
\r
1504 $message = $this->getMessage($message, $network);
\r
1505 $len = strlen($message);
\r
1506 if ($this->ns_writeln("UUM $this->id $to $network 1 $len") === false ||
\r
1507 $this->ns_writedata($Message) === false) {
\r
1510 $this->debug_message("*** Sent to $to (network: $network):\n$Message");
\r
1517 * @param string $to To address in form user@host.com(@network)
\r
1518 * where network is 1 for MSN, 32 for Yahoo
\r
1519 * and 'Offline' for offline messages
\r
1520 * @param string $message Message
\r
1522 public function sendMessage($to, $message) {
\r
1523 if ($message != '') {
\r
1524 $toParts = explode('@', $to);
\r
1525 if(count($toParts) < 3) {
\r
1526 list($name, $host) = $toParts;
\r
1529 list($name, $host, $network) = $toParts;
\r
1532 $recipient = $name.'@'.$host;
\r
1534 if ($network === 1) {
\r
1535 if (!isset($this->switchBoardSessionLookup[$recipient])) {
\r
1536 if (!isset($this->switchBoardSessions[$recipient]) || time() - $this->switchBoardSessions[$recipient]['XFRReqTime'] > $this->XFRReqTimeout) {
\r
1537 $this->debug_message("*** No existing SB session or request has timed out");
\r
1538 $this->reqSBSession($recipient);
\r
1542 $socket = $this->switchBoardSessionLookup[$recipient];
\r
1543 $intsocket = (int) $socket;
\r
1544 if ($this->switchBoardSessions[$intsocket]['offline']) {
\r
1545 $this->debug_message("*** Contact ($recipient) offline, sending OIM");
\r
1546 $this->endSBSession($socket);
\r
1547 return $this->sendMessage($recipient.'@Offline', $message);
\r
1549 if ($this->switchBoardSessions[$intsocket]['joined'] !== true) {
\r
1550 $this->debug_message("*** Recipient has not joined session, returning false");
\r
1554 $this->debug_message("*** Attempting to send message to $recipient using existing SB session");
\r
1556 if ($this->sendMessageViaSB($recipient, $message)) {
\r
1557 $this->debug_message('*** Message sent successfully');
\r
1564 } elseif ($network == 'Offline') {
\r
1566 //FIXME: ä¿®æ£Send OIM
\r
1568 $re_login = false;
\r
1569 for ($i = 0; $i < $this->oim_try; $i++) {
\r
1570 if (($oim_result = $this->sendOIM($recipient, $message, $lockkey)) === true) break;
\r
1571 if (is_array($oim_result) && $oim_result['challenge'] !== false) {
\r
1572 // need challenge lockkey
\r
1573 $this->debug_message("*** Need challenge code for ".$oim_result['challenge']);
\r
1574 $lockkey = $this->getChallenge($oim_result['challenge']);
\r
1577 if ($oim_result === false || $oim_result['auth_policy'] !== false) {
\r
1579 $this->debug_message("*** Can't send OIM, but we already re-logged-in again, so returning false");
\r
1582 $this->debug_message("*** Can't send OIM, maybe ticket expired, trying to login again");
\r
1584 // Maybe we need to re-login again
\r
1585 if (!$this->get_passport_ticket()) {
\r
1586 $this->debug_message("*** Can't re-login, something went wrong here, returning false");
\r
1589 $this->debug_message("*** Getting new ticket and trying again");
\r
1596 return $this->sendOtherNetworkMessage($recipient, $message, $network);
\r
1607 * Get OIM mail data
\r
1609 * @return string mail data or false on failure
\r
1611 function getOIM_maildata() {
\r
1612 preg_match('#t=(.*)&p=(.*)#', $this->ticket['web_ticket'], $matches);
\r
1613 if (count($matches) == 0) {
\r
1614 $this->debug_message('*** No web ticket?');
\r
1617 $t = htmlspecialchars($matches[1]);
\r
1618 $p = htmlspecialchars($matches[2]);
\r
1619 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
1620 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
1621 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
1622 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
\r
1624 <PassportCookie xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1630 <GetMetadata xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi" />
\r
1632 </soap:Envelope>';
\r
1634 $header_array = array(
\r
1635 'SOAPAction: '.self::OIM_MAILDATA_SOAP,
\r
1636 'Content-Type: text/xml; charset=utf-8',
\r
1637 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Messenger '.self::BUILDVER.')'
\r
1640 $this->debug_message('*** URL: '.self::OIM_MAILDATA_URL);
\r
1641 $this->debug_message("*** Sending SOAP:\n$XML");
\r
1642 $curl = curl_init();
\r
1643 curl_setopt($curl, CURLOPT_URL, self::OIM_MAILDATA_URL);
\r
1644 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
1645 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1646 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
1647 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
1648 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1649 curl_setopt($curl, CURLOPT_POST, 1);
\r
1650 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
1651 $data = curl_exec($curl);
\r
1652 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
1653 curl_close($curl);
\r
1654 $this->debug_message("*** Get Result:\n$data");
\r
1656 if ($http_code != 200) {
\r
1657 $this->debug_message("*** Could not get OIM maildata! http code: $http_code");
\r
1661 // <GetMetadataResponse xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">See #XML_Data</GetMetadataResponse>
\r
1662 preg_match('#<GetMetadataResponse([^>]*)>(.*)</GetMetadataResponse>#', $data, $matches);
\r
1663 if (count($matches) == 0) {
\r
1664 $this->debug_message('*** Could not get OIM maildata');
\r
1667 return $matches[2];
\r
1671 * Fetch OIM message with given id
\r
1673 * @param string $msgid
\r
1674 * @return string Message or false on failure
\r
1676 function getOIM_message($msgid) {
\r
1677 preg_match('#t=(.*)&p=(.*)#', $this->ticket['web_ticket'], $matches);
\r
1678 if (count($matches) == 0) {
\r
1679 $this->debug_message('*** No web ticket?');
\r
1682 $t = htmlspecialchars($matches[1]);
\r
1683 $p = htmlspecialchars($matches[2]);
\r
1686 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
1687 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
1688 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
1689 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
\r
1691 <PassportCookie xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1697 <GetMessage xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1698 <messageId>'.$msgid.'</messageId>
\r
1699 <alsoMarkAsRead>false</alsoMarkAsRead>
\r
1702 </soap:Envelope>';
\r
1704 $header_array = array(
\r
1705 'SOAPAction: '.self::OIM_READ_SOAP,
\r
1706 'Content-Type: text/xml; charset=utf-8',
\r
1707 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Messenger '.self::BUILDVER.')'
\r
1710 $this->debug_message('*** URL: '.self::OIM_READ_URL);
\r
1711 $this->debug_message("*** Sending SOAP:\n$XML");
\r
1712 $curl = curl_init();
\r
1713 curl_setopt($curl, CURLOPT_URL, self::OIM_READ_URL);
\r
1714 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
1715 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1716 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
1717 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
1718 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1719 curl_setopt($curl, CURLOPT_POST, 1);
\r
1720 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
1721 $data = curl_exec($curl);
\r
1722 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
1723 curl_close($curl);
\r
1724 $this->debug_message("*** Get Result:\n$data");
\r
1726 if ($http_code != 200) {
\r
1727 $this->debug_message("*** Can't get OIM: $msgid, http code = $http_code");
\r
1731 // why can't use preg_match('#<GetMessageResult>(.*)</GetMessageResult>#', $data, $matches)?
\r
1733 $start = strpos($data, '<GetMessageResult>');
\r
1734 $end = strpos($data, '</GetMessageResult>');
\r
1735 if ($start === false || $end === false || $start > $end) {
\r
1736 $this->debug_message("*** Can't get OIM: $msgid");
\r
1739 $lines = substr($data, $start + 18, $end - $start);
\r
1740 $aLines = @explode("\n", $lines);
\r
1744 foreach ($aLines as $line) {
\r
1745 $line = rtrim($line);
\r
1747 if ($line === '') {
\r
1753 // stop at empty lines
\r
1754 if ($line === '') break;
\r
1757 $sMsg = base64_decode($sOIM);
\r
1758 //$this->debug_message("*** we get OIM ($msgid): $sMsg");
\r
1761 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
1762 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
1763 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
1764 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
\r
1766 <PassportCookie xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1772 <DeleteMessages xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1774 <messageId>'.$msgid.'</messageId>
\r
1778 </soap:Envelope>';
\r
1780 $header_array = array(
\r
1781 'SOAPAction: '.self::OIM_DEL_SOAP,
\r
1782 'Content-Type: text/xml; charset=utf-8',
\r
1783 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Messenger '.self::BUILDVER.')'
\r
1786 $this->debug_message('*** URL: '.self::OIM_DEL_URL);
\r
1787 $this->debug_message("*** Sending SOAP:\n$XML");
\r
1788 $curl = curl_init();
\r
1789 curl_setopt($curl, CURLOPT_URL, self::OIM_DEL_URL);
\r
1790 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
1791 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1792 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
1793 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
1794 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1795 curl_setopt($curl, CURLOPT_POST, 1);
\r
1796 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
1797 $data = curl_exec($curl);
\r
1798 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
1799 curl_close($curl);
\r
1800 $this->debug_message("*** Get Result:\n$data");
\r
1802 if ($http_code != 200)
\r
1803 $this->debug_message("*** Could not delete OIM: $msgid, http code = $http_code");
\r
1805 $this->debug_message("*** OIM ($msgid) deleted");
\r
1810 * Send offline message
\r
1812 * @param string $to Intended recipient
\r
1813 * @param string $sMessage Message
\r
1814 * @param string $lockkey Lock key
\r
1815 * @return mixed true on success or error data
\r
1817 private function sendOIM($to, $sMessage, $lockkey) {
\r
1818 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
1819 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
1820 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
1821 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
\r
1823 <From memberName="'.$this->user.'"
\r
1824 friendlyName="=?utf-8?B?'.base64_encode($this->user).'?="
\r
1827 xmlns="http://messenger.msn.com/ws/2004/09/oim/"
\r
1828 msnpVer="'.self::PROTOCOL.'"
\r
1829 buildVer="'.self::BUILDVER.'"/>
\r
1830 <To memberName="'.$to.'" xmlns="http://messenger.msn.com/ws/2004/09/oim/"/>
\r
1831 <Ticket passport="'.htmlspecialchars($this->ticket['oim_ticket']).'"
\r
1832 appid="'.self::PROD_ID.'"
\r
1833 lockkey="'.$lockkey.'"
\r
1834 xmlns="http://messenger.msn.com/ws/2004/09/oim/"/>
\r
1835 <Sequence xmlns="http://schemas.xmlsoap.org/ws/2003/03/rm">
\r
1836 <Identifier xmlns="http://schemas.xmlsoap.org/ws/2002/07/utility">http://messenger.msn.com</Identifier>
\r
1837 <MessageNumber>1</MessageNumber>
\r
1841 <MessageType xmlns="http://messenger.msn.com/ws/2004/09/oim/">text</MessageType>
\r
1842 <Content xmlns="http://messenger.msn.com/ws/2004/09/oim/">MIME-Version: 1.0
\r
1843 Content-Type: text/plain; charset=UTF-8
\r
1844 Content-Transfer-Encoding: base64
\r
1845 X-OIM-Message-Type: OfflineMessage
\r
1846 X-OIM-Run-Id: {DAB68CFA-38C9-449B-945E-38AFA51E50A7}
\r
1847 X-OIM-Sequence-Num: 1
\r
1849 '.chunk_split(base64_encode($sMessage)).'
\r
1852 </soap:Envelope>';
\r
1854 $header_array = array(
\r
1855 'SOAPAction: '.self::OIM_SEND_SOAP,
\r
1856 'Content-Type: text/xml',
\r
1857 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Messenger '.self::BUILDVER.')'
\r
1860 $this->debug_message('*** URL: '.self::OIM_SEND_URL);
\r
1861 $this->debug_message("*** Sending SOAP:\n$XML");
\r
1862 $curl = curl_init();
\r
1863 curl_setopt($curl, CURLOPT_URL, self::OIM_SEND_URL);
\r
1864 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
1865 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1866 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
1867 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
1868 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1869 curl_setopt($curl, CURLOPT_POST, 1);
\r
1870 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
1871 $data = curl_exec($curl);
\r
1872 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
1873 curl_close($curl);
\r
1874 $this->debug_message("*** Get Result:\n$data");
\r
1876 if ($http_code == 200) {
\r
1877 $this->debug_message("*** OIM sent for $to");
\r
1881 $challenge = false;
\r
1882 $auth_policy = false;
\r
1883 // the lockkey is invalid, authenticated fail, we need challenge it again
\r
1884 // <LockKeyChallenge xmlns="http://messenger.msn.com/ws/2004/09/oim/">364763969</LockKeyChallenge>
\r
1885 preg_match("#<LockKeyChallenge (.*)>(.*)</LockKeyChallenge>#", $data, $matches);
\r
1886 if (count($matches) != 0) {
\r
1887 // yes, we get new LockKeyChallenge
\r
1888 $challenge = $matches[2];
\r
1889 $this->debug_message("*** OIM need new challenge ($challenge) for $to");
\r
1891 // auth policy error
\r
1892 // <RequiredAuthPolicy xmlns="http://messenger.msn.com/ws/2004/09/oim/">MBI_SSL</RequiredAuthPolicy>
\r
1893 preg_match("#<RequiredAuthPolicy (.*)>(.*)</RequiredAuthPolicy>#", $data, $matches);
\r
1894 if (count($matches) != 0) {
\r
1895 $auth_policy = $matches[2];
\r
1896 $this->debug_message("*** OIM need new auth policy ($auth_policy) for $to");
\r
1898 if ($auth_policy === false && $challenge === false) {
\r
1899 //<faultcode xmlns:q0="http://messenger.msn.com/ws/2004/09/oim/">q0:AuthenticationFailed</faultcode>
\r
1900 preg_match("#<faultcode (.*)>(.*)</faultcode>#", $data, $matches);
\r
1901 if (count($matches) == 0) {
\r
1902 // no error, we assume the OIM is sent
\r
1903 $this->debug_message("*** OIM sent for $to");
\r
1906 $err_code = $matches[2];
\r
1907 //<faultstring>Exception of type 'System.Web.Services.Protocols.SoapException' was thrown.</faultstring>
\r
1908 preg_match("#<faultstring>(.*)</faultstring>#", $data, $matches);
\r
1909 if (count($matches) > 0)
\r
1910 $err_msg = $matches[1];
\r
1913 $this->debug_message("*** OIM failed for $to");
\r
1914 $this->debug_message("*** OIM Error code: $err_code");
\r
1915 $this->debug_message("*** OIM Error Message: $err_msg");
\r
1918 return array('challenge' => $challenge, 'auth_policy' => $auth_policy);
\r
1922 * Contact / Membership list methods
\r
1926 * Fetch contact list
\r
1928 * @return boolean true on success
\r
1930 private function UpdateContacts() {
\r
1931 $ABApplicationHeaderArray = array(
\r
1932 'ABApplicationHeader' => array(
\r
1933 ':' => array('xmlns' => 'http://www.msn.com/webservices/AddressBook'),
\r
1934 'ApplicationId' => 'CFE80F9D-180F-4399-82AB-413F33A1FA11',
\r
1935 'IsMigration' => false,
\r
1936 'PartnerScenario' => 'ContactSave'
\r
1940 $ABApplicationHeader = new SoapHeader('http://www.msn.com/webservices/AddressBook', 'ABApplicationHeader', $this->Array2SoapVar($ABApplicationHeaderArray));
\r
1941 $ABFindAllArray = array(
\r
1942 'ABFindAll' => array(
\r
1943 ':' => array('xmlns'=>'http://www.msn.com/webservices/AddressBook'),
\r
1944 'abId' => '00000000-0000-0000-0000-000000000000',
\r
1945 'abView' => 'Full',
\r
1946 'lastChange' => '0001-01-01T00:00:00.0000000-08:00',
\r
1949 $ABFindAll = new SoapParam($this->Array2SoapVar($ABFindAllArray), 'ABFindAll');
\r
1950 $this->ABService->__setSoapHeaders(array($ABApplicationHeader, $this->ABAuthHeader));
\r
1951 $this->Contacts = array();
\r
1953 $this->debug_message('*** Updating Contacts...');
\r
1954 $Result = $this->ABService->ABFindAll($ABFindAll);
\r
1955 $this->debug_message("*** Result:\n".print_r($Result, true)."\n".$this->ABService->__getLastResponse());
\r
1956 foreach($Result->ABFindAllResult->contacts->Contact as $Contact)
\r
1957 $this->Contacts[$Contact->contactInfo->passportName] = $Contact;
\r
1958 } catch(Exception $e) {
\r
1959 $this->debug_message("*** Update Contacts Error \nRequest:".$this->ABService->__getLastRequest()."\nError:".$e->getMessage());
\r
1968 * @param string $email
\r
1969 * @param integer $network
\r
1970 * @param string $display
\r
1971 * @param boolean $sendADL
\r
1972 * @return boolean true on success
\r
1974 private function addContact($email, $network, $display = '', $sendADL = false) {
\r
1975 if ($network != 1) return true;
\r
1976 if (isset($this->Contacts[$email])) return true;
\r
1978 $ABContactAddArray = array(
\r
1979 'ABContactAdd' => array(
\r
1980 ':' => array('xmlns' => 'http://www.msn.com/webservices/AddressBook'),
\r
1981 'abId' => '00000000-0000-0000-0000-000000000000',
\r
1982 'contacts' => array(
\r
1983 'Contact' => array(
\r
1984 ':' => array('xmlns' => 'http://www.msn.com/webservices/AddressBook'),
\r
1985 'contactInfo' => array(
\r
1986 'contactType' => 'LivePending',
\r
1987 'passportName' => $email,
\r
1988 'isMessengerUser' => true,
\r
1989 'MessengerMemberInfo' => array(
\r
1990 'DisplayName' => $email
\r
1995 'options' => array(
\r
1996 'EnableAllowListManagement' => true
\r
2000 $ABContactAdd = new SoapParam($this->Array2SoapVar($ABContactAddArray), 'ABContactAdd');
\r
2002 $this->debug_message("*** Adding Contact $email...");
\r
2003 $this->ABService->ABContactAdd($ABContactAdd);
\r
2004 } catch(Exception $e) {
\r
2005 $this->debug_message("*** Add Contact Error \nRequest:".$this->ABService->__getLastRequest()."\nError:".$e->getMessage());
\r
2008 if ($sendADL && !feof($this->NSfp)) {
\r
2009 @list($u_name, $u_domain) = @explode('@', $email);
\r
2010 foreach (array('1', '2') as $l) {
\r
2011 $str = '<ml l="1"><d n="'.$u_domain.'"><c n="'.$u_name.'" l="'.$l.'" t="'.$network.'" /></d></ml>';
\r
2012 $len = strlen($str);
\r
2013 // NS: >>> ADL {id} {size}
\r
2014 $this->ns_writeln("ADL $this->id $len");
\r
2015 $this->ns_writedata($str);
\r
2018 $this->UpdateContacts();
\r
2023 * Remove contact from list
\r
2025 * @param integer $memberID
\r
2026 * @param string $email
\r
2027 * @param integer $network
\r
2028 * @param string $list
\r
2030 function delMemberFromList($memberID, $email, $network, $list) {
\r
2031 if ($network != 1 && $network != 32) return true;
\r
2032 if ($memberID === false) return true;
\r
2034 $ticket = htmlspecialchars($this->ticket['contact_ticket']);
\r
2035 if ($network == 1)
\r
2036 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2037 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2038 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2039 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2040 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2042 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2043 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2044 <IsMigration>false</IsMigration>
\r
2045 <PartnerScenario>ContactMsgrAPI</PartnerScenario>
\r
2046 </ABApplicationHeader>
\r
2047 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2048 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2049 <TicketToken>'.$ticket.'</TicketToken>
\r
2053 <DeleteMember xmlns="http://www.msn.com/webservices/AddressBook">
\r
2056 <Type>Messenger</Type>
\r
2057 <ForeignId></ForeignId>
\r
2061 <MemberRole>'.$list.'</MemberRole>
\r
2063 <Member xsi:type="PassportMember" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
\r
2064 <Type>Passport</Type>
\r
2065 <MembershipId>'.$memberID.'</MembershipId>
\r
2066 <State>Accepted</State>
\r
2073 </soap:Envelope>';
\r
2075 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2076 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2077 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2078 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2079 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2081 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2082 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2083 <IsMigration>false</IsMigration>
\r
2084 <PartnerScenario>ContactMsgrAPI</PartnerScenario>
\r
2085 </ABApplicationHeader>
\r
2086 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2087 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2088 <TicketToken>'.$ticket.'</TicketToken>
\r
2092 <DeleteMember xmlns="http://www.msn.com/webservices/AddressBook">
\r
2095 <Type>Messenger</Type>
\r
2096 <ForeignId></ForeignId>
\r
2100 <MemberRole>'.$list.'</MemberRole>
\r
2102 <Member xsi:type="EmailMember" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
\r
2103 <Type>Email</Type>
\r
2104 <MembershipId>'.$memberID.'</MembershipId>
\r
2105 <State>Accepted</State>
\r
2112 </soap:Envelope>';
\r
2114 $header_array = array(
\r
2115 'SOAPAction: '.self::DELMEMBER_SOAP,
\r
2116 'Content-Type: text/xml; charset=utf-8',
\r
2117 'User-Agent: MSN Explorer/9.0 (MSN 8.0; TmstmpExt)'
\r
2120 $this->debug_message('*** URL: '.self::DELMEMBER_URL);
\r
2121 $this->debug_message("*** Sending SOAP:\n$XML");
\r
2122 $curl = curl_init();
\r
2123 curl_setopt($curl, CURLOPT_URL, self::DELMEMBER_URL);
\r
2124 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
2125 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
2126 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
2127 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
2128 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
2129 curl_setopt($curl, CURLOPT_POST, 1);
\r
2130 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
2131 $data = curl_exec($curl);
\r
2132 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
2133 curl_close($curl);
\r
2134 $this->debug_message("*** Get Result:\n$data");
\r
2136 if ($http_code != 200) {
\r
2137 preg_match('#<faultcode>(.*)</faultcode><faultstring>(.*)</faultstring>#', $data, $matches);
\r
2138 if (count($matches) == 0) {
\r
2139 $this->debug_message("*** Could not delete member (network: $network) $email ($memberID) from $list list");
\r
2142 $faultcode = trim($matches[1]);
\r
2143 $faultstring = trim($matches[2]);
\r
2144 if (strcasecmp($faultcode, 'soap:Client') || stripos($faultstring, 'Member does not exist') === false) {
\r
2145 $this->debug_message("*** Could not delete member (network: $network) $email ($memberID) from $list list, error code: $faultcode, $faultstring");
\r
2148 $this->debug_message("*** Could not delete member (network: $network) $email ($memberID) from $list list, not present in list");
\r
2151 $this->debug_message("*** Member successfully deleted (network: $network) $email ($memberID) from $list list");
\r
2156 * Add contact to list
\r
2158 * @param string $email
\r
2159 * @param integer $network
\r
2160 * @param string $list
\r
2162 function addMemberToList($email, $network, $list) {
\r
2163 if ($network != 1 && $network != 32) return true;
\r
2164 $ticket = htmlspecialchars($this->ticket['contact_ticket']);
\r
2167 if ($network == 1)
\r
2168 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2169 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2170 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2171 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2172 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2174 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2175 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2176 <IsMigration>false</IsMigration>
\r
2177 <PartnerScenario>ContactMsgrAPI</PartnerScenario>
\r
2178 </ABApplicationHeader>
\r
2179 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2180 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2181 <TicketToken>'.$ticket.'</TicketToken>
\r
2185 <AddMember xmlns="http://www.msn.com/webservices/AddressBook">
\r
2188 <Type>Messenger</Type>
\r
2189 <ForeignId></ForeignId>
\r
2193 <MemberRole>'.$list.'</MemberRole>
\r
2195 <Member xsi:type="PassportMember" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
\r
2196 <Type>Passport</Type>
\r
2197 <State>Accepted</State>
\r
2198 <PassportName>'.$user.'</PassportName>
\r
2205 </soap:Envelope>';
\r
2207 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2208 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2209 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2210 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2211 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2213 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2214 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2215 <IsMigration>false</IsMigration>
\r
2216 <PartnerScenario>ContactMsgrAPI</PartnerScenario>
\r
2217 </ABApplicationHeader>
\r
2218 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2219 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2220 <TicketToken>'.$ticket.'</TicketToken>
\r
2224 <AddMember xmlns="http://www.msn.com/webservices/AddressBook">
\r
2227 <Type>Messenger</Type>
\r
2228 <ForeignId></ForeignId>
\r
2232 <MemberRole>'.$list.'</MemberRole>
\r
2234 <Member xsi:type="EmailMember" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
\r
2235 <Type>Email</Type>
\r
2236 <State>Accepted</State>
\r
2237 <Email>'.$user.'</Email>
\r
2240 <Name>MSN.IM.BuddyType</Name>
\r
2241 <Value>32:YAHOO</Value>
\r
2250 </soap:Envelope>';
\r
2251 $header_array = array(
\r
2252 'SOAPAction: '.self::ADDMEMBER_SOAP,
\r
2253 'Content-Type: text/xml; charset=utf-8',
\r
2254 'User-Agent: MSN Explorer/9.0 (MSN 8.0; TmstmpExt)'
\r
2257 $this->debug_message('*** URL: '.self::ADDMEMBER_URL);
\r
2258 $this->debug_message("*** Sending SOAP:\n$XML");
\r
2259 $curl = curl_init();
\r
2260 curl_setopt($curl, CURLOPT_URL, self::ADDMEMBER_URL);
\r
2261 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
2262 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
2263 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
2264 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
2265 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
2266 curl_setopt($curl, CURLOPT_POST, 1);
\r
2267 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
2268 $data = curl_exec($curl);
\r
2269 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
2270 curl_close($curl);
\r
2271 $this->debug_message("*** Get Result:\n$data");
\r
2273 if ($http_code != 200) {
\r
2274 preg_match('#<faultcode>(.*)</faultcode><faultstring>(.*)</faultstring>#', $data, $matches);
\r
2275 if (count($matches) == 0) {
\r
2276 $this->debug_message("*** Could not add member (network: $network) $email to $list list");
\r
2279 $faultcode = trim($matches[1]);
\r
2280 $faultstring = trim($matches[2]);
\r
2281 if (strcasecmp($faultcode, 'soap:Client') || stripos($faultstring, 'Member already exists') === false) {
\r
2282 $this->debug_message("*** Could not add member (network: $network) $email to $list list, error code: $faultcode, $faultstring");
\r
2285 $this->debug_message("*** Could not add member (network: $network) $email to $list list, already present");
\r
2288 $this->debug_message("*** Member successfully added (network: $network) $email to $list list");
\r
2293 * Get membership lists
\r
2295 * @param mixed $returnData Membership list or false on failure
\r
2297 function getMembershipList($returnData = false) {
\r
2298 $ticket = htmlspecialchars($this->ticket['contact_ticket']);
\r
2299 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2300 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2301 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2302 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2303 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2305 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2306 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2307 <IsMigration>false</IsMigration>
\r
2308 <PartnerScenario>Initial</PartnerScenario>
\r
2309 </ABApplicationHeader>
\r
2310 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2311 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2312 <TicketToken>'.$ticket.'</TicketToken>
\r
2316 <FindMembership xmlns="http://www.msn.com/webservices/AddressBook">
\r
2319 <ServiceType>Messenger</ServiceType>
\r
2320 <ServiceType>Invitation</ServiceType>
\r
2321 <ServiceType>SocialNetwork</ServiceType>
\r
2322 <ServiceType>Space</ServiceType>
\r
2323 <ServiceType>Profile</ServiceType>
\r
2328 </soap:Envelope>';
\r
2329 $header_array = array(
\r
2330 'SOAPAction: '.self::MEMBERSHIP_SOAP,
\r
2331 'Content-Type: text/xml; charset=utf-8',
\r
2332 'User-Agent: MSN Explorer/9.0 (MSN 8.0; TmstmpExt)'
\r
2334 $this->debug_message('*** URL: '.self::MEMBERSHIP_URL);
\r
2335 $this->debug_message("*** Sending SOAP:\n$XML");
\r
2336 $curl = curl_init();
\r
2337 curl_setopt($curl, CURLOPT_URL, self::MEMBERSHIP_URL);
\r
2338 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
2339 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
2340 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
2341 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
2342 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
2343 curl_setopt($curl, CURLOPT_POST, 1);
\r
2344 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
2345 $data = curl_exec($curl);
\r
2346 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
2347 curl_close($curl);
\r
2348 $this->debug_message("*** Get Result:\n$data");
\r
2350 if ($http_code != 200) return false;
\r
2352 $aMemberships = array();
\r
2354 //$this->debug_message("search p = $p");
\r
2355 $start = strpos($p, '<Membership>');
\r
2356 $end = strpos($p, '</Membership>');
\r
2357 if ($start === false || $end === false || $start > $end) break;
\r
2358 //$this->debug_message("start = $start, end = $end");
\r
2360 $sMembership = substr($p, $start, $end - $start);
\r
2361 $aMemberships[] = $sMembership;
\r
2362 //$this->debug_message("add sMembership = $sMembership");
\r
2363 $p = substr($p, $end);
\r
2365 //$this->debug_message("aMemberships = ".var_export($aMemberships, true));
\r
2367 $aContactList = array();
\r
2368 foreach ($aMemberships as $sMembership) {
\r
2369 //$this->debug_message("sMembership = $sMembership");
\r
2370 if (isset($matches)) unset($matches);
\r
2371 preg_match('#<MemberRole>(.*)</MemberRole>#', $sMembership, $matches);
\r
2372 if (count($matches) == 0) continue;
\r
2373 $sMemberRole = $matches[1];
\r
2374 //$this->debug_message("MemberRole = $sMemberRole");
\r
2375 if ($sMemberRole != 'Allow' && $sMemberRole != 'Reverse' && $sMemberRole != 'Pending') continue;
\r
2376 $p = $sMembership;
\r
2377 if (isset($aMembers)) unset($aMembers);
\r
2378 $aMembers = array();
\r
2380 //$this->debug_message("search p = $p");
\r
2381 $start = strpos($p, '<Member xsi:type="');
\r
2382 $end = strpos($p, '</Member>');
\r
2383 if ($start === false || $end === false || $start > $end) break;
\r
2384 //$this->debug_message("start = $start, end = $end");
\r
2386 $sMember = substr($p, $start, $end - $start);
\r
2387 $aMembers[] = $sMember;
\r
2388 //$this->debug_message("add sMember = $sMember");
\r
2389 $p = substr($p, $end);
\r
2391 //$this->debug_message("aMembers = ".var_export($aMembers, true));
\r
2392 foreach ($aMembers as $sMember) {
\r
2393 //$this->debug_message("sMember = $sMember");
\r
2394 if (isset($matches)) unset($matches);
\r
2395 preg_match('#<Member xsi\:type="([^"]*)">#', $sMember, $matches);
\r
2396 if (count($matches) == 0) continue;
\r
2397 $sMemberType = $matches[1];
\r
2398 //$this->debug_message("MemberType = $sMemberType");
\r
2400 preg_match('#<MembershipId>(.*)</MembershipId>#', $sMember, $matches);
\r
2401 if (count($matches) == 0) continue;
\r
2402 $id = $matches[1];
\r
2403 if ($sMemberType == 'PassportMember') {
\r
2404 if (strpos($sMember, '<Type>Passport</Type>') === false) continue;
\r
2406 preg_match('#<PassportName>(.*)</PassportName>#', $sMember, $matches);
\r
2408 else if ($sMemberType == 'EmailMember') {
\r
2409 if (strpos($sMember, '<Type>Email</Type>') === false) continue;
\r
2410 // Value is 32: or 32:YAHOO
\r
2411 preg_match('#<Annotation><Name>MSN.IM.BuddyType</Name><Value>(.*):(.*)</Value></Annotation>#', $sMember, $matches);
\r
2412 if (count($matches) == 0) continue;
\r
2413 if ($matches[1] != 32) continue;
\r
2415 preg_match('#<Email>(.*)</Email>#', $sMember, $matches);
\r
2417 if ($network == -1) continue;
\r
2418 if (count($matches) > 0) {
\r
2419 $email = $matches[1];
\r
2420 @list($u_name, $u_domain) = @explode('@', $email);
\r
2421 if ($u_domain == NULL) continue;
\r
2422 $aContactList[$u_domain][$u_name][$network][$sMemberRole] = $id;
\r
2423 $this->debug_message("*** Adding new contact (network: $network, status: $sMemberRole): $u_name@$u_domain ($id)");
\r
2427 return $aContactList;
\r
2431 * MsnObj related methods
\r
2436 * @param $FilePath 圖檔路徑
\r
2437 * @param $Type 檔案類型 3=>大é è²¼,2表情圖案
\r
2440 private function MsnObj($FilePath, $Type = 3) {
\r
2441 if (!($FileSize=filesize($FilePath))) return '';
\r
2442 $Location = md5($FilePath);
\r
2443 $Friendly = md5($FilePath.$Type);
\r
2444 if (isset($this->MsnObjMap[$Location])) return $this->MsnObjMap[$Location];
\r
2445 $sha1d = base64_encode(sha1(file_get_contents($FilePath), true));
\r
2446 $sha1c = base64_encode(sha1("Creator".$this->user."Size$FileSize"."Type$Type"."Location$Location"."Friendly".$Friendly."SHA1D$sha1d", true));
\r
2447 $this->MsnObjArray[$Location] = $FilePath;
\r
2448 $MsnObj = '<msnobj Creator="'.$this->user.'" Size="'.$FileSize.'" Type="'.$Type.'" Location="'.$Location.'" Friendly="'.$Friendly.'" SHA1D="'.$sha1d.'" SHA1C="'.$sha1c.'"/>';
\r
2449 $this->MsnObjMap[$Location] = $MsnObj;
\r
2450 $this->debug_message("*** p2p: addMsnObj $FilePath::$MsnObj\n");
\r
2454 private function GetPictureFilePath($Context) {
\r
2455 $MsnObj = base64_decode($Context);
\r
2456 if (preg_match('/location="(.*?)"/i', $MsnObj, $Match))
\r
2457 $location = $Match[1];
\r
2458 $this->debug_message("*** p2p: PictureFile[$location] ::All".print_r($this->MsnObjArray,true)."\n");
\r
2459 if ($location && isset($this->MsnObjArray[$location]))
\r
2460 return $this->MsnObjArray[$location];
\r
2464 private function GetMsnObjDefine($Message) {
\r
2465 $DefineString = '';
\r
2466 if (is_array($this->Emotions))
\r
2467 foreach ($this->Emotions as $Pattern => $FilePath) {
\r
2468 if (strpos($Message, $Pattern) !== false)
\r
2469 $DefineString .= "$Pattern\t".$this->MsnObj($FilePath, 2)."\t";
\r
2471 return $DefineString;
\r
2479 * Read data of specified size from NS socket
\r
2481 * @param integer $size Size to read
\r
2482 * @return string Data read
\r
2484 private function ns_readdata($size) {
\r
2487 while (!feof($this->NSfp)) {
\r
2488 $buf = @fread($this->NSfp, $size - $count);
\r
2490 $count += strlen($buf);
\r
2491 if ($count >= $size) break;
\r
2493 $this->debug_message("NS: data ($size/$count) <<<\n$data");
\r
2498 * Read line from the NS socket
\r
2500 * @return string Data read
\r
2502 private function ns_readln() {
\r
2503 $data = @fgets($this->NSfp, 4096);
\r
2504 if ($data !== false) {
\r
2505 $data = trim($data);
\r
2506 $this->debug_message("NS: <<< $data");
\r
2512 * Write line to NS socket
\r
2514 * Also increments id
\r
2516 * @param string $data Line to write to socket
\r
2517 * @return mixed Bytes written or false on failure
\r
2519 private function ns_writeln($data) {
\r
2520 $result = @fwrite($this->NSfp, $data."\r\n");
\r
2521 if ($result !== false) {
\r
2522 $this->debug_message("NS: >>> $data");
\r
2529 * Write data to NS socket
\r
2531 * @param string $data Data to write to socket
\r
2532 * @return mixed Bytes written or false on failure
\r
2534 private function ns_writedata($data) {
\r
2535 $result = @fwrite($this->NSfp, $data);
\r
2536 if ($result !== false) {
\r
2537 $this->debug_message("NS: >>> $data");
\r
2543 * Read data of specified size from given SB socket
\r
2545 * @param resource $socket SB socket
\r
2546 * @param integer $size Size to read
\r
2547 * @return string Data read
\r
2549 private function sb_readdata($socket, $size) {
\r
2552 while (!feof($socket)) {
\r
2553 $buf = @fread($socket, $size - $count);
\r
2555 $count += strlen($buf);
\r
2556 if ($count >= $size) break;
\r
2558 $this->debug_message("SB: data ($size/$count) <<<\n$data");
\r
2563 * Read line from given SB socket
\r
2565 * @param resource $socket SB Socket
\r
2566 * @return string Line read
\r
2568 private function sb_readln($socket) {
\r
2569 $data = @fgets($socket, 4096);
\r
2570 if ($data !== false) {
\r
2571 $data = trim($data);
\r
2572 $this->debug_message("SB: <<< $data");
\r
2578 * Write line to given SB socket
\r
2580 * Also increments id
\r
2582 * @param resource $socket SB socket
\r
2583 * @param integer $id Reference to SB id
\r
2584 * @param string $data Line to write
\r
2585 * @return mixed Bytes written or false on error
\r
2587 private function sb_writeln($socket, &$id, $data) {
\r
2588 $result = @fwrite($socket, $data."\r\n");
\r
2589 if ($result !== false) {
\r
2590 $this->debug_message("SB: >>> $data");
\r
2597 * Write data to given SB socket
\r
2599 * @param resource $socket SB socket
\r
2600 * @param $data Data to write to socket
\r
2601 * @return mixed Bytes written or false on error
\r
2603 private function sb_writedata($socket, $data) {
\r
2604 $result = @fwrite($socket, $data);
\r
2605 if ($result !== false) {
\r
2606 $this->debug_message("SB: >>> $data");
\r
2612 * Get all the sockets currently in use
\r
2614 * @return array Array of socket resources
\r
2616 public function getSockets() {
\r
2617 return array_merge(array($this->NSfp), $this->switchBoardSessionLookup);
\r
2621 * Checks socket for end of file
\r
2623 * @param resource $socket Socket to check
\r
2624 * @return boolean true if end of file (socket)
\r
2626 private static function socketcheck($socket){
\r
2627 $info = stream_get_meta_data($socket);
\r
2628 return $info['eof'];
\r
2632 * Key generation methods
\r
2635 private function derive_key($key, $magic) {
\r
2636 $hash1 = mhash(MHASH_SHA1, $magic, $key);
\r
2637 $hash2 = mhash(MHASH_SHA1, $hash1.$magic, $key);
\r
2638 $hash3 = mhash(MHASH_SHA1, $hash1, $key);
\r
2639 $hash4 = mhash(MHASH_SHA1, $hash3.$magic, $key);
\r
2640 return $hash2.substr($hash4, 0, 4);
\r
2643 private function generateLoginBLOB($key, $challenge) {
\r
2644 $key1 = base64_decode($key);
\r
2645 $key2 = $this->derive_key($key1, 'WS-SecureConversationSESSION KEY HASH');
\r
2646 $key3 = $this->derive_key($key1, 'WS-SecureConversationSESSION KEY ENCRYPTION');
\r
2648 // get hash of challenge using key2
\r
2649 $hash = mhash(MHASH_SHA1, $challenge, $key2);
\r
2651 // get 8 bytes random data
\r
2652 $iv = substr(base64_encode(rand(1000,9999).rand(1000,9999)), 2, 8);
\r
2654 $cipher = mcrypt_cbc(MCRYPT_3DES, $key3, $challenge."\x08\x08\x08\x08\x08\x08\x08\x08", MCRYPT_ENCRYPT, $iv);
\r
2656 $blob = pack('LLLLLLL', 28, 1, 0x6603, 0x8004, 8, 20, 72);
\r
2661 return base64_encode($blob);
\r
2665 * Generate challenge response
\r
2667 * @param string $code
\r
2668 * @return string challenge response code
\r
2670 private function getChallenge($code) {
\r
2672 // http://msnpiki.msnfanatic.com/index.php/MSNP11:Challenges
\r
2673 // Step 1: The MD5 Hash
\r
2674 $md5Hash = md5($code.self::PROD_KEY);
\r
2675 $aMD5 = @explode("\0", chunk_split($md5Hash, 8, "\0"));
\r
2676 for ($i = 0; $i < 4; $i++) {
\r
2677 $aMD5[$i] = implode('', array_reverse(@explode("\0", chunk_split($aMD5[$i], 2, "\0"))));
\r
2678 $aMD5[$i] = (0 + base_convert($aMD5[$i], 16, 10)) & 0x7FFFFFFF;
\r
2681 // Step 2: A new string
\r
2682 $chl_id = $code.self::PROD_ID;
\r
2683 $chl_id .= str_repeat('0', 8 - (strlen($chl_id) % 8));
\r
2685 $aID = @explode("\0", substr(chunk_split($chl_id, 4, "\0"), 0, -1));
\r
2686 for ($i = 0; $i < count($aID); $i++) {
\r
2687 $aID[$i] = implode('', array_reverse(@explode("\0", chunk_split($aID[$i], 1, "\0"))));
\r
2688 $aID[$i] = 0 + base_convert(bin2hex($aID[$i]), 16, 10);
\r
2691 // Step 3: The 64 bit key
\r
2692 $magic_num = 0x0E79A9C1;
\r
2693 $str7f = 0x7FFFFFFF;
\r
2696 for ($i = 0; $i < count($aID); $i += 2) {
\r
2698 $temp = bcmod(bcmul($magic_num, $temp), $str7f);
\r
2699 $temp = bcadd($temp, $high);
\r
2700 $temp = bcadd(bcmul($aMD5[0], $temp), $aMD5[1]);
\r
2701 $temp = bcmod($temp, $str7f);
\r
2703 $high = $aID[$i+1];
\r
2704 $high = bcmod(bcadd($high, $temp), $str7f);
\r
2705 $high = bcadd(bcmul($aMD5[2], $high), $aMD5[3]);
\r
2706 $high = bcmod($high, $str7f);
\r
2708 $low = bcadd(bcadd($low, $high), $temp);
\r
2711 $high = bcmod(bcadd($high, $aMD5[1]), $str7f);
\r
2712 $low = bcmod(bcadd($low, $aMD5[3]), $str7f);
\r
2714 $new_high = bcmul($high & 0xFF, 0x1000000);
\r
2715 $new_high = bcadd($new_high, bcmul($high & 0xFF00, 0x100));
\r
2716 $new_high = bcadd($new_high, bcdiv($high & 0xFF0000, 0x100));
\r
2717 $new_high = bcadd($new_high, bcdiv($high & 0xFF000000, 0x1000000));
\r
2718 // we need integer here
\r
2719 $high = 0+$new_high;
\r
2721 $new_low = bcmul($low & 0xFF, 0x1000000);
\r
2722 $new_low = bcadd($new_low, bcmul($low & 0xFF00, 0x100));
\r
2723 $new_low = bcadd($new_low, bcdiv($low & 0xFF0000, 0x100));
\r
2724 $new_low = bcadd($new_low, bcdiv($low & 0xFF000000, 0x1000000));
\r
2725 // we need integer here
\r
2726 $low = 0+$new_low;
\r
2728 // we just use 32 bits integer, don't need the key, just high/low
\r
2729 // $key = bcadd(bcmul($high, 0x100000000), $low);
\r
2731 // Step 4: Using the key
\r
2732 $md5Hash = md5($code.self::PROD_KEY);
\r
2733 $aHash = @explode("\0", chunk_split($md5Hash, 8, "\0"));
\r
2736 $hash .= sprintf("%08x", (0 + base_convert($aHash[0], 16, 10)) ^ $high);
\r
2737 $hash .= sprintf("%08x", (0 + base_convert($aHash[1], 16, 10)) ^ $low);
\r
2738 $hash .= sprintf("%08x", (0 + base_convert($aHash[2], 16, 10)) ^ $high);
\r
2739 $hash .= sprintf("%08x", (0 + base_convert($aHash[3], 16, 10)) ^ $low);
\r
2748 private function Array2SoapVar($Array, $ReturnSoapVarObj = true, $TypeName = null, $TypeNameSpace = null) {
\r
2749 $ArrayString = '';
\r
2750 foreach($Array as $Key => $Val) {
\r
2751 if ($Key{0} == ':') continue;
\r
2753 if (is_array($Val[':'])) {
\r
2754 foreach ($Val[':'] as $AttribName => $AttribVal)
\r
2755 $Attrib .= " $AttribName = '$AttribVal'";
\r
2757 if ($Key{0} == '!') {
\r
2758 //List Type Define
\r
2759 $Key = substr($Key,1);
\r
2760 foreach ($Val as $ListKey => $ListVal) {
\r
2761 if ($ListKey{0} == ':') continue;
\r
2762 if (is_array($ListVal)) $ListVal = $this->Array2SoapVar($ListVal, false);
\r
2763 elseif (is_bool($ListVal)) $ListVal = $ListVal ? 'true' : 'false';
\r
2764 $ArrayString .= "<$Key$Attrib>$ListVal</$Key>";
\r
2768 if (is_array($Val)) $Val = $this->Array2SoapVar($Val, false);
\r
2769 elseif (is_bool($Val)) $Val = $Val ? 'true' : 'false';
\r
2770 $ArrayString .= "<$Key$Attrib>$Val</$Key>";
\r
2772 if ($ReturnSoapVarObj) return new SoapVar($ArrayString, XSD_ANYXML, $TypeName, $TypeNameSpace);
\r
2773 return $ArrayString;
\r
2776 private function linetoArray($lines) {
\r
2777 $lines = str_replace("\r", '', $lines);
\r
2778 $lines = explode("\n", $lines);
\r
2779 foreach ($lines as $line) {
\r
2780 if (!isset($line{3})) continue;
\r
2781 list($Key, $Val) = explode(':', $line);
\r
2782 $Data[trim($Key)] = trim($Val);
\r
2788 * Get Passport ticket
\r
2790 * @param string $url URL string (Optional)
\r
2791 * @return mixed Array of tickets or false on failure
\r
2793 private function get_passport_ticket($url = '') {
\r
2794 $user = $this->user;
\r
2795 $password = htmlspecialchars($this->password);
\r
2798 $passport_url = self::PASSPORT_URL;
\r
2800 $passport_url = $url;
\r
2802 $XML = '<?xml version="1.0" encoding="UTF-8"?>
\r
2803 <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"
\r
2804 xmlns:wsse="http://schemas.xmlsoap.org/ws/2003/06/secext"
\r
2805 xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"
\r
2806 xmlns:wsp="http://schemas.xmlsoap.org/ws/2002/12/policy"
\r
2807 xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
\r
2808 xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/03/addressing"
\r
2809 xmlns:wssc="http://schemas.xmlsoap.org/ws/2004/04/sc"
\r
2810 xmlns:wst="http://schemas.xmlsoap.org/ws/2004/04/trust">
\r
2812 <ps:AuthInfo xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL" Id="PPAuthInfo">
\r
2813 <ps:HostingApp>{7108E71A-9926-4FCB-BCC9-9A9D3F32E423}</ps:HostingApp>
\r
2814 <ps:BinaryVersion>4</ps:BinaryVersion>
\r
2815 <ps:UIVersion>1</ps:UIVersion>
\r
2816 <ps:Cookies></ps:Cookies>
\r
2817 <ps:RequestParams>AQAAAAIAAABsYwQAAAAxMDMz</ps:RequestParams>
\r
2820 <wsse:UsernameToken Id="user">
\r
2821 <wsse:Username>'.$user.'</wsse:Username>
\r
2822 <wsse:Password>'.$password.'</wsse:Password>
\r
2823 </wsse:UsernameToken>
\r
2827 <ps:RequestMultipleSecurityTokens xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL" Id="RSTS">
\r
2828 <wst:RequestSecurityToken Id="RST0">
\r
2829 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2831 <wsa:EndpointReference>
\r
2832 <wsa:Address>http://Passport.NET/tb</wsa:Address>
\r
2833 </wsa:EndpointReference>
\r
2835 </wst:RequestSecurityToken>
\r
2836 <wst:RequestSecurityToken Id="RST1">
\r
2837 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2839 <wsa:EndpointReference>
\r
2840 <wsa:Address>messengerclear.live.com</wsa:Address>
\r
2841 </wsa:EndpointReference>
\r
2843 <wsse:PolicyReference URI="'.$this->passport_policy.'"></wsse:PolicyReference>
\r
2844 </wst:RequestSecurityToken>
\r
2845 <wst:RequestSecurityToken Id="RST2">
\r
2846 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2848 <wsa:EndpointReference>
\r
2849 <wsa:Address>messenger.msn.com</wsa:Address>
\r
2850 </wsa:EndpointReference>
\r
2852 <wsse:PolicyReference URI="?id=507"></wsse:PolicyReference>
\r
2853 </wst:RequestSecurityToken>
\r
2854 <wst:RequestSecurityToken Id="RST3">
\r
2855 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2857 <wsa:EndpointReference>
\r
2858 <wsa:Address>contacts.msn.com</wsa:Address>
\r
2859 </wsa:EndpointReference>
\r
2861 <wsse:PolicyReference URI="MBI"></wsse:PolicyReference>
\r
2862 </wst:RequestSecurityToken>
\r
2863 <wst:RequestSecurityToken Id="RST4">
\r
2864 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2866 <wsa:EndpointReference>
\r
2867 <wsa:Address>messengersecure.live.com</wsa:Address>
\r
2868 </wsa:EndpointReference>
\r
2870 <wsse:PolicyReference URI="MBI_SSL"></wsse:PolicyReference>
\r
2871 </wst:RequestSecurityToken>
\r
2872 <wst:RequestSecurityToken Id="RST5">
\r
2873 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2875 <wsa:EndpointReference>
\r
2876 <wsa:Address>spaces.live.com</wsa:Address>
\r
2877 </wsa:EndpointReference>
\r
2879 <wsse:PolicyReference URI="MBI"></wsse:PolicyReference>
\r
2880 </wst:RequestSecurityToken>
\r
2881 <wst:RequestSecurityToken Id="RST6">
\r
2882 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2884 <wsa:EndpointReference>
\r
2885 <wsa:Address>storage.msn.com</wsa:Address>
\r
2886 </wsa:EndpointReference>
\r
2888 <wsse:PolicyReference URI="MBI"></wsse:PolicyReference>
\r
2889 </wst:RequestSecurityToken>
\r
2890 </ps:RequestMultipleSecurityTokens>
\r
2894 $this->debug_message("*** URL: $passport_url");
\r
2895 $this->debug_message("*** Sending SOAP:\n$XML");
\r
2896 $curl = curl_init();
\r
2897 curl_setopt($curl, CURLOPT_URL, $passport_url);
\r
2898 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
2899 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
2900 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
2901 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
2902 curl_setopt($curl, CURLOPT_POST, 1);
\r
2903 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
2904 $data = curl_exec($curl);
\r
2905 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
2906 curl_close($curl);
\r
2907 $this->debug_message("*** Get Result:\n$data");
\r
2909 if ($http_code != 200) {
\r
2910 // sometimes, redirect to another URL
\r
2912 //<faultcode>psf:Redirect</faultcode>
\r
2913 //<psf:redirectUrl>https://msnia.login.live.com/pp450/RST.srf</psf:redirectUrl>
\r
2914 //<faultstring>Authentication Failure</faultstring>
\r
2915 if (strpos($data, '<faultcode>psf:Redirect</faultcode>') === false) {
\r
2916 $this->debug_message("*** Could not get passport ticket! http code = $http_code");
\r
2919 preg_match("#<psf\:redirectUrl>(.*)</psf\:redirectUrl>#", $data, $matches);
\r
2920 if (count($matches) == 0) {
\r
2921 $this->debug_message('*** Redirected, but could not get redirect URL!');
\r
2924 $redirect_url = $matches[1];
\r
2925 if ($redirect_url == $passport_url) {
\r
2926 $this->debug_message('*** Redirected, but to same URL!');
\r
2929 $this->debug_message("*** Redirected to $redirect_url");
\r
2930 return $this->get_passport_ticket($redirect_url);
\r
2933 // sometimes, redirect to another URL, also return 200
\r
2935 //<faultcode>psf:Redirect</faultcode>
\r
2936 //<psf:redirectUrl>https://msnia.login.live.com/pp450/RST.srf</psf:redirectUrl>
\r
2937 //<faultstring>Authentication Failure</faultstring>
\r
2938 if (strpos($data, '<faultcode>psf:Redirect</faultcode>') !== false) {
\r
2939 preg_match("#<psf\:redirectUrl>(.*)</psf\:redirectUrl>#", $data, $matches);
\r
2940 if (count($matches) != 0) {
\r
2941 $redirect_url = $matches[1];
\r
2942 if ($redirect_url == $passport_url) {
\r
2943 $this->debug_message('*** Redirected, but to same URL!');
\r
2946 $this->debug_message("*** Redirected to $redirect_url");
\r
2947 return $this->get_passport_ticket($redirect_url);
\r
2951 // no Redurect faultcode or URL
\r
2952 // we should get the ticket here
\r
2954 // we need ticket and secret code
\r
2955 // RST1: messengerclear.live.com
\r
2956 // <wsse:BinarySecurityToken Id="Compact1">t=tick&p=</wsse:BinarySecurityToken>
\r
2957 // <wst:BinarySecret>binary secret</wst:BinarySecret>
\r
2958 // RST2: messenger.msn.com
\r
2959 // <wsse:BinarySecurityToken Id="PPToken2">t=tick</wsse:BinarySecurityToken>
\r
2960 // RST3: contacts.msn.com
\r
2961 // <wsse:BinarySecurityToken Id="Compact3">t=tick&p=</wsse:BinarySecurityToken>
\r
2962 // RST4: messengersecure.live.com
\r
2963 // <wsse:BinarySecurityToken Id="Compact4">t=tick&p=</wsse:BinarySecurityToken>
\r
2964 // RST5: spaces.live.com
\r
2965 // <wsse:BinarySecurityToken Id="Compact5">t=tick&p=</wsse:BinarySecurityToken>
\r
2966 // RST6: storage.msn.com
\r
2967 // <wsse:BinarySecurityToken Id="Compact6">t=tick&p=</wsse:BinarySecurityToken>
\r
2969 "<wsse\:BinarySecurityToken Id=\"Compact1\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2970 "<wst\:BinarySecret>(.*)</wst\:BinarySecret>(.*)".
\r
2971 "<wsse\:BinarySecurityToken Id=\"PPToken2\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2972 "<wsse\:BinarySecurityToken Id=\"Compact3\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2973 "<wsse\:BinarySecurityToken Id=\"Compact4\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2974 "<wsse\:BinarySecurityToken Id=\"Compact5\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2975 "<wsse\:BinarySecurityToken Id=\"Compact6\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2979 // no ticket found!
\r
2980 if (count($matches) == 0) {
\r
2981 $this->debug_message('*** Could not get passport ticket!');
\r
2985 //$this->debug_message(var_export($matches, true));
\r
2986 // matches[0]: all data
\r
2987 // matches[1]: RST1 (messengerclear.live.com) ticket
\r
2988 // matches[2]: ...
\r
2989 // matches[3]: RST1 (messengerclear.live.com) binary secret
\r
2990 // matches[4]: ...
\r
2991 // matches[5]: RST2 (messenger.msn.com) ticket
\r
2992 // matches[6]: ...
\r
2993 // matches[7]: RST3 (contacts.msn.com) ticket
\r
2994 // matches[8]: ...
\r
2995 // matches[9]: RST4 (messengersecure.live.com) ticket
\r
2996 // matches[10]: ...
\r
2997 // matches[11]: RST5 (spaces.live.com) ticket
\r
2998 // matches[12]: ...
\r
2999 // matches[13]: RST6 (storage.live.com) ticket
\r
3000 // matches[14]: ...
\r
3003 // ticket => $matches[1]
\r
3004 // secret => $matches[3]
\r
3005 // web_ticket => $matches[5]
\r
3006 // contact_ticket => $matches[7]
\r
3007 // oim_ticket => $matches[9]
\r
3008 // space_ticket => $matches[11]
\r
3009 // storage_ticket => $matches[13]
\r
3011 // yes, we get ticket
\r
3012 $aTickets = array(
\r
3013 'ticket' => html_entity_decode($matches[1]),
\r
3014 'secret' => html_entity_decode($matches[3]),
\r
3015 'web_ticket' => html_entity_decode($matches[5]),
\r
3016 'contact_ticket' => html_entity_decode($matches[7]),
\r
3017 'oim_ticket' => html_entity_decode($matches[9]),
\r
3018 'space_ticket' => html_entity_decode($matches[11]),
\r
3019 'storage_ticket' => html_entity_decode($matches[13])
\r
3021 $this->ticket = $aTickets;
\r
3022 //$this->debug_message(var_export($aTickets, true));
\r
3023 $ABAuthHeaderArray = array(
\r
3024 'ABAuthHeader' => array(
\r
3025 ':' => array('xmlns' => 'http://www.msn.com/webservices/AddressBook'),
\r
3026 'ManagedGroupRequest' => false,
\r
3027 'TicketToken' => htmlspecialchars($this->ticket['contact_ticket']),
\r
3030 $this->ABAuthHeader = new SoapHeader('http://www.msn.com/webservices/AddressBook', 'ABAuthHeader', $this->Array2SoapVar($ABAuthHeaderArray));
\r
3035 * Generate the data to send a message
\r
3037 * @param string $sMessage Message
\r
3038 * @param integer $network Network
\r
3039 * @return string Message data
\r
3041 private function getMessage($sMessage, $network = 1) {
\r
3042 $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
3043 $msg_header_len = strlen($msg_header);
\r
3044 if ($network == 1)
\r
3045 $maxlen = self::MAX_MSN_MESSAGE_LEN - $msg_header_len;
\r
3047 $maxlen = self::MAX_YAHOO_MESSAGE_LEN - $msg_header_len;
\r
3048 $sMessage = str_replace("\r", '', $sMessage);
\r
3049 $msg = substr($sMessage, 0, $maxlen);
\r
3050 return $msg_header.$msg;
\r
3054 * Sleep for the given number of seconds
\r
3056 * @param integer $wait Number of seconds to sleep for
\r
3058 private function NSRetryWait($wait) {
\r
3059 $this->debug_message("*** Sleeping for $wait seconds before retrying");
\r
3064 * Sends a ping command
\r
3066 * Should be called about every 50 seconds
\r
3070 public function sendPing() {
\r
3072 $this->ns_writeln("PNG");
\r
3076 * Methods to add / call callbacks
\r
3080 * Calls User Handler
\r
3082 * Calls registered handler for a specific event.
\r
3084 * @param string $event Command (event) name (Rvous etc)
\r
3085 * @param array $data Data
\r
3086 * @see registerHandler
\r
3089 private function callHandler($event, $data = NULL) {
\r
3090 if (isset($this->myEventHandlers[$event])) {
\r
3091 if ($data !== NULL) {
\r
3092 call_user_func($this->myEventHandlers[$event], $data);
\r
3094 call_user_func($this->myEventHandlers[$event]);
\r
3100 * Registers a user handler
\r
3103 * IMIn, Pong, ConnectFailed, Reconnect,
\r
3104 * AddedToList, RemovedFromList, StatusChange
\r
3106 * @param string $event Event name
\r
3107 * @param string $handler User function to call
\r
3108 * @see callHandler
\r
3109 * @return boolean true if successful
\r
3111 public function registerHandler($event, $handler) {
\r
3112 if (is_callable($handler)) {
\r
3113 $this->myEventHandlers[$event] = $handler;
\r
3121 * Debugging methods
\r
3125 * Print message if debugging is enabled
\r
3127 * @param string $str Message to print
\r
3129 private function debug_message($str) {
\r
3130 if (!$this->debug) return;
\r
3135 * Dump binary data
\r
3137 * @param string $str Data string
\r
3138 * @return Binary data
\r
3140 private function dump_binary($str) {
\r
3144 $len = strlen($str);
\r
3145 for ($i = 0; $i < $len; $i++) {
\r
3146 if (($i % 16) == 0) {
\r
3147 if ($buf !== '') {
\r
3148 $buf .= "$h_str $a_str\n";
\r
3150 $buf .= sprintf("%04X:", $i);
\r
3154 $ch = ord($str[$i]);
\r
3158 $a_str .= chr($ch);
\r
3159 $h_str .= sprintf(" %02X", $ch);
\r
3161 if ($h_str !== '')
\r
3162 $buf .= "$h_str $a_str\n";
\r