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 authenticated fail!';
\r
278 $ticket = $aTickets['ticket'];
\r
279 $secret = $aTickets['secret'];
\r
280 $this->ticket = $aTickets;
\r
281 $login_code = $this->generateLoginBLOB($secret, $nonce);
\r
283 // NS: >>> USR {id} SSO S {ticket} {login_code}
\r
284 $this->ns_writeln("USR $this->id ".self::LOGIN_METHOD." S $ticket $login_code");
\r
285 $this->authed = true;
\r
289 // main login server will redirect to anther NS after USR command
\r
291 // NS: <<< XFR {id} NS {server} 0 {server}
\r
293 // NS: <<< XFR {id} NS {server} U D
\r
294 @list(/* XFR */, /* id */, $Type, $server, /* ... */) = @explode(' ', $data);
\r
295 if ($Type!='NS') break;
\r
296 @list($ip, $port) = @explode(':', $server);
\r
297 // this connection will close after XFR
\r
298 @fclose($this->NSfp);
\r
300 $this->NSfp = @fsockopen($ip, $port, $errno, $errstr, $this->timeout);
\r
301 if (!$this->NSfp) {
\r
302 $this->error = "Can't connect to $ip:$port, error => $errno, $errstr";
\r
307 // NS: >> VER {id} MSNP9 CVR0
\r
309 // NS: >>> VER {id} MSNP15 CVR0
\r
310 $this->ns_writeln("VER $this->id ".self::PROTOCOL.' CVR0');
\r
314 // return some policy data after 'USR {id} SSO I {user}' command
\r
315 // NS: <<< GCF 0 {size}
\r
316 @list(/* GCF */, /* 0 */, $size,) = @explode(' ', $data);
\r
317 // we don't need the data, just read it and drop
\r
318 if (is_numeric($size) && $size > 0)
\r
319 $this->ns_readdata($size);
\r
323 // we'll quit if got any error
\r
324 if (is_numeric($code)) {
\r
327 $this->ns_writeln("OUT");
\r
328 @fclose($this->NSfp);
\r
329 $this->error = "Error code: $code, please check the detail information from: http://msnpiki.msnfanatic.com/index.php/Reference:Error_List";
\r
332 // unknown response from server, just ignore it
\r
340 * Sign onto the NS server and retrieve the address book
\r
344 public function signon() {
\r
345 /* FIXME Don't implement the signon as a loop or we could hang
\r
346 * the queue handler! */
\r
347 $this->debug_message('*** Trying to connect to MSN network');
\r
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) continue;
\r
363 // Get membership lists
\r
364 if (($this->aContactList = $this->getMembershipList()) === false) {
\r
365 $this->signonFailure('!!! Get membership list failed');
\r
369 if ($this->update_pending) {
\r
370 if (is_array($this->aContactList)) {
\r
371 $pending = 'Pending';
\r
372 foreach ($this->aContactList as $u_domain => $aUserList) {
\r
373 foreach ($aUserList as $u_name => $aNetworks) {
\r
374 foreach ($aNetworks as $network => $aData) {
\r
375 if (isset($aData[$pending])) {
\r
378 foreach (array('Allow', 'Reverse') as $list) {
\r
379 if (isset($aData[$list]))
\r
382 if ($this->addMemberToList($u_name.'@'.$u_domain, $network, $list)) {
\r
383 $this->aContactList[$u_domain][$u_name][$network][$list] = false;
\r
389 $id = $aData[$pending];
\r
390 // we can delete it from pending now
\r
391 if ($this->delMemberFromList($id, $u_name.'@'.$u_domain, $network, $pending))
\r
392 unset($this->aContactList[$u_domain][$u_name][$network][$pending]);
\r
397 foreach (array('Allow', 'Reverse') as $list) {
\r
398 if (!isset($aData[$list])) {
\r
399 if ($this->addMemberToList($u_name.'@'.$u_domain, $network, $list))
\r
400 $this->aContactList[$u_domain][$u_name][$network][$list] = false;
\r
412 if (is_array($this->aContactList)) {
\r
413 foreach ($this->aContactList as $u_domain => $aUserList) {
\r
414 $str = '<d n="'.$u_domain.'">';
\r
415 $len += strlen($str);
\r
417 $this->aADL[$n] = '<ml l="1">'.$sList.'</ml>';
\r
420 $len = strlen($str);
\r
423 foreach ($aUserList as $u_name => $aNetworks) {
\r
424 foreach ($aNetworks as $network => $status) {
\r
425 $str = '<c n="'.$u_name.'" l="3" t="'.$network.'" />';
\r
426 $len += strlen($str);
\r
427 // max: 7500, but <ml l="1"></d></ml> is 19,
\r
431 $this->aADL[$n] = '<ml l="1">'.$sList.'</ml>';
\r
433 $sList = '<d n="'.$u_domain.'">'.$str;
\r
434 $len = strlen($sList);
\r
443 $this->aADL[$n] = '<ml l="1">'.$sList.'</ml>';
\r
444 // NS: >>> BLP {id} BL
\r
445 $this->ns_writeln("BLP $this->id BL");
\r
446 foreach ($this->aADL as $str) {
\r
447 $len = strlen($str);
\r
448 // NS: >>> ADL {id} {size}
\r
449 $this->ns_writeln("ADL $this->id $len");
\r
450 $this->ns_writedata($str);
\r
452 // NS: >>> PRP {id} MFN name
\r
453 if ($this->alias == '') $this->alias = $user;
\r
454 $aliasname = rawurlencode($this->alias);
\r
455 $this->ns_writeln("PRP $this->id MFN $aliasname");
\r
456 //è¨å®šå€‹äººå¤§é è²¼
\r
457 //$MsnObj=$this->PhotoStckObj();
\r
458 // NS: >>> CHG {id} {status} {clientid} {msnobj}
\r
459 $this->ns_writeln("CHG $this->id NLN $this->clientid");
\r
460 if ($this->PhotoStickerFile !== false)
\r
461 $this->ns_writeln("CHG $this->id NLN $this->clientid ".rawurlencode($this->MsnObj($this->PhotoStickerFile)));
\r
462 // NS: >>> UUX {id} length
\r
463 $str = '<Data><PSM>'.htmlspecialchars($this->psm).'</PSM><CurrentMedia></CurrentMedia><MachineGuid></MachineGuid></Data>';
\r
464 $len = strlen($str);
\r
465 $this->ns_writeln("UUX $this->id $len");
\r
466 $this->ns_writedata($str);
\r
467 if (!self::socketcheck($this->NSfp)) {
\r
468 $this->debug_message('*** Connected, waiting for commands');
\r
471 $this->NSRetryWait($this->retry_wait);
\r
477 * Called if there is an error during signon
\r
479 * @param string $message Error message to log
\r
482 private function signonFailure($message) {
\r
483 $this->debug_message($message);
\r
484 $this->callHandler('ConnectFailed');
\r
485 $this->NSRetryWait($this->retry_wait);
\r
489 * Log out and close the NS connection
\r
493 private function nsLogout() {
\r
494 if (is_resource($this->NSfp) && !feof($this->NSfp)) {
\r
497 $this->ns_writeln("OUT");
\r
498 fclose($this->NSfp);
\r
499 $this->NSfp = false;
\r
500 $this->debug_message("*** Logged out");
\r
505 * NS and SB command handling methods
\r
509 * Read and handle incoming command from NS
\r
513 private function nsReceive() {
\r
514 // Sign in again if not signed in or socket failed
\r
515 if (!is_resource($this->NSfp) || self::socketcheck($this->NSfp)) {
\r
516 $this->callHandler('Reconnect');
\r
517 $this->NSRetryWait($this->retry_wait);
\r
522 $data = $this->ns_readln();
\r
523 if ($data === false) {
\r
524 // There was no data / an error when reading from the socket so reconnect
\r
525 $this->callHandler('Reconnect');
\r
526 $this->NSRetryWait($this->retry_wait);
\r
531 switch (substr($data, 0, 3)) {
\r
533 // after 'USR {id} OK {user} {verify} 0' response, the server will send SBS and profile to us
\r
534 // NS: <<< SBS 0 null
\r
540 // refresh ADL, so we re-send it again
\r
541 if (is_array($this->aADL)) {
\r
542 foreach ($this->aADL as $str) {
\r
543 $len = strlen($str);
\r
544 // NS: >>> ADL {id} {size}
\r
545 $this->ns_writeln("ADL $this->id $len");
\r
546 $this->ns_writedata($str);
\r
552 // NS: <<< LST {email} {alias} 11 0
\r
553 @list(/* LST */, $email, /* alias */,) = @explode(' ', $data);
\r
554 @list($u_name, $u_domain) = @explode('@', $email);
\r
555 if (!isset($this->aContactList[$u_domain][$u_name][1])) {
\r
556 $this->aContactList[$u_domain][$u_name][1]['Allow'] = 'Allow';
\r
557 $this->debug_message("*** Added to contact list: $u_name@$u_domain");
\r
562 // randomly, we get ADL command, someone add us to their contact list for MSNP15
\r
563 // NS: <<< ADL 0 {size}
\r
564 @list(/* ADL */, /* 0 */, $size,) = @explode(' ', $data);
\r
565 if (is_numeric($size) && $size > 0) {
\r
566 $data = $this->ns_readdata($size);
\r
567 preg_match('#<ml><d n="([^"]+)"><c n="([^"]+)"(.*) t="(\d*)"(.*) /></d></ml>#', $data, $matches);
\r
568 if (is_array($matches) && count($matches) > 0) {
\r
569 $u_domain = $matches[1];
\r
570 $u_name = $matches[2];
\r
571 $network = $matches[4];
\r
572 if (isset($this->aContactList[$u_domain][$u_name][$network]))
\r
573 $this->debug_message("*** Someone (network: $network) added us to their list (but already in our list): $u_name@$u_domain");
\r
577 foreach (array('Allow', 'Reverse') as $list) {
\r
578 if (!$this->addMemberToList($u_name.'@'.$u_domain, $network, $list)) {
\r
580 $this->debug_message("*** Could not add $u_name@$u_domain (network: $network) to $list list");
\r
583 $aTickets = $this->get_passport_ticket();
\r
584 if (!$aTickets || !is_array($aTickets)) {
\r
585 // failed to login? ignore it
\r
586 $this->debug_message("*** Could not re-login, something wrong here");
\r
587 $this->debug_message("*** Could not add $u_name@$u_domain (network: $network) to $list list");
\r
591 $this->ticket = $aTickets;
\r
592 $this->debug_message("**** Got new ticket, trying again");
\r
593 if (!$this->addMemberToList($u_name.'@'.$u_domain, $network, $list)) {
\r
594 $this->debug_message("*** Could not add $u_name@$u_domain (network: $network) to $list list");
\r
598 $this->aContactList[$u_domain][$u_name][$network][$list] = false;
\r
601 $this->debug_message("*** Someone (network: $network) added us to their list: $u_name@$u_domain");
\r
603 $str = '<ml l="1"><d n="'.$u_domain.'"><c n="'.$u_name.'" l="3" t="'.$network.'" /></d></ml>';
\r
604 $len = strlen($str);
\r
606 $this->callHandler('AddedToList', array('screenname' => $u_name.'@'.$u_domain, 'network' => $network));
\r
609 $this->debug_message("*** Someone added us to their list: $data");
\r
614 // randomly, we get RML command, someome remove us to their contact list for MSNP15
\r
615 // NS: <<< RML 0 {size}
\r
616 @list(/* RML */, /* 0 */, $size,) = @explode(' ', $data);
\r
617 if (is_numeric($size) && $size > 0) {
\r
618 $data = $this->ns_readdata($size);
\r
619 preg_match('#<ml><d n="([^"]+)"><c n="([^"]+)"(.*) t="(\d*)"(.*) /></d></ml>#', $data, $matches);
\r
620 if (is_array($matches) && count($matches) > 0) {
\r
621 $u_domain = $matches[1];
\r
622 $u_name = $matches[2];
\r
623 $network = $matches[4];
\r
624 if (isset($this->aContactList[$u_domain][$u_name][$network])) {
\r
625 $aData = $this->aContactList[$u_domain][$u_name][$network];
\r
627 foreach ($aData as $list => $id)
\r
628 $this->delMemberFromList($id, $u_name.'@'.$u_domain, $network, $list);
\r
630 unset($this->aContactList[$u_domain][$u_name][$network]);
\r
631 $this->debug_message("*** Someone (network: $network) removed us from their list: $u_name@$u_domain");
\r
634 $this->debug_message("*** Someone (network: $network) removed us from their list (but not in our list): $u_name@$u_domain");
\r
636 $this->callHandler('RemovedFromList', array('screenname' => $u_name.'@'.$u_domain, 'network' => $network));
\r
639 $this->debug_message("*** Someone removed us from their list: $data");
\r
644 // randomly, we get MSG notification from server
\r
645 // NS: <<< MSG Hotmail Hotmail {size}
\r
646 @list(/* MSG */, /* Hotmail */, /* Hotmail */, $size,) = @explode(' ', $data);
\r
647 if (is_numeric($size) && $size > 0) {
\r
648 $data = $this->ns_readdata($size);
\r
649 $aLines = @explode("\n", $data);
\r
653 foreach ($aLines as $line) {
\r
654 $line = rtrim($line);
\r
656 if ($line === '') {
\r
660 if (strncasecmp($line, 'Content-Type:', 13) == 0) {
\r
661 if (strpos($line, 'text/x-msmsgsinitialmdatanotification') === false && strpos($line, 'text/x-msmsgsoimnotification') === false) {
\r
662 // we just need text/x-msmsgsinitialmdatanotification
\r
663 // or text/x-msmsgsoimnotification
\r
670 if (strncasecmp($line, 'Mail-Data:', 10) == 0) {
\r
671 $maildata = trim(substr($line, 10));
\r
676 $this->debug_message("*** Ignoring MSG for: $line");
\r
679 if ($maildata == '') {
\r
680 $this->debug_message("*** Ignoring MSG not for OIM");
\r
684 if (strcasecmp($maildata, 'too-large') == 0) {
\r
685 $this->debug_message("*** Large mail-data, need to get the data via SOAP");
\r
686 $maildata = $this->getOIM_maildata();
\r
687 if ($maildata === false) {
\r
688 $this->debug_message("*** Could not get mail-data via SOAP");
\r
690 // maybe we need to re-login again
\r
691 $aTickets = $this->get_passport_ticket();
\r
692 if (!$aTickets || !is_array($aTickets)) {
\r
693 // failed to login? ignore it
\r
694 $this->debug_message("*** Could not re-login, something wrong here, ignoring this OIM");
\r
698 $this->ticket = $aTickets;
\r
699 $this->debug_message("*** Got new ticket, trying again");
\r
700 $maildata = $this->getOIM_maildata();
\r
701 if ($maildata === false) {
\r
702 $this->debug_message("*** Could not get mail-data via SOAP, and re-login already attempted, ignoring this OIM");
\r
707 // could be a lots of <M>...</M>, so we can't use preg_match here
\r
711 $start = strpos($p, '<M>');
\r
712 $end = strpos($p, '</M>');
\r
713 if ($start === false || $end === false || $start > $end) break;
\r
715 $sOIM = substr($p, $start, $end - $start);
\r
717 $p = substr($p, $end);
\r
719 if (count($aOIMs) == 0) {
\r
720 $this->debug_message("*** Ignoring empty OIM");
\r
723 foreach ($aOIMs as $maildata) {
\r
724 // T: 11 for MSN, 13 for Yahoo
\r
725 // S: 6 for MSN, 7 for Yahoo
\r
726 // RT: the datetime received by server
\r
727 // RS: already read or not
\r
728 // SZ: size of message
\r
731 // F: always 00000000-0000-0000-0000-000000000009
\r
733 preg_match('#<T>(.*)</T>#', $maildata, $matches);
\r
734 if (count($matches) == 0) {
\r
735 $this->debug_message("*** Ignoring OIM maildata without <T>type</T>");
\r
738 $oim_type = $matches[1];
\r
739 if ($oim_type = 13)
\r
743 preg_match('#<E>(.*)</E>#', $maildata, $matches);
\r
744 if (count($matches) == 0) {
\r
745 $this->debug_message("*** Ignoring OIM maildata without <E>sender</E>");
\r
748 $oim_sender = $matches[1];
\r
749 preg_match('#<I>(.*)</I>#', $maildata, $matches);
\r
750 if (count($matches) == 0) {
\r
751 $this->debug_message("*** Ignoring OIM maildata without <I>msgid</I>");
\r
754 $oim_msgid = $matches[1];
\r
755 preg_match('#<SZ>(.*)</SZ>#', $maildata, $matches);
\r
756 $oim_size = (count($matches) == 0) ? 0 : $matches[1];
\r
757 preg_match('#<RT>(.*)</RT>#', $maildata, $matches);
\r
758 $oim_time = (count($matches) == 0) ? 0 : $matches[1];
\r
759 $this->debug_message("*** OIM received from $oim_sender, Time: $oim_time, MSGID: $oim_msgid, size: $oim_size");
\r
760 $sMsg = $this->getOIM_message($oim_msgid);
\r
761 if ($sMsg === false) {
\r
762 $this->debug_message("*** Could not get OIM, msgid = $oim_msgid");
\r
764 $this->debug_message("*** Could not get OIM via SOAP, and re-login already attempted, ignoring this OIM");
\r
767 $aTickets = $this->get_passport_ticket();
\r
768 if (!$aTickets || !is_array($aTickets)) {
\r
769 // failed to login? ignore it
\r
770 $this->debug_message("*** Could not re-login, something wrong here, ignoring this OIM");
\r
774 $this->ticket = $aTickets;
\r
775 $this->debug_message("*** get new ticket, try it again");
\r
776 $sMsg = $this->getOIM_message($oim_msgid);
\r
777 if ($sMsg === false) {
\r
778 $this->debug_message("*** Could not get OIM via SOAP, and re-login already attempted, ignoring this OIM");
\r
782 $this->debug_message("*** MSG (Offline) from $oim_sender (network: $network): $sMsg");
\r
783 $this->callHandler('IMin', array('sender' => $oim_sender, 'message' => $sMsg, 'network' => $network, 'offline' => true));
\r
789 // randomly, we get UBM, this is the message from other network, like Yahoo!
\r
790 // NS: <<< UBM {email} $network $type {size}
\r
791 @list(/* UBM */, $from_email, $network, $type, $size,) = @explode(' ', $data);
\r
792 if (is_numeric($size) && $size > 0) {
\r
793 $data = $this->ns_readdata($size);
\r
794 $aLines = @explode("\n", $data);
\r
798 foreach ($aLines as $line) {
\r
799 $line = rtrim($line);
\r
801 if ($line === '') {
\r
805 if (strncasecmp($line, 'TypingUser:', 11) == 0) {
\r
811 $aSubLines = @explode("\r", $line);
\r
812 foreach ($aSubLines as $str) {
\r
819 $this->debug_message("*** Ignoring message from $from_email: $line");
\r
822 $this->debug_message("*** MSG from $from_email (network: $network): $sMsg");
\r
823 $this->callHandler('IMin', array('sender' => $from_email, 'message' => $sMsg, 'network' => $network, 'offline' => false));
\r
828 // randomly, we get UBX notification from server
\r
829 // NS: <<< UBX email {network} {size}
\r
830 @list(/* UBX */, /* email */, /* network */, $size,) = @explode(' ', $data);
\r
831 // we don't need the notification data, so just ignore it
\r
832 if (is_numeric($size) && $size > 0)
\r
833 $this->ns_readdata($size);
\r
837 // randomly, we'll get challenge from server
\r
838 // NS: <<< CHL 0 {code}
\r
839 @list(/* CHL */, /* 0 */, $chl_code,) = @explode(' ', $data);
\r
840 $fingerprint = $this->getChallenge($chl_code);
\r
841 // NS: >>> QRY {id} {product_id} 32
\r
842 // NS: >>> fingerprint
\r
843 $this->ns_writeln("QRY $this->id ".self::PROD_ID.' 32');
\r
844 $this->ns_writedata($fingerprint);
\r
845 $this->ns_writeln("CHG $this->id NLN $this->clientid");
\r
846 if ($this->PhotoStickerFile !== false)
\r
847 $this->ns_writeln("CHG $this->id NLN $this->clientid ".rawurlencode($this->MsnObj($this->PhotoStickerFile)));
\r
850 // NS: <<< CHG {id} {status} {code}
\r
852 // change our status to online first
\r
856 // sometimes, NS will redirect to another NS
\r
858 // NS: <<< XFR {id} NS {server} 0 {server}
\r
860 // NS: <<< XFR {id} NS {server} U D
\r
861 // for normal switchboard XFR
\r
862 // NS: <<< XFR {id} SB {server} CKI {cki} U messenger.msn.com 0
\r
863 @list(/* XFR */, /* {id} */, $server_type, $server, /* CKI */, $cki_code, /* ... */) = @explode(' ', $data);
\r
864 @list($ip, $port) = @explode(':', $server);
\r
865 if ($server_type != 'SB') {
\r
867 // this connection will close after XFR
\r
872 $this->debug_message("NS: <<< XFR SB");
\r
873 $user = array_shift($this->waitingForXFR);
\r
874 $bSBresult = $this->switchboard_control($ip, $port, $cki_code, $User, $Message);
\r
876 $bSBresult = $this->switchboard_control($ip, $port, $cki_code, $aMSNUsers[$nCurrentUser], $sMessage);
\r
877 if ($bSBresult === false) {
\r
878 // error for switchboard
\r
879 $this->debug_message("!!! error for sending message to ".$aMSNUsers[$nCurrentUser]);
\r
880 $aOfflineUsers[] = $aMSNUsers[$nCurrentUser];
\r
884 // NS: <<< QNG {time}
\r
885 @list(/* QNG */, $ping_wait) = @explode(' ', $data);
\r
886 $this->callHandler('Pong', $ping_wait);
\r
890 if ($this->PhotoStickerFile !== false)
\r
891 $this->ns_writeln("CHG $this->id NLN $this->clientid ".rawurlencode($this->MsnObj($this->PhotoStickerFile)));
\r
893 $this->ns_writeln("CHG $this->id NLN $this->clientid");
\r
894 // someone is trying to talk to us
\r
895 // NS: <<< RNG {session_id} {server} {auth_type} {ticket} {email} {alias} U {client} 0
\r
896 $this->debug_message("NS: <<< RNG $data");
\r
897 @list(/* RNG */, $sid, $server, /* auth_type */, $ticket, $email, $name, ) = @explode(' ', $data);
\r
898 @list($sb_ip, $sb_port) = @explode(':', $server);
\r
899 $this->debug_message("*** RING from $email, $sb_ip:$sb_port");
\r
900 $this->addContact($email, 1, $email, true);
\r
901 $this->connectToSBSession('Passive', $sb_ip, $sb_port, $email, array('sid' => $sid, 'ticket' => $ticket));
\r
904 // force logout from NS
\r
906 $this->debug_message("*** LOGOUT from NS");
\r
907 return $this->nsLogout();
\r
910 $code = substr($data,0,3);
\r
911 if (is_numeric($code)) {
\r
912 $this->error = "Error code: $code, please check the detail information from: http://msnpiki.msnfanatic.com/index.php/Reference:Error_List";
\r
913 $this->debug_message("*** NS: $this->error");
\r
915 return $this->nsLogout();
\r
922 * Read and handle incoming command/message from
\r
923 * a switchboard session socket
\r
925 private function sbReceive($socket) {
\r
926 $intsocket = (int) $socket;
\r
927 $session = &$this->switchBoardSessions[$intsocket];
\r
929 if (feof($socket)) {
\r
930 // Unset session lookup value
\r
931 unset($this->switchBoardSessionLookup[$session['to']]);
\r
933 // Unset session itself
\r
934 unset($this->switchBoardSessions[$intsocket]);
\r
938 $id = &$session['id'];
\r
940 $data = $this->sb_readln($socket);
\r
941 $code = substr($data, 0, 3);
\r
944 // SB: <<< IRO {id} {rooster} {roostercount} {email} {alias} {clientid}
\r
945 @list(/* IRO */, /* id */, $cur_num, $total, $email, $alias, $clientid) = @explode(' ', $data);
\r
946 $this->debug_message("*** $email joined session");
\r
947 $session['joined'] = true;
\r
950 $this->debug_message("*** Quit for BYE");
\r
951 $this->endSBSession();
\r
954 // SB: <<< USR {id} OK {user} {alias}
\r
955 // we don't need the data, just ignore it
\r
956 // request user to join this switchboard
\r
957 // SB: >>> CAL {id} {user}
\r
958 $this->sb_writeln($socket, $id, "CAL $this->id $user");
\r
961 // SB: <<< CAL {id} RINGING {?}
\r
962 // we don't need this, just ignore, and wait for other response
\r
966 // SB: <<< JOI {user} {alias} {clientid?}
\r
968 // we don't need the data, just ignore it
\r
969 // no more user here
\r
970 $session['joined'] = true;
\r
973 // SB: <<< MSG {email} {alias} {len}
\r
974 @list(/* MSG */, $from_email, /* alias */, $len, ) = @explode(' ', $data);
\r
976 $data = $this->sb_readdata($socket, $len);
\r
977 $aLines = @explode("\n", $data);
\r
982 foreach ($aLines as $line) {
\r
983 $line = rtrim($line);
\r
985 if ($line === '') {
\r
989 if (strncasecmp($line, 'TypingUser:', 11) == 0) {
\r
990 // typing notification, just ignore
\r
994 if (strncasecmp($line, 'Chunk:', 6) == 0) {
\r
995 // we don't handle any split message, just ignore
\r
999 if (strncasecmp($line, 'Content-Type: application/x-msnmsgrp2p', 38) == 0) {
\r
1000 // p2p message, ignore it, but we need to send acknowledgement for it...
\r
1002 $p = strstr($data, "\n\n");
\r
1004 if ($p === false) {
\r
1005 $p = strstr($data, "\r\n\r\n");
\r
1007 $sMsg = substr($p, 4);
\r
1010 $sMsg = substr($p, 2);
\r
1013 if (strncasecmp($line, 'Content-Type: application/x-', 28) == 0) {
\r
1014 // ignore all application/x-... message
\r
1016 // application/x-ms-ink => ink message
\r
1020 if (strncasecmp($line, 'Content-Type: text/x-', 21) == 0) {
\r
1021 // ignore all text/x-... message
\r
1023 // text/x-msnmsgr-datacast => nudge, voice clip....
\r
1024 // text/x-mms-animemoticon => customized animemotion word
\r
1035 $this->debug_message("*** Ignoring SB data from $from_email: $line");
\r
1039 // we will ignore any p2p message after sending acknowledgement
\r
1041 $len = strlen($sMsg);
\r
1042 $this->debug_message("*** p2p message from $from_email, size $len");
\r
1043 // header = 48 bytes
\r
1044 // content >= 0 bytes
\r
1045 // footer = 4 bytes
\r
1046 // so it need to >= 52 bytes
\r
1047 /*if ($len < 52) {
\r
1048 $this->debug_message("*** p2p: size error, less than 52!");
\r
1051 $aDwords = @unpack("V12dword", $sMsg);
\r
1052 if (!is_array($aDwords)) {
\r
1053 $this->debug_message("*** p2p: header unpack error!");
\r
1056 $this->debug_message("*** p2p: dump received message:\n".$this->dump_binary($sMsg));
\r
1057 $hdr_SessionID = $aDwords['dword1'];
\r
1058 $hdr_Identifier = $aDwords['dword2'];
\r
1059 $hdr_DataOffsetLow = $aDwords['dword3'];
\r
1060 $hdr_DataOffsetHigh = $aDwords['dword4'];
\r
1061 $hdr_TotalDataSizeLow = $aDwords['dword5'];
\r
1062 $hdr_TotalDataSizeHigh = $aDwords['dword6'];
\r
1063 $hdr_MessageLength = $aDwords['dword7'];
\r
1064 $hdr_Flag = $aDwords['dword8'];
\r
1065 $hdr_AckID = $aDwords['dword9'];
\r
1066 $hdr_AckUID = $aDwords['dword10'];
\r
1067 $hdr_AckSizeLow = $aDwords['dword11'];
\r
1068 $hdr_AckSizeHigh = $aDwords['dword12'];
\r
1069 $this->debug_message("*** p2p: header SessionID = $hdr_SessionID");
\r
1070 $this->debug_message("*** p2p: header Inentifier = $hdr_Identifier");
\r
1071 $this->debug_message("*** p2p: header Data Offset Low = $hdr_DataOffsetLow");
\r
1072 $this->debug_message("*** p2p: header Data Offset High = $hdr_DataOffsetHigh");
\r
1073 $this->debug_message("*** p2p: header Total Data Size Low = $hdr_TotalDataSizeLow");
\r
1074 $this->debug_message("*** p2p: header Total Data Size High = $hdr_TotalDataSizeHigh");
\r
1075 $this->debug_message("*** p2p: header MessageLength = $hdr_MessageLength");
\r
1076 $this->debug_message("*** p2p: header Flag = $hdr_Flag");
\r
1077 $this->debug_message("*** p2p: header AckID = $hdr_AckID");
\r
1078 $this->debug_message("*** p2p: header AckUID = $hdr_AckUID");
\r
1079 $this->debug_message("*** p2p: header AckSize Low = $hdr_AckSizeLow");
\r
1080 $this->debug_message("*** p2p: header AckSize High = $hdr_AckSizeHigh");
\r
1081 if ($hdr_Flag == 2) {
\r
1082 //This is an ACK from SB ignore....
\r
1083 $this->debug_message("*** p2p: //This is an ACK from SB ignore....:\n");
\r
1086 $MsgBody = $this->linetoArray(substr($sMsg, 48, -4));
\r
1087 $this->debug_message("*** p2p: body".print_r($MsgBody, true));
\r
1088 if (($MsgBody['EUF-GUID']=='{A4268EEC-FEC5-49E5-95C3-F126696BDBF6}')&&($PictureFilePath=$this->GetPictureFilePath($MsgBody['Context']))) {
\r
1090 if ($this->sb_readln($socket) === false) break;
\r
1092 $this->debug_message("*** p2p: Inv hdr:\n".$this->dump_binary(substr($sMsg, 0, 48)));
\r
1093 preg_match('/{([0-9A-F\-]*)}/i', $MsgBody['Via'], $Matches);
\r
1094 $BranchGUID = $Matches[1];
\r
1095 //it's an invite to send a display picture.
\r
1096 $new_id = ~$hdr_Identifier;
\r
1098 "LLLLLLLLLLLL", $hdr_SessionID,
\r
1101 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1106 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh
\r
1108 $footer = pack("L", 0);
\r
1109 $message = "MIME-Version: 1.0\r\nContent-Type: application/x-msnmsgrp2p\r\nP2P-Dest: $from_email\r\n\r\n$hdr$footer";
\r
1110 $len = strlen($message);
\r
1111 $this->sb_writeln($socket, $id, "MSG $this->id D $len");
\r
1112 $this->sb_writedata($socket, $message);
\r
1113 $this->debug_message("*** p2p: send display picture acknowledgement for $hdr_SessionID");
\r
1114 $this->debug_message("*** p2p: Invite ACK message:\n".$this->dump_binary($message));
\r
1115 $this->sb_readln($socket); // Read ACK;
\r
1116 $this->debug_message("*** p2p: Invite ACK Hdr:\n".$this->dump_binary($hdr));
\r
1118 //Send 200 OK message
\r
1119 $MessageContent="SessionID: ".$MsgBody['SessionID']."\r\n\r\n".pack("C", 0);
\r
1121 "MSNSLP/1.0 200 OK\r\n".
\r
1122 "To: <msnmsgr:".$from_email.">\r\n".
\r
1123 "From: <msnmsgr:".$this->user.">\r\n".
\r
1124 "Via: ".$MsgBody['Via']."\r\n".
\r
1125 "CSeq: ".($MsgBody['CSeq']+1)."\r\n".
\r
1126 "Call-ID: ".$MsgBody['Call-ID']."\r\n".
\r
1127 "Max-Forwards: 0\r\n".
\r
1128 "Content-Type: application/x-msnmsgr-sessionreqbody\r\n".
\r
1129 "Content-Length: ".strlen($MessageContent)."\r\n\r\n".
\r
1131 $hdr_TotalDataSizeLow=strlen($MessagePayload);
\r
1132 $hdr_TotalDataSizeHigh=0;
\r
1134 "LLLLLLLLLLLL", $hdr_SessionID,
\r
1137 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1138 strlen($MessagePayload),
\r
1146 "MIME-Version: 1.0\r\n".
\r
1147 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1148 "P2P-Dest: $from_email\r\n\r\n$hdr$MessagePayload$footer";
\r
1149 $this->sb_writeln($socket, $id, "MSG $this->id D ".strlen($message));
\r
1150 $this->sb_writedata($socket, $message);
\r
1151 $this->debug_message("*** p2p: dump 200 ok message:\n".$this->dump_binary($message));
\r
1152 $this->sb_readln($socket); // Read ACK;
\r
1154 $this->debug_message("*** p2p: 200 ok:\n".$this->dump_binary($hdr));
\r
1155 // send data preparation message
\r
1156 // send 4 null bytes as data
\r
1157 $hdr_TotalDataSizeLow = 4;
\r
1158 $hdr_TotalDataSizeHigh = 0 ;
\r
1162 $MsgBody['SessionID'],
\r
1165 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1166 $hdr_TotalDataSizeLow,
\r
1173 "MIME-Version: 1.0\r\n".
\r
1174 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1175 "P2P-Dest: $from_email\r\n\r\n$hdr".pack('L', 0)."$footer";
\r
1176 $this->sb_writeln($socket, $id, "MSG $this->id D ".strlen($message));
\r
1177 $this->sb_writedata($socket, $message);
\r
1178 $this->debug_message("*** p2p: dump send Data preparation message:\n".$this->dump_binary($message));
\r
1179 $this->debug_message("*** p2p: Data Prepare Hdr:\n".$this->dump_binary($hdr));
\r
1180 $this->sb_readln($socket); // Read ACK;
\r
1182 // send Data Content..
\r
1183 $footer=pack('N',1);
\r
1185 $FileSize=filesize($PictureFilePath);
\r
1186 if ($hTitle=fopen($PictureFilePath,'rb')) {
\r
1189 while (!feof($hTitle)) {
\r
1190 $FileContent = fread($hTitle, 1024);
\r
1191 $FileContentSize = strlen($FileContent);
\r
1194 $MsgBody['SessionID'],
\r
1205 "MIME-Version: 1.0\r\n".
\r
1206 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1207 "P2P-Dest: $from_email\r\n\r\n$hdr$FileContent$footer";
\r
1208 $this->sb_writeln($socket, $id, "MSG $this->id D ".strlen($message));
\r
1209 $this->sb_writedata($socket, $message);
\r
1210 $this->debug_message("*** p2p: dump send Data Content message $Offset / $FileSize :\n".$this->dump_binary($message));
\r
1211 $this->debug_message("*** p2p: Data Content Hdr:\n".$this->dump_binary($hdr));
\r
1212 //$this->SB_readln($socket);//Read ACK;
\r
1213 $Offset += $FileContentSize;
\r
1218 $MessageContent="\r\n".pack("C", 0);
\r
1220 "BYE MSNMSGR:MSNSLP/1.0\r\n".
\r
1221 "To: <msnmsgr:$from_email>\r\n".
\r
1222 "From: <msnmsgr:".$this->user.">\r\n".
\r
1223 "Via: MSNSLP/1.0/TLP ;branch={".$BranchGUID."}\r\n".
\r
1225 "Call-ID: ".$MsgBody['Call-ID']."\r\n".
\r
1226 "Max-Forwards: 0\r\n".
\r
1227 "Content-Type: application/x-msnmsgr-sessionclosebody\r\n".
\r
1228 "Content-Length: ".strlen($MessageContent)."\r\n\r\n".$MessageContent;
\r
1229 $footer=pack('N',0);
\r
1230 $hdr_TotalDataSizeLow=strlen($MessagePayload);
\r
1231 $hdr_TotalDataSizeHigh=0;
\r
1233 $hdr = pack("LLLLLLLLLLLL",
\r
1237 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1244 "MIME-Version: 1.0\r\n".
\r
1245 "Content-Type: application/x-msnmsgrp2p\r\n".
\r
1246 "P2P-Dest: $from_email\r\n\r\n$hdr$MessagePayload$footer";
\r
1247 $this->sb_writeln($socket, $id, "MSG $id D ".strlen($message));
\r
1249 $this->sb_writedata($socket, $message);
\r
1250 $this->debug_message("*** p2p: dump send BYE message :\n".$this->dump_binary($message));
\r
1255 //if ($hdr_Flag == 2) {
\r
1256 // just send ACK...
\r
1257 // $this->sb_writeln($socket, $id, "ACK $id");
\r
1260 if ($hdr_SessionID == 4) {
\r
1262 $this->debug_message("*** p2p: ignore flag 4");
\r
1265 $finished = false;
\r
1266 if ($hdr_TotalDataSizeHigh == 0) {
\r
1267 // only 32 bites size
\r
1268 if (($hdr_MessageLength + $hdr_DataOffsetLow) == $hdr_TotalDataSizeLow)
\r
1272 // we won't accept any file transfer
\r
1273 // so I think we won't get any message size need to use 64 bits
\r
1274 // 64 bits size here, can't count directly...
\r
1275 $totalsize = base_convert(sprintf("%X%08X", $hdr_TotalDataSizeHigh, $hdr_TotalDataSizeLow), 16, 10);
\r
1276 $dataoffset = base_convert(sprintf("%X%08X", $hdr_DataOffsetHigh, $hdr_DataOffsetLow), 16, 10);
\r
1277 $messagelength = base_convert(sprintf("%X", $hdr_MessageLength), 16, 10);
\r
1278 $now_size = bcadd($dataoffset, $messagelength);
\r
1279 if (bccomp($now_size, $totalsize) >= 0)
\r
1283 // ignore not finished split packet
\r
1284 $this->debug_message("*** p2p: ignore split packet, not finished");
\r
1287 //$new_id = ~$hdr_Identifier;
\r
1290 $hdr = pack("LLLLLLLLLLLL", $hdr_SessionID,
\r
1293 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh,
\r
1298 $hdr_TotalDataSizeLow, $hdr_TotalDataSizeHigh);
\r
1299 $footer = pack("L", 0);
\r
1300 $message = "MIME-Version: 1.0\r\nContent-Type: application/x-msnmsgrp2p\r\nP2P-Dest: $from_email\r\n\r\n$hdr$footer";
\r
1301 $len = strlen($message);
\r
1302 $this->sb_writeln($socket, $id, "MSG $id D $len");
\r
1304 $this->sb_writedata($socket, $message);
\r
1305 $this->debug_message("*** p2p: send acknowledgement for $hdr_SessionID");
\r
1306 $this->debug_message("*** p2p: dump sent message:\n".$this->dump_binary($hdr.$footer));
\r
1310 $this->debug_message("*** MSG from $from_email: $sMsg");
\r
1311 $this->callHandler('IMin', array('sender' => $from_email, 'message' => $sMsg, 'network' => $network, 'offline' => false));
\r
1314 $this->debug_message("*** User $user is offline. Trying OIM.");
\r
1315 $session['offline'] = true;
\r
1318 if (is_numeric($code)) {
\r
1319 $this->error = "Error code: $code, please check the detail information from: http://msnpiki.msnfanatic.com/index.php/Reference:Error_List";
\r
1320 $this->debug_message("*** SB: $this->error");
\r
1328 * Checks for new data and calls appropriate methods
\r
1330 * This method is usually called in an infinite loop to keep checking for new data
\r
1334 public function receive() {
\r
1335 // First, get an array of sockets that have data that is ready to be read
\r
1337 $ready = $this->getSockets();
\r
1338 $numrdy = stream_select($ready, $w = NULL, $x = NULL, NULL);
\r
1340 // Now that we've waited for something, go through the $ready
\r
1341 // array and read appropriately
\r
1343 foreach ($ready as $socket) {
\r
1344 if ($socket == $this->NSfp) {
\r
1345 $this->nsReceive();
\r
1347 $this->sbReceive($socket);
\r
1353 * Switchboard related methods
\r
1357 * Send a request for a switchboard session
\r
1359 * @param string $to Target email for switchboard session
\r
1361 private function reqSBSession($to) {
\r
1362 $this->debug_message("*** Request SB for $to");
\r
1363 $this->ns_writeln("XFR $this->id SB");
\r
1365 // Add to the queue of those waiting for a switchboard session reponse
\r
1366 $this->switchBoardSessions[$to] = array(
\r
1370 'joined' => false,
\r
1371 'offline' => false,
\r
1372 'XFRReqTime' => time()
\r
1374 $this->waitingForXFR[] = &$this->switchBoardSessions[$to];
\r
1378 * Following an XFR or RNG, connect to the switchboard session
\r
1380 * @param string $mode Mode, either 'Active' (in the case of XFR) or 'Passive' (in the case of RNG)
\r
1381 * @param string $ip IP of Switchboard
\r
1382 * @param integer $port Port of Switchboard
\r
1383 * @param string $to User on other end of Switchboard
\r
1384 * @param array $param Array of parameters - 'cki', 'ticket', 'sid'
\r
1385 * @return boolean true if successful
\r
1387 private function connectToSBSession($mode, $ip, $port, $to, $param) {
\r
1388 $this->debug_message("*** SB: Trying to connect to switchboard server $ip:$port");
\r
1390 $socket = @fsockopen($ip, $port, $errno, $errstr, $this->timeout);
\r
1392 $this->debug_message("*** SB: Can't connect to $ip:$port, error => $errno, $errstr");
\r
1396 // Store the socket in the lookup array
\r
1397 $this->switchBoardSessionLookup[$to] = $socket;
\r
1399 // Store the socket in the sessions array
\r
1400 $this->switchBoardSessions[$to] = array(
\r
1402 'socket' => $socket,
\r
1404 'joined' => false,
\r
1405 'offline' => false,
\r
1406 'XFRReqTime' => time()
\r
1409 // Change the index of the session to the socket
\r
1410 $intsocket = (int) $socket;
\r
1411 $this->switchBoardSessions[$intsocket] = $this->switchBoardSessions[$to];
\r
1412 unset($this->switchBoardSessions[$to]);
\r
1414 $id = &$this->switchBoardSessions[$intsocket]['id'];
\r
1416 if ($mode == 'Active') {
\r
1417 $cki_code = $param['cki'];
\r
1419 // SB: >>> USR {id} {user} {cki}
\r
1420 $this->sb_writeln($socket, $id, "USR $id $this->user $cki_code");
\r
1423 $ticket = $param['ticket'];
\r
1424 $sid = $param['sid'];
\r
1426 // SB: >>> ANS {id} {user} {ticket} {session_id}
\r
1427 $this->sb_writeln($socket, $id, "ANS $id $this->user $ticket $sid");
\r
1432 * Called when we want to end a switchboard session
\r
1433 * or a switchboard session ends
\r
1435 * @param resource $socket Socket
\r
1436 * @param boolean $killsession Whether to delete the session
\r
1439 private function endSBSession($socket) {
\r
1440 if (!self::socketcheck($socket)) {
\r
1441 $this->sb_writeln($socket, $fake = 0, 'OUT');
\r
1445 // Unset session lookup value
\r
1446 $intsocket = (int) $socket;
\r
1447 unset($this->switchBoardSessionLookup[$this->switchBoardSessions[$intsocket]['to']]);
\r
1449 // Unset session itself
\r
1450 unset($this->switchBoardSessions[$intsocket]);
\r
1454 * Send a message via an existing SB session
\r
1456 * @param string $to Recipient for message
\r
1457 * @param string $message Message
\r
1458 * @return boolean true on success
\r
1460 private function sendMessageViaSB($to, $message) {
\r
1461 $socket = $this->switchBoardSessionLookup[$to];
\r
1462 if (self::socketcheck($socket)) {
\r
1466 $intsocket = (int) $socket;
\r
1467 if (!$this->switchBoardSessions[$intsocket]['joined']) {
\r
1468 // If our participant has not joined the session yet we can't message them!
\r
1472 $id = &$this->switchBoardSessions[$intsocket]['id'];
\r
1474 $aMessage = $this->getMessage($Message);
\r
1475 // CheckEmotion...
\r
1476 $MsnObjDefine = $this->GetMsnObjDefine($aMessage);
\r
1477 if ($MsnObjDefine !== '') {
\r
1478 $SendString = "MIME-Version: 1.0\r\nContent-Type: text/x-mms-emoticon\r\n\r\n$MsnObjDefine";
\r
1479 $len = strlen($SendString);
\r
1481 if ($this->sb_writeln($socket, $id, "MSG $id N $len") === false ||
\r
1482 $this->sb_writedata($socket, $SendString) === false) {
\r
1486 $len = strlen($aMessage);
\r
1488 if ($this->sb_writeln($socket, $id, "MSG $id N $len") === false ||
\r
1489 $this->sb_writedata($socket, $aMessage) === false) {
\r
1493 // Don't close the SB session, we might as well leave it open
\r
1498 * Send a message to a user on another network
\r
1500 * @param string $to Intended recipient
\r
1501 * @param string $message Message
\r
1502 * @param integer $network Network
\r
1505 private function sendOtherNetworkMessage($to, $message, $network) {
\r
1506 $message = $this->getMessage($message, $network);
\r
1507 $len = strlen($message);
\r
1508 if ($this->ns_writeln("UUM $this->id $to $network 1 $len") === false ||
\r
1509 $this->ns_writedata($Message) === false) {
\r
1512 $this->debug_message("*** Sent to $to (network: $network):\n$Message");
\r
1519 * @param string $to To address in form user@host.com(@network)
\r
1520 * where network is 1 for MSN, 32 for Yahoo
\r
1521 * and 'Offline' for offline messages
\r
1522 * @param string $message Message
\r
1524 public function sendMessage($to, $message) {
\r
1525 if ($message != '') {
\r
1526 list($name, $host, $network) = explode('@', $to);
\r
1527 $network = $network == '' ? 1 : $network;
\r
1528 $recipient = $name.$host;
\r
1530 if ($network === 1) {
\r
1531 if (!isset($this->switchBoardSessionLookup[$recipient]) && (!isset($this->switchBoardSessions[$recipient])
\r
1532 || time() - $this->switchBoardSessions[$recipient]['XFRReqTime'] > $this->XFRReqTimeout)) {
\r
1533 $this->debug_message("*** No existing SB session or request has timed out");
\r
1534 $this->reqSBSession($recipient);
\r
1537 $socket = $this->switchBoardSessionLookup[$to];
\r
1538 if ($this->switchBoardSessions[(int) $socket]['offline']) {
\r
1539 $this->debug_message("*** Contact ($recipient) offline, sending OIM");
\r
1540 $this->endSBSession($socket);
\r
1541 return $this->sendMessage($recipient.'@Offline', $message);
\r
1543 $this->debug_message("*** Attempting to send message to $recipient using existing SB session");
\r
1545 if ($this->sendMessageViaSB($recipient, $message)) {
\r
1546 $this->debug_message('*** Message sent successfully');
\r
1549 $this->debug_message('*** Message sending failed, requesting new SB session');
\r
1550 $this->reqSBSession($to);
\r
1555 } elseif ($network == 'Offline') {
\r
1557 //FIXME: ä¿®æ£Send OIM
\r
1559 $re_login = false;
\r
1560 for ($i = 0; $i < $this->oim_try; $i++) {
\r
1561 if (($oim_result = $this->sendOIM($recipient, $message, $lockkey)) === true) break;
\r
1562 if (is_array($oim_result) && $oim_result['challenge'] !== false) {
\r
1563 // need challenge lockkey
\r
1564 $this->debug_message("*** Need challenge code for ".$oim_result['challenge']);
\r
1565 $lockkey = $this->getChallenge($oim_result['challenge']);
\r
1568 if ($oim_result === false || $oim_result['auth_policy'] !== false) {
\r
1570 $this->debug_message("*** Can't send OIM, but we already re-logged-in again, so returning false");
\r
1573 $this->debug_message("*** Can't send OIM, maybe ticket expired, trying to login again");
\r
1575 // Maybe we need to re-login again
\r
1576 if (!$this->get_passport_ticket()) {
\r
1577 $this->debug_message("*** Can't re-login, something went wrong here, returning false");
\r
1580 $this->debug_message("*** Getting new ticket and trying again");
\r
1587 return $this->sendOtherNetworkMessage($recipient, $message, $network);
\r
1598 * Get OIM mail data
\r
1600 * @return string mail data or false on failure
\r
1602 function getOIM_maildata() {
\r
1603 preg_match('#t=(.*)&p=(.*)#', $this->ticket['web_ticket'], $matches);
\r
1604 if (count($matches) == 0) {
\r
1605 $this->debug_message('*** No web ticket?');
\r
1608 $t = htmlspecialchars($matches[1]);
\r
1609 $p = htmlspecialchars($matches[2]);
\r
1610 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
1611 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
1612 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
1613 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
\r
1615 <PassportCookie xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1621 <GetMetadata xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi" />
\r
1623 </soap:Envelope>';
\r
1625 $header_array = array(
\r
1626 'SOAPAction: '.self::OIM_MAILDATA_SOAP,
\r
1627 'Content-Type: text/xml; charset=utf-8',
\r
1628 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Messenger '.self::BUILDVER.')'
\r
1631 $this->debug_message('*** URL: '.self::OIM_MAILDATA_URL);
\r
1632 $this->debug_message("*** Sending SOAP:\n$XML");
\r
1633 $curl = curl_init();
\r
1634 curl_setopt($curl, CURLOPT_URL, self::OIM_MAILDATA_URL);
\r
1635 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
1636 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1637 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
1638 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
1639 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1640 curl_setopt($curl, CURLOPT_POST, 1);
\r
1641 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
1642 $data = curl_exec($curl);
\r
1643 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
1644 curl_close($curl);
\r
1645 $this->debug_message("*** Get Result:\n$data");
\r
1647 if ($http_code != 200) {
\r
1648 $this->debug_message("*** Could not get OIM maildata! http code: $http_code");
\r
1652 // <GetMetadataResponse xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">See #XML_Data</GetMetadataResponse>
\r
1653 preg_match('#<GetMetadataResponse([^>]*)>(.*)</GetMetadataResponse>#', $data, $matches);
\r
1654 if (count($matches) == 0) {
\r
1655 $this->debug_message('*** Could not get OIM maildata');
\r
1658 return $matches[2];
\r
1662 * Fetch OIM message with given id
\r
1664 * @param string $msgid
\r
1665 * @return string Message or false on failure
\r
1667 function getOIM_message($msgid) {
\r
1668 preg_match('#t=(.*)&p=(.*)#', $this->ticket['web_ticket'], $matches);
\r
1669 if (count($matches) == 0) {
\r
1670 $this->debug_message('*** No web ticket?');
\r
1673 $t = htmlspecialchars($matches[1]);
\r
1674 $p = htmlspecialchars($matches[2]);
\r
1677 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
1678 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
1679 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
1680 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
\r
1682 <PassportCookie xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1688 <GetMessage xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1689 <messageId>'.$msgid.'</messageId>
\r
1690 <alsoMarkAsRead>false</alsoMarkAsRead>
\r
1693 </soap:Envelope>';
\r
1695 $header_array = array(
\r
1696 'SOAPAction: '.self::OIM_READ_SOAP,
\r
1697 'Content-Type: text/xml; charset=utf-8',
\r
1698 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Messenger '.self::BUILDVER.')'
\r
1701 $this->debug_message('*** URL: '.self::OIM_READ_URL);
\r
1702 $this->debug_message("*** Sending SOAP:\n$XML");
\r
1703 $curl = curl_init();
\r
1704 curl_setopt($curl, CURLOPT_URL, self::OIM_READ_URL);
\r
1705 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
1706 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1707 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
1708 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
1709 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1710 curl_setopt($curl, CURLOPT_POST, 1);
\r
1711 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
1712 $data = curl_exec($curl);
\r
1713 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
1714 curl_close($curl);
\r
1715 $this->debug_message("*** Get Result:\n$data");
\r
1717 if ($http_code != 200) {
\r
1718 $this->debug_message("*** Can't get OIM: $msgid, http code = $http_code");
\r
1722 // why can't use preg_match('#<GetMessageResult>(.*)</GetMessageResult>#', $data, $matches)?
\r
1724 $start = strpos($data, '<GetMessageResult>');
\r
1725 $end = strpos($data, '</GetMessageResult>');
\r
1726 if ($start === false || $end === false || $start > $end) {
\r
1727 $this->debug_message("*** Can't get OIM: $msgid");
\r
1730 $lines = substr($data, $start + 18, $end - $start);
\r
1731 $aLines = @explode("\n", $lines);
\r
1735 foreach ($aLines as $line) {
\r
1736 $line = rtrim($line);
\r
1738 if ($line === '') {
\r
1744 // stop at empty lines
\r
1745 if ($line === '') break;
\r
1748 $sMsg = base64_decode($sOIM);
\r
1749 //$this->debug_message("*** we get OIM ($msgid): $sMsg");
\r
1752 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
1753 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
1754 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
1755 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
\r
1757 <PassportCookie xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1763 <DeleteMessages xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi">
\r
1765 <messageId>'.$msgid.'</messageId>
\r
1769 </soap:Envelope>';
\r
1771 $header_array = array(
\r
1772 'SOAPAction: '.self::OIM_DEL_SOAP,
\r
1773 'Content-Type: text/xml; charset=utf-8',
\r
1774 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Messenger '.self::BUILDVER.')'
\r
1777 $this->debug_message('*** URL: '.self::OIM_DEL_URL);
\r
1778 $this->debug_message("*** Sending SOAP:\n$XML");
\r
1779 $curl = curl_init();
\r
1780 curl_setopt($curl, CURLOPT_URL, self::OIM_DEL_URL);
\r
1781 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
1782 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1783 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
1784 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
1785 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1786 curl_setopt($curl, CURLOPT_POST, 1);
\r
1787 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
1788 $data = curl_exec($curl);
\r
1789 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
1790 curl_close($curl);
\r
1791 $this->debug_message("*** Get Result:\n$data");
\r
1793 if ($http_code != 200)
\r
1794 $this->debug_message("*** Could not delete OIM: $msgid, http code = $http_code");
\r
1796 $this->debug_message("*** OIM ($msgid) deleted");
\r
1801 * Send offline message
\r
1803 * @param string $to Intended recipient
\r
1804 * @param string $sMessage Message
\r
1805 * @param string $lockkey Lock key
\r
1806 * @return mixed true on success or error data
\r
1808 private function sendOIM($to, $sMessage, $lockkey) {
\r
1809 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
1810 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
1811 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
1812 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
\r
1814 <From memberName="'.$this->user.'"
\r
1815 friendlyName="=?utf-8?B?'.base64_encode($this->user).'?="
\r
1818 xmlns="http://messenger.msn.com/ws/2004/09/oim/"
\r
1819 msnpVer="'.self::PROTOCOL.'"
\r
1820 buildVer="'.self::BUILDVER.'"/>
\r
1821 <To memberName="'.$to.'" xmlns="http://messenger.msn.com/ws/2004/09/oim/"/>
\r
1822 <Ticket passport="'.htmlspecialchars($this->ticket['oim_ticket']).'"
\r
1823 appid="'.self::PROD_ID.'"
\r
1824 lockkey="'.$lockkey.'"
\r
1825 xmlns="http://messenger.msn.com/ws/2004/09/oim/"/>
\r
1826 <Sequence xmlns="http://schemas.xmlsoap.org/ws/2003/03/rm">
\r
1827 <Identifier xmlns="http://schemas.xmlsoap.org/ws/2002/07/utility">http://messenger.msn.com</Identifier>
\r
1828 <MessageNumber>1</MessageNumber>
\r
1832 <MessageType xmlns="http://messenger.msn.com/ws/2004/09/oim/">text</MessageType>
\r
1833 <Content xmlns="http://messenger.msn.com/ws/2004/09/oim/">MIME-Version: 1.0
\r
1834 Content-Type: text/plain; charset=UTF-8
\r
1835 Content-Transfer-Encoding: base64
\r
1836 X-OIM-Message-Type: OfflineMessage
\r
1837 X-OIM-Run-Id: {DAB68CFA-38C9-449B-945E-38AFA51E50A7}
\r
1838 X-OIM-Sequence-Num: 1
\r
1840 '.chunk_split(base64_encode($sMessage)).'
\r
1843 </soap:Envelope>';
\r
1845 $header_array = array(
\r
1846 'SOAPAction: '.self::OIM_SEND_SOAP,
\r
1847 'Content-Type: text/xml',
\r
1848 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Messenger '.self::BUILDVER.')'
\r
1851 $this->debug_message('*** URL: '.self::OIM_SEND_URL);
\r
1852 $this->debug_message("*** Sending SOAP:\n$XML");
\r
1853 $curl = curl_init();
\r
1854 curl_setopt($curl, CURLOPT_URL, self::OIM_SEND_URL);
\r
1855 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
1856 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1857 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
1858 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
1859 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1860 curl_setopt($curl, CURLOPT_POST, 1);
\r
1861 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
1862 $data = curl_exec($curl);
\r
1863 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
1864 curl_close($curl);
\r
1865 $this->debug_message("*** Get Result:\n$data");
\r
1867 if ($http_code == 200) {
\r
1868 $this->debug_message("*** OIM sent for $to");
\r
1872 $challenge = false;
\r
1873 $auth_policy = false;
\r
1874 // the lockkey is invalid, authenticated fail, we need challenge it again
\r
1875 // <LockKeyChallenge xmlns="http://messenger.msn.com/ws/2004/09/oim/">364763969</LockKeyChallenge>
\r
1876 preg_match("#<LockKeyChallenge (.*)>(.*)</LockKeyChallenge>#", $data, $matches);
\r
1877 if (count($matches) != 0) {
\r
1878 // yes, we get new LockKeyChallenge
\r
1879 $challenge = $matches[2];
\r
1880 $this->debug_message("*** OIM need new challenge ($challenge) for $to");
\r
1882 // auth policy error
\r
1883 // <RequiredAuthPolicy xmlns="http://messenger.msn.com/ws/2004/09/oim/">MBI_SSL</RequiredAuthPolicy>
\r
1884 preg_match("#<RequiredAuthPolicy (.*)>(.*)</RequiredAuthPolicy>#", $data, $matches);
\r
1885 if (count($matches) != 0) {
\r
1886 $auth_policy = $matches[2];
\r
1887 $this->debug_message("*** OIM need new auth policy ($auth_policy) for $to");
\r
1889 if ($auth_policy === false && $challenge === false) {
\r
1890 //<faultcode xmlns:q0="http://messenger.msn.com/ws/2004/09/oim/">q0:AuthenticationFailed</faultcode>
\r
1891 preg_match("#<faultcode (.*)>(.*)</faultcode>#", $data, $matches);
\r
1892 if (count($matches) == 0) {
\r
1893 // no error, we assume the OIM is sent
\r
1894 $this->debug_message("*** OIM sent for $to");
\r
1897 $err_code = $matches[2];
\r
1898 //<faultstring>Exception of type 'System.Web.Services.Protocols.SoapException' was thrown.</faultstring>
\r
1899 preg_match("#<faultstring>(.*)</faultstring>#", $data, $matches);
\r
1900 if (count($matches) > 0)
\r
1901 $err_msg = $matches[1];
\r
1904 $this->debug_message("*** OIM failed for $to");
\r
1905 $this->debug_message("*** OIM Error code: $err_code");
\r
1906 $this->debug_message("*** OIM Error Message: $err_msg");
\r
1909 return array('challenge' => $challenge, 'auth_policy' => $auth_policy);
\r
1913 * Contact / Membership list methods
\r
1917 * Fetch contact list
\r
1919 * @return boolean true on success
\r
1921 private function UpdateContacts() {
\r
1922 $ABApplicationHeaderArray = array(
\r
1923 'ABApplicationHeader' => array(
\r
1924 ':' => array('xmlns' => 'http://www.msn.com/webservices/AddressBook'),
\r
1925 'ApplicationId' => 'CFE80F9D-180F-4399-82AB-413F33A1FA11',
\r
1926 'IsMigration' => false,
\r
1927 'PartnerScenario' => 'ContactSave'
\r
1931 $ABApplicationHeader = new SoapHeader('http://www.msn.com/webservices/AddressBook', 'ABApplicationHeader', $this->Array2SoapVar($ABApplicationHeaderArray));
\r
1932 $ABFindAllArray = array(
\r
1933 'ABFindAll' => array(
\r
1934 ':' => array('xmlns'=>'http://www.msn.com/webservices/AddressBook'),
\r
1935 'abId' => '00000000-0000-0000-0000-000000000000',
\r
1936 'abView' => 'Full',
\r
1937 'lastChange' => '0001-01-01T00:00:00.0000000-08:00',
\r
1940 $ABFindAll = new SoapParam($this->Array2SoapVar($ABFindAllArray), 'ABFindAll');
\r
1941 $this->ABService->__setSoapHeaders(array($ABApplicationHeader, $this->ABAuthHeader));
\r
1942 $this->Contacts = array();
\r
1944 $this->debug_message('*** Updating Contacts...');
\r
1945 $Result = $this->ABService->ABFindAll($ABFindAll);
\r
1946 $this->debug_message("*** Result:\n".print_r($Result, true)."\n".$this->ABService->__getLastResponse());
\r
1947 foreach($Result->ABFindAllResult->contacts->Contact as $Contact)
\r
1948 $this->Contacts[$Contact->contactInfo->passportName] = $Contact;
\r
1949 } catch(Exception $e) {
\r
1950 $this->debug_message("*** Update Contacts Error \nRequest:".$this->ABService->__getLastRequest()."\nError:".$e->getMessage());
\r
1959 * @param string $email
\r
1960 * @param integer $network
\r
1961 * @param string $display
\r
1962 * @param boolean $sendADL
\r
1963 * @return boolean true on success
\r
1965 private function addContact($email, $network, $display = '', $sendADL = false) {
\r
1966 if ($network != 1) return true;
\r
1967 if (isset($this->Contacts[$email])) return true;
\r
1969 $ABContactAddArray = array(
\r
1970 'ABContactAdd' => array(
\r
1971 ':' => array('xmlns' => 'http://www.msn.com/webservices/AddressBook'),
\r
1972 'abId' => '00000000-0000-0000-0000-000000000000',
\r
1973 'contacts' => array(
\r
1974 'Contact' => array(
\r
1975 ':' => array('xmlns' => 'http://www.msn.com/webservices/AddressBook'),
\r
1976 'contactInfo' => array(
\r
1977 'contactType' => 'LivePending',
\r
1978 'passportName' => $email,
\r
1979 'isMessengerUser' => true,
\r
1980 'MessengerMemberInfo' => array(
\r
1981 'DisplayName' => $email
\r
1986 'options' => array(
\r
1987 'EnableAllowListManagement' => true
\r
1991 $ABContactAdd = new SoapParam($this->Array2SoapVar($ABContactAddArray), 'ABContactAdd');
\r
1993 $this->debug_message("*** Adding Contact $email...");
\r
1994 $this->ABService->ABContactAdd($ABContactAdd);
\r
1995 } catch(Exception $e) {
\r
1996 $this->debug_message("*** Add Contact Error \nRequest:".$this->ABService->__getLastRequest()."\nError:".$e->getMessage());
\r
1999 if ($sendADL && !feof($this->NSfp)) {
\r
2000 @list($u_name, $u_domain) = @explode('@', $email);
\r
2001 foreach (array('1', '2') as $l) {
\r
2002 $str = '<ml l="1"><d n="'.$u_domain.'"><c n="'.$u_name.'" l="'.$l.'" t="'.$network.'" /></d></ml>';
\r
2003 $len = strlen($str);
\r
2004 // NS: >>> ADL {id} {size}
\r
2005 $this->ns_writeln("ADL $this->id $len");
\r
2006 $this->ns_writedata($str);
\r
2009 $this->UpdateContacts();
\r
2014 * Remove contact from list
\r
2016 * @param integer $memberID
\r
2017 * @param string $email
\r
2018 * @param integer $network
\r
2019 * @param string $list
\r
2021 function delMemberFromList($memberID, $email, $network, $list) {
\r
2022 if ($network != 1 && $network != 32) return true;
\r
2023 if ($memberID === false) return true;
\r
2025 $ticket = htmlspecialchars($this->ticket['contact_ticket']);
\r
2026 if ($network == 1)
\r
2027 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2028 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2029 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2030 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2031 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2033 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2034 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2035 <IsMigration>false</IsMigration>
\r
2036 <PartnerScenario>ContactMsgrAPI</PartnerScenario>
\r
2037 </ABApplicationHeader>
\r
2038 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2039 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2040 <TicketToken>'.$ticket.'</TicketToken>
\r
2044 <DeleteMember xmlns="http://www.msn.com/webservices/AddressBook">
\r
2047 <Type>Messenger</Type>
\r
2048 <ForeignId></ForeignId>
\r
2052 <MemberRole>'.$list.'</MemberRole>
\r
2054 <Member xsi:type="PassportMember" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
\r
2055 <Type>Passport</Type>
\r
2056 <MembershipId>'.$memberID.'</MembershipId>
\r
2057 <State>Accepted</State>
\r
2064 </soap:Envelope>';
\r
2066 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2067 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2068 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2069 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2070 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2072 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2073 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2074 <IsMigration>false</IsMigration>
\r
2075 <PartnerScenario>ContactMsgrAPI</PartnerScenario>
\r
2076 </ABApplicationHeader>
\r
2077 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2078 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2079 <TicketToken>'.$ticket.'</TicketToken>
\r
2083 <DeleteMember xmlns="http://www.msn.com/webservices/AddressBook">
\r
2086 <Type>Messenger</Type>
\r
2087 <ForeignId></ForeignId>
\r
2091 <MemberRole>'.$list.'</MemberRole>
\r
2093 <Member xsi:type="EmailMember" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
\r
2094 <Type>Email</Type>
\r
2095 <MembershipId>'.$memberID.'</MembershipId>
\r
2096 <State>Accepted</State>
\r
2103 </soap:Envelope>';
\r
2105 $header_array = array(
\r
2106 'SOAPAction: '.self::DELMEMBER_SOAP,
\r
2107 'Content-Type: text/xml; charset=utf-8',
\r
2108 'User-Agent: MSN Explorer/9.0 (MSN 8.0; TmstmpExt)'
\r
2111 $this->debug_message('*** URL: '.self::DELMEMBER_URL);
\r
2112 $this->debug_message("*** Sending SOAP:\n$XML");
\r
2113 $curl = curl_init();
\r
2114 curl_setopt($curl, CURLOPT_URL, self::DELMEMBER_URL);
\r
2115 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
2116 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
2117 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
2118 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
2119 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
2120 curl_setopt($curl, CURLOPT_POST, 1);
\r
2121 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
2122 $data = curl_exec($curl);
\r
2123 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
2124 curl_close($curl);
\r
2125 $this->debug_message("*** Get Result:\n$data");
\r
2127 if ($http_code != 200) {
\r
2128 preg_match('#<faultcode>(.*)</faultcode><faultstring>(.*)</faultstring>#', $data, $matches);
\r
2129 if (count($matches) == 0) {
\r
2130 $this->debug_message("*** Could not delete member (network: $network) $email ($memberID) from $list list");
\r
2133 $faultcode = trim($matches[1]);
\r
2134 $faultstring = trim($matches[2]);
\r
2135 if (strcasecmp($faultcode, 'soap:Client') || stripos($faultstring, 'Member does not exist') === false) {
\r
2136 $this->debug_message("*** Could not delete member (network: $network) $email ($memberID) from $list list, error code: $faultcode, $faultstring");
\r
2139 $this->debug_message("*** Could not delete member (network: $network) $email ($memberID) from $list list, not present in list");
\r
2142 $this->debug_message("*** Member successfully deleted (network: $network) $email ($memberID) from $list list");
\r
2147 * Add contact to list
\r
2149 * @param string $email
\r
2150 * @param integer $network
\r
2151 * @param string $list
\r
2153 function addMemberToList($email, $network, $list) {
\r
2154 if ($network != 1 && $network != 32) return true;
\r
2155 $ticket = htmlspecialchars($this->ticket['contact_ticket']);
\r
2158 if ($network == 1)
\r
2159 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2160 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2161 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2162 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2163 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2165 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2166 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2167 <IsMigration>false</IsMigration>
\r
2168 <PartnerScenario>ContactMsgrAPI</PartnerScenario>
\r
2169 </ABApplicationHeader>
\r
2170 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2171 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2172 <TicketToken>'.$ticket.'</TicketToken>
\r
2176 <AddMember xmlns="http://www.msn.com/webservices/AddressBook">
\r
2179 <Type>Messenger</Type>
\r
2180 <ForeignId></ForeignId>
\r
2184 <MemberRole>'.$list.'</MemberRole>
\r
2186 <Member xsi:type="PassportMember" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
\r
2187 <Type>Passport</Type>
\r
2188 <State>Accepted</State>
\r
2189 <PassportName>'.$user.'</PassportName>
\r
2196 </soap:Envelope>';
\r
2198 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2199 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2200 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2201 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2202 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2204 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2205 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2206 <IsMigration>false</IsMigration>
\r
2207 <PartnerScenario>ContactMsgrAPI</PartnerScenario>
\r
2208 </ABApplicationHeader>
\r
2209 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2210 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2211 <TicketToken>'.$ticket.'</TicketToken>
\r
2215 <AddMember xmlns="http://www.msn.com/webservices/AddressBook">
\r
2218 <Type>Messenger</Type>
\r
2219 <ForeignId></ForeignId>
\r
2223 <MemberRole>'.$list.'</MemberRole>
\r
2225 <Member xsi:type="EmailMember" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
\r
2226 <Type>Email</Type>
\r
2227 <State>Accepted</State>
\r
2228 <Email>'.$user.'</Email>
\r
2231 <Name>MSN.IM.BuddyType</Name>
\r
2232 <Value>32:YAHOO</Value>
\r
2241 </soap:Envelope>';
\r
2242 $header_array = array(
\r
2243 'SOAPAction: '.self::ADDMEMBER_SOAP,
\r
2244 'Content-Type: text/xml; charset=utf-8',
\r
2245 'User-Agent: MSN Explorer/9.0 (MSN 8.0; TmstmpExt)'
\r
2248 $this->debug_message('*** URL: '.self::ADDMEMBER_URL);
\r
2249 $this->debug_message("*** Sending SOAP:\n$XML");
\r
2250 $curl = curl_init();
\r
2251 curl_setopt($curl, CURLOPT_URL, self::ADDMEMBER_URL);
\r
2252 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
2253 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
2254 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
2255 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
2256 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
2257 curl_setopt($curl, CURLOPT_POST, 1);
\r
2258 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
2259 $data = curl_exec($curl);
\r
2260 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
2261 curl_close($curl);
\r
2262 $this->debug_message("*** Get Result:\n$data");
\r
2264 if ($http_code != 200) {
\r
2265 preg_match('#<faultcode>(.*)</faultcode><faultstring>(.*)</faultstring>#', $data, $matches);
\r
2266 if (count($matches) == 0) {
\r
2267 $this->debug_message("*** Could not add member (network: $network) $email to $list list");
\r
2270 $faultcode = trim($matches[1]);
\r
2271 $faultstring = trim($matches[2]);
\r
2272 if (strcasecmp($faultcode, 'soap:Client') || stripos($faultstring, 'Member already exists') === false) {
\r
2273 $this->debug_message("*** Could not add member (network: $network) $email to $list list, error code: $faultcode, $faultstring");
\r
2276 $this->debug_message("*** Could not add member (network: $network) $email to $list list, already present");
\r
2279 $this->debug_message("*** Member successfully added (network: $network) $email to $list list");
\r
2284 * Get membership lists
\r
2286 * @param mixed $returnData Membership list or false on failure
\r
2288 function getMembershipList($returnData = false) {
\r
2289 $ticket = htmlspecialchars($this->ticket['contact_ticket']);
\r
2290 $XML = '<?xml version="1.0" encoding="utf-8"?>
\r
2291 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
\r
2292 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\r
2293 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
\r
2294 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
\r
2296 <ABApplicationHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2297 <ApplicationId>996CDE1E-AA53-4477-B943-2BE802EA6166</ApplicationId>
\r
2298 <IsMigration>false</IsMigration>
\r
2299 <PartnerScenario>Initial</PartnerScenario>
\r
2300 </ABApplicationHeader>
\r
2301 <ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
\r
2302 <ManagedGroupRequest>false</ManagedGroupRequest>
\r
2303 <TicketToken>'.$ticket.'</TicketToken>
\r
2307 <FindMembership xmlns="http://www.msn.com/webservices/AddressBook">
\r
2310 <ServiceType>Messenger</ServiceType>
\r
2311 <ServiceType>Invitation</ServiceType>
\r
2312 <ServiceType>SocialNetwork</ServiceType>
\r
2313 <ServiceType>Space</ServiceType>
\r
2314 <ServiceType>Profile</ServiceType>
\r
2319 </soap:Envelope>';
\r
2320 $header_array = array(
\r
2321 'SOAPAction: '.self::MEMBERSHIP_SOAP,
\r
2322 'Content-Type: text/xml; charset=utf-8',
\r
2323 'User-Agent: MSN Explorer/9.0 (MSN 8.0; TmstmpExt)'
\r
2325 $this->debug_message('*** URL: '.self::MEMBERSHIP_URL);
\r
2326 $this->debug_message("*** Sending SOAP:\n$XML");
\r
2327 $curl = curl_init();
\r
2328 curl_setopt($curl, CURLOPT_URL, self::MEMBERSHIP_URL);
\r
2329 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_array);
\r
2330 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
2331 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
2332 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
2333 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
2334 curl_setopt($curl, CURLOPT_POST, 1);
\r
2335 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
2336 $data = curl_exec($curl);
\r
2337 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
2338 curl_close($curl);
\r
2339 $this->debug_message("*** Get Result:\n$data");
\r
2341 if ($http_code != 200) return false;
\r
2343 $aMemberships = array();
\r
2345 //$this->debug_message("search p = $p");
\r
2346 $start = strpos($p, '<Membership>');
\r
2347 $end = strpos($p, '</Membership>');
\r
2348 if ($start === false || $end === false || $start > $end) break;
\r
2349 //$this->debug_message("start = $start, end = $end");
\r
2351 $sMembership = substr($p, $start, $end - $start);
\r
2352 $aMemberships[] = $sMembership;
\r
2353 //$this->debug_message("add sMembership = $sMembership");
\r
2354 $p = substr($p, $end);
\r
2356 //$this->debug_message("aMemberships = ".var_export($aMemberships, true));
\r
2358 $aContactList = array();
\r
2359 foreach ($aMemberships as $sMembership) {
\r
2360 //$this->debug_message("sMembership = $sMembership");
\r
2361 if (isset($matches)) unset($matches);
\r
2362 preg_match('#<MemberRole>(.*)</MemberRole>#', $sMembership, $matches);
\r
2363 if (count($matches) == 0) continue;
\r
2364 $sMemberRole = $matches[1];
\r
2365 //$this->debug_message("MemberRole = $sMemberRole");
\r
2366 if ($sMemberRole != 'Allow' && $sMemberRole != 'Reverse' && $sMemberRole != 'Pending') continue;
\r
2367 $p = $sMembership;
\r
2368 if (isset($aMembers)) unset($aMembers);
\r
2369 $aMembers = array();
\r
2371 //$this->debug_message("search p = $p");
\r
2372 $start = strpos($p, '<Member xsi:type="');
\r
2373 $end = strpos($p, '</Member>');
\r
2374 if ($start === false || $end === false || $start > $end) break;
\r
2375 //$this->debug_message("start = $start, end = $end");
\r
2377 $sMember = substr($p, $start, $end - $start);
\r
2378 $aMembers[] = $sMember;
\r
2379 //$this->debug_message("add sMember = $sMember");
\r
2380 $p = substr($p, $end);
\r
2382 //$this->debug_message("aMembers = ".var_export($aMembers, true));
\r
2383 foreach ($aMembers as $sMember) {
\r
2384 //$this->debug_message("sMember = $sMember");
\r
2385 if (isset($matches)) unset($matches);
\r
2386 preg_match('#<Member xsi\:type="([^"]*)">#', $sMember, $matches);
\r
2387 if (count($matches) == 0) continue;
\r
2388 $sMemberType = $matches[1];
\r
2389 //$this->debug_message("MemberType = $sMemberType");
\r
2391 preg_match('#<MembershipId>(.*)</MembershipId>#', $sMember, $matches);
\r
2392 if (count($matches) == 0) continue;
\r
2393 $id = $matches[1];
\r
2394 if ($sMemberType == 'PassportMember') {
\r
2395 if (strpos($sMember, '<Type>Passport</Type>') === false) continue;
\r
2397 preg_match('#<PassportName>(.*)</PassportName>#', $sMember, $matches);
\r
2399 else if ($sMemberType == 'EmailMember') {
\r
2400 if (strpos($sMember, '<Type>Email</Type>') === false) continue;
\r
2401 // Value is 32: or 32:YAHOO
\r
2402 preg_match('#<Annotation><Name>MSN.IM.BuddyType</Name><Value>(.*):(.*)</Value></Annotation>#', $sMember, $matches);
\r
2403 if (count($matches) == 0) continue;
\r
2404 if ($matches[1] != 32) continue;
\r
2406 preg_match('#<Email>(.*)</Email>#', $sMember, $matches);
\r
2408 if ($network == -1) continue;
\r
2409 if (count($matches) > 0) {
\r
2410 $email = $matches[1];
\r
2411 @list($u_name, $u_domain) = @explode('@', $email);
\r
2412 if ($u_domain == NULL) continue;
\r
2413 $aContactList[$u_domain][$u_name][$network][$sMemberRole] = $id;
\r
2414 $this->debug_message("*** Adding new contact (network: $network, status: $sMemberRole): $u_name@$u_domain ($id)");
\r
2418 return $aContactList;
\r
2422 * MsnObj related methods
\r
2427 * @param $FilePath 圖檔路徑
\r
2428 * @param $Type 檔案類型 3=>大é è²¼,2表情圖案
\r
2431 private function MsnObj($FilePath, $Type = 3) {
\r
2432 if (!($FileSize=filesize($FilePath))) return '';
\r
2433 $Location = md5($FilePath);
\r
2434 $Friendly = md5($FilePath.$Type);
\r
2435 if (isset($this->MsnObjMap[$Location])) return $this->MsnObjMap[$Location];
\r
2436 $sha1d = base64_encode(sha1(file_get_contents($FilePath), true));
\r
2437 $sha1c = base64_encode(sha1("Creator".$this->user."Size$FileSize"."Type$Type"."Location$Location"."Friendly".$Friendly."SHA1D$sha1d", true));
\r
2438 $this->MsnObjArray[$Location] = $FilePath;
\r
2439 $MsnObj = '<msnobj Creator="'.$this->user.'" Size="'.$FileSize.'" Type="'.$Type.'" Location="'.$Location.'" Friendly="'.$Friendly.'" SHA1D="'.$sha1d.'" SHA1C="'.$sha1c.'"/>';
\r
2440 $this->MsnObjMap[$Location] = $MsnObj;
\r
2441 $this->debug_message("*** p2p: addMsnObj $FilePath::$MsnObj\n");
\r
2445 private function GetPictureFilePath($Context) {
\r
2446 $MsnObj = base64_decode($Context);
\r
2447 if (preg_match('/location="(.*?)"/i', $MsnObj, $Match))
\r
2448 $location = $Match[1];
\r
2449 $this->debug_message("*** p2p: PictureFile[$location] ::All".print_r($this->MsnObjArray,true)."\n");
\r
2450 if ($location && isset($this->MsnObjArray[$location]))
\r
2451 return $this->MsnObjArray[$location];
\r
2455 private function GetMsnObjDefine($Message) {
\r
2456 $DefineString = '';
\r
2457 if (is_array($this->Emotions))
\r
2458 foreach ($this->Emotions as $Pattern => $FilePath) {
\r
2459 if (strpos($Message, $Pattern) !== false)
\r
2460 $DefineString .= "$Pattern\t".$this->MsnObj($FilePath, 2)."\t";
\r
2462 return $DefineString;
\r
2470 * Read data of specified size from NS socket
\r
2472 * @param integer $size Size to read
\r
2473 * @return string Data read
\r
2475 private function ns_readdata($size) {
\r
2478 while (!feof($this->NSfp)) {
\r
2479 $buf = @fread($this->NSfp, $size - $count);
\r
2481 $count += strlen($buf);
\r
2482 if ($count >= $size) break;
\r
2484 $this->debug_message("NS: data ($size/$count) <<<\n$data");
\r
2489 * Read line from the NS socket
\r
2491 * @return string Data read
\r
2493 private function ns_readln() {
\r
2494 $data = @fgets($this->NSfp, 4096);
\r
2495 if ($data !== false) {
\r
2496 $data = trim($data);
\r
2497 $this->debug_message("NS: <<< $data");
\r
2503 * Write line to NS socket
\r
2505 * Also increments id
\r
2507 * @param string $data Line to write to socket
\r
2508 * @return mixed Bytes written or false on failure
\r
2510 private function ns_writeln($data) {
\r
2511 $result = @fwrite($this->NSfp, $data."\r\n");
\r
2512 if ($result !== false) {
\r
2513 $this->debug_message("NS: >>> $data");
\r
2520 * Write data to NS socket
\r
2522 * @param string $data Data to write to socket
\r
2523 * @return mixed Bytes written or false on failure
\r
2525 private function ns_writedata($data) {
\r
2526 $result = @fwrite($this->NSfp, $data);
\r
2527 if ($result !== false) {
\r
2528 $this->debug_message("NS: >>> $data");
\r
2534 * Read data of specified size from given SB socket
\r
2536 * @param resource $socket SB socket
\r
2537 * @param integer $size Size to read
\r
2538 * @return string Data read
\r
2540 private function sb_readdata($socket, $size) {
\r
2543 while (!feof($socket)) {
\r
2544 $buf = @fread($socket, $size - $count);
\r
2546 $count += strlen($buf);
\r
2547 if ($count >= $size) break;
\r
2549 $this->debug_message("SB: data ($size/$count) <<<\n$data");
\r
2554 * Read line from given SB socket
\r
2556 * @param resource $socket SB Socket
\r
2557 * @return string Line read
\r
2559 private function sb_readln($socket) {
\r
2560 $data = @fgets($socket, 4096);
\r
2561 if ($data !== false) {
\r
2562 $data = trim($data);
\r
2563 $this->debug_message("SB: <<< $data");
\r
2569 * Write line to given SB socket
\r
2571 * Also increments id
\r
2573 * @param resource $socket SB socket
\r
2574 * @param integer $id Reference to SB id
\r
2575 * @param string $data Line to write
\r
2576 * @return mixed Bytes written or false on error
\r
2578 private function sb_writeln($socket, &$id, $data) {
\r
2579 $result = @fwrite($socket, $data."\r\n");
\r
2580 if ($result !== false) {
\r
2581 $this->debug_message("SB: >>> $data");
\r
2588 * Write data to given SB socket
\r
2590 * @param resource $socket SB socket
\r
2591 * @param $data Data to write to socket
\r
2592 * @return mixed Bytes written or false on error
\r
2594 private function sb_writedata($socket, $data) {
\r
2595 $result = @fwrite($socket, $data);
\r
2596 if ($result !== false) {
\r
2597 $this->debug_message("SB: >>> $data");
\r
2603 * Get all the sockets currently in use
\r
2605 * @return array Array of socket resources
\r
2607 public function getSockets() {
\r
2608 return array_merge(array($this->NSfp), $this->switchBoardSessionLookup);
\r
2612 * Checks socket for end of file
\r
2614 * @param resource $socket Socket to check
\r
2615 * @return boolean true if end of file (socket)
\r
2617 private static function socketcheck($socket){
\r
2618 $info = stream_get_meta_data($socket);
\r
2619 return $info['eof'];
\r
2623 * Key generation methods
\r
2626 private function derive_key($key, $magic) {
\r
2627 $hash1 = mhash(MHASH_SHA1, $magic, $key);
\r
2628 $hash2 = mhash(MHASH_SHA1, $hash1.$magic, $key);
\r
2629 $hash3 = mhash(MHASH_SHA1, $hash1, $key);
\r
2630 $hash4 = mhash(MHASH_SHA1, $hash3.$magic, $key);
\r
2631 return $hash2.substr($hash4, 0, 4);
\r
2634 private function generateLoginBLOB($key, $challenge) {
\r
2635 $key1 = base64_decode($key);
\r
2636 $key2 = $this->derive_key($key1, 'WS-SecureConversationSESSION KEY HASH');
\r
2637 $key3 = $this->derive_key($key1, 'WS-SecureConversationSESSION KEY ENCRYPTION');
\r
2639 // get hash of challenge using key2
\r
2640 $hash = mhash(MHASH_SHA1, $challenge, $key2);
\r
2642 // get 8 bytes random data
\r
2643 $iv = substr(base64_encode(rand(1000,9999).rand(1000,9999)), 2, 8);
\r
2645 $cipher = mcrypt_cbc(MCRYPT_3DES, $key3, $challenge."\x08\x08\x08\x08\x08\x08\x08\x08", MCRYPT_ENCRYPT, $iv);
\r
2647 $blob = pack('LLLLLLL', 28, 1, 0x6603, 0x8004, 8, 20, 72);
\r
2652 return base64_encode($blob);
\r
2656 * Generate challenge response
\r
2658 * @param string $code
\r
2659 * @return string challenge response code
\r
2661 private function getChallenge($code) {
\r
2663 // http://msnpiki.msnfanatic.com/index.php/MSNP11:Challenges
\r
2664 // Step 1: The MD5 Hash
\r
2665 $md5Hash = md5($code.self::PROD_KEY);
\r
2666 $aMD5 = @explode("\0", chunk_split($md5Hash, 8, "\0"));
\r
2667 for ($i = 0; $i < 4; $i++) {
\r
2668 $aMD5[$i] = implode('', array_reverse(@explode("\0", chunk_split($aMD5[$i], 2, "\0"))));
\r
2669 $aMD5[$i] = (0 + base_convert($aMD5[$i], 16, 10)) & 0x7FFFFFFF;
\r
2672 // Step 2: A new string
\r
2673 $chl_id = $code.self::PROD_ID;
\r
2674 $chl_id .= str_repeat('0', 8 - (strlen($chl_id) % 8));
\r
2676 $aID = @explode("\0", substr(chunk_split($chl_id, 4, "\0"), 0, -1));
\r
2677 for ($i = 0; $i < count($aID); $i++) {
\r
2678 $aID[$i] = implode('', array_reverse(@explode("\0", chunk_split($aID[$i], 1, "\0"))));
\r
2679 $aID[$i] = 0 + base_convert(bin2hex($aID[$i]), 16, 10);
\r
2682 // Step 3: The 64 bit key
\r
2683 $magic_num = 0x0E79A9C1;
\r
2684 $str7f = 0x7FFFFFFF;
\r
2687 for ($i = 0; $i < count($aID); $i += 2) {
\r
2689 $temp = bcmod(bcmul($magic_num, $temp), $str7f);
\r
2690 $temp = bcadd($temp, $high);
\r
2691 $temp = bcadd(bcmul($aMD5[0], $temp), $aMD5[1]);
\r
2692 $temp = bcmod($temp, $str7f);
\r
2694 $high = $aID[$i+1];
\r
2695 $high = bcmod(bcadd($high, $temp), $str7f);
\r
2696 $high = bcadd(bcmul($aMD5[2], $high), $aMD5[3]);
\r
2697 $high = bcmod($high, $str7f);
\r
2699 $low = bcadd(bcadd($low, $high), $temp);
\r
2702 $high = bcmod(bcadd($high, $aMD5[1]), $str7f);
\r
2703 $low = bcmod(bcadd($low, $aMD5[3]), $str7f);
\r
2705 $new_high = bcmul($high & 0xFF, 0x1000000);
\r
2706 $new_high = bcadd($new_high, bcmul($high & 0xFF00, 0x100));
\r
2707 $new_high = bcadd($new_high, bcdiv($high & 0xFF0000, 0x100));
\r
2708 $new_high = bcadd($new_high, bcdiv($high & 0xFF000000, 0x1000000));
\r
2709 // we need integer here
\r
2710 $high = 0+$new_high;
\r
2712 $new_low = bcmul($low & 0xFF, 0x1000000);
\r
2713 $new_low = bcadd($new_low, bcmul($low & 0xFF00, 0x100));
\r
2714 $new_low = bcadd($new_low, bcdiv($low & 0xFF0000, 0x100));
\r
2715 $new_low = bcadd($new_low, bcdiv($low & 0xFF000000, 0x1000000));
\r
2716 // we need integer here
\r
2717 $low = 0+$new_low;
\r
2719 // we just use 32 bits integer, don't need the key, just high/low
\r
2720 // $key = bcadd(bcmul($high, 0x100000000), $low);
\r
2722 // Step 4: Using the key
\r
2723 $md5Hash = md5($code.self::PROD_KEY);
\r
2724 $aHash = @explode("\0", chunk_split($md5Hash, 8, "\0"));
\r
2727 $hash .= sprintf("%08x", (0 + base_convert($aHash[0], 16, 10)) ^ $high);
\r
2728 $hash .= sprintf("%08x", (0 + base_convert($aHash[1], 16, 10)) ^ $low);
\r
2729 $hash .= sprintf("%08x", (0 + base_convert($aHash[2], 16, 10)) ^ $high);
\r
2730 $hash .= sprintf("%08x", (0 + base_convert($aHash[3], 16, 10)) ^ $low);
\r
2739 private function Array2SoapVar($Array, $ReturnSoapVarObj = true, $TypeName = null, $TypeNameSpace = null) {
\r
2740 $ArrayString = '';
\r
2741 foreach($Array as $Key => $Val) {
\r
2742 if ($Key{0} == ':') continue;
\r
2744 if (is_array($Val[':'])) {
\r
2745 foreach ($Val[':'] as $AttribName => $AttribVal)
\r
2746 $Attrib .= " $AttribName = '$AttribVal'";
\r
2748 if ($Key{0} == '!') {
\r
2749 //List Type Define
\r
2750 $Key = substr($Key,1);
\r
2751 foreach ($Val as $ListKey => $ListVal) {
\r
2752 if ($ListKey{0} == ':') continue;
\r
2753 if (is_array($ListVal)) $ListVal = $this->Array2SoapVar($ListVal, false);
\r
2754 elseif (is_bool($ListVal)) $ListVal = $ListVal ? 'true' : 'false';
\r
2755 $ArrayString .= "<$Key$Attrib>$ListVal</$Key>";
\r
2759 if (is_array($Val)) $Val = $this->Array2SoapVar($Val, false);
\r
2760 elseif (is_bool($Val)) $Val = $Val ? 'true' : 'false';
\r
2761 $ArrayString .= "<$Key$Attrib>$Val</$Key>";
\r
2763 if ($ReturnSoapVarObj) return new SoapVar($ArrayString, XSD_ANYXML, $TypeName, $TypeNameSpace);
\r
2764 return $ArrayString;
\r
2767 private function linetoArray($lines) {
\r
2768 $lines = str_replace("\r", '', $lines);
\r
2769 $lines = explode("\n", $lines);
\r
2770 foreach ($lines as $line) {
\r
2771 if (!isset($line{3})) continue;
\r
2772 list($Key, $Val) = explode(':', $line);
\r
2773 $Data[trim($Key)] = trim($Val);
\r
2779 * Get Passport ticket
\r
2781 * @param string $url URL string (Optional)
\r
2782 * @return mixed Array of tickets or false on failure
\r
2784 private function get_passport_ticket($url = '') {
\r
2785 $user = $this->user;
\r
2786 $password = htmlspecialchars($this->password);
\r
2789 $passport_url = self::PASSPORT_URL;
\r
2791 $passport_url = $url;
\r
2793 $XML = '<?xml version="1.0" encoding="UTF-8"?>
\r
2794 <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"
\r
2795 xmlns:wsse="http://schemas.xmlsoap.org/ws/2003/06/secext"
\r
2796 xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"
\r
2797 xmlns:wsp="http://schemas.xmlsoap.org/ws/2002/12/policy"
\r
2798 xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
\r
2799 xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/03/addressing"
\r
2800 xmlns:wssc="http://schemas.xmlsoap.org/ws/2004/04/sc"
\r
2801 xmlns:wst="http://schemas.xmlsoap.org/ws/2004/04/trust">
\r
2803 <ps:AuthInfo xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL" Id="PPAuthInfo">
\r
2804 <ps:HostingApp>{7108E71A-9926-4FCB-BCC9-9A9D3F32E423}</ps:HostingApp>
\r
2805 <ps:BinaryVersion>4</ps:BinaryVersion>
\r
2806 <ps:UIVersion>1</ps:UIVersion>
\r
2807 <ps:Cookies></ps:Cookies>
\r
2808 <ps:RequestParams>AQAAAAIAAABsYwQAAAAxMDMz</ps:RequestParams>
\r
2811 <wsse:UsernameToken Id="user">
\r
2812 <wsse:Username>'.$user.'</wsse:Username>
\r
2813 <wsse:Password>'.$password.'</wsse:Password>
\r
2814 </wsse:UsernameToken>
\r
2818 <ps:RequestMultipleSecurityTokens xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL" Id="RSTS">
\r
2819 <wst:RequestSecurityToken Id="RST0">
\r
2820 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2822 <wsa:EndpointReference>
\r
2823 <wsa:Address>http://Passport.NET/tb</wsa:Address>
\r
2824 </wsa:EndpointReference>
\r
2826 </wst:RequestSecurityToken>
\r
2827 <wst:RequestSecurityToken Id="RST1">
\r
2828 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2830 <wsa:EndpointReference>
\r
2831 <wsa:Address>messengerclear.live.com</wsa:Address>
\r
2832 </wsa:EndpointReference>
\r
2834 <wsse:PolicyReference URI="'.$this->passport_policy.'"></wsse:PolicyReference>
\r
2835 </wst:RequestSecurityToken>
\r
2836 <wst:RequestSecurityToken Id="RST2">
\r
2837 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2839 <wsa:EndpointReference>
\r
2840 <wsa:Address>messenger.msn.com</wsa:Address>
\r
2841 </wsa:EndpointReference>
\r
2843 <wsse:PolicyReference URI="?id=507"></wsse:PolicyReference>
\r
2844 </wst:RequestSecurityToken>
\r
2845 <wst:RequestSecurityToken Id="RST3">
\r
2846 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2848 <wsa:EndpointReference>
\r
2849 <wsa:Address>contacts.msn.com</wsa:Address>
\r
2850 </wsa:EndpointReference>
\r
2852 <wsse:PolicyReference URI="MBI"></wsse:PolicyReference>
\r
2853 </wst:RequestSecurityToken>
\r
2854 <wst:RequestSecurityToken Id="RST4">
\r
2855 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2857 <wsa:EndpointReference>
\r
2858 <wsa:Address>messengersecure.live.com</wsa:Address>
\r
2859 </wsa:EndpointReference>
\r
2861 <wsse:PolicyReference URI="MBI_SSL"></wsse:PolicyReference>
\r
2862 </wst:RequestSecurityToken>
\r
2863 <wst:RequestSecurityToken Id="RST5">
\r
2864 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2866 <wsa:EndpointReference>
\r
2867 <wsa:Address>spaces.live.com</wsa:Address>
\r
2868 </wsa:EndpointReference>
\r
2870 <wsse:PolicyReference URI="MBI"></wsse:PolicyReference>
\r
2871 </wst:RequestSecurityToken>
\r
2872 <wst:RequestSecurityToken Id="RST6">
\r
2873 <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>
\r
2875 <wsa:EndpointReference>
\r
2876 <wsa:Address>storage.msn.com</wsa:Address>
\r
2877 </wsa:EndpointReference>
\r
2879 <wsse:PolicyReference URI="MBI"></wsse:PolicyReference>
\r
2880 </wst:RequestSecurityToken>
\r
2881 </ps:RequestMultipleSecurityTokens>
\r
2885 $this->debug_message("*** URL: $passport_url");
\r
2886 $this->debug_message("*** Sending SOAP:\n$XML");
\r
2887 $curl = curl_init();
\r
2888 curl_setopt($curl, CURLOPT_URL, $passport_url);
\r
2889 if ($this->debug) curl_setopt($curl, CURLOPT_HEADER, 1);
\r
2890 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
2891 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
\r
2892 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
\r
2893 curl_setopt($curl, CURLOPT_POST, 1);
\r
2894 curl_setopt($curl, CURLOPT_POSTFIELDS, $XML);
\r
2895 $data = curl_exec($curl);
\r
2896 $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
\r
2897 curl_close($curl);
\r
2898 $this->debug_message("*** Get Result:\n$data");
\r
2900 if ($http_code != 200) {
\r
2901 // sometimes, redirect to another URL
\r
2903 //<faultcode>psf:Redirect</faultcode>
\r
2904 //<psf:redirectUrl>https://msnia.login.live.com/pp450/RST.srf</psf:redirectUrl>
\r
2905 //<faultstring>Authentication Failure</faultstring>
\r
2906 if (strpos($data, '<faultcode>psf:Redirect</faultcode>') === false) {
\r
2907 $this->debug_message("*** Could not get passport ticket! http code = $http_code");
\r
2910 preg_match("#<psf\:redirectUrl>(.*)</psf\:redirectUrl>#", $data, $matches);
\r
2911 if (count($matches) == 0) {
\r
2912 $this->debug_message('*** Redirected, but could not get redirect URL!');
\r
2915 $redirect_url = $matches[1];
\r
2916 if ($redirect_url == $passport_url) {
\r
2917 $this->debug_message('*** Redirected, but to same URL!');
\r
2920 $this->debug_message("*** Redirected to $redirect_url");
\r
2921 return $this->get_passport_ticket($redirect_url);
\r
2924 // sometimes, redirect to another URL, also return 200
\r
2926 //<faultcode>psf:Redirect</faultcode>
\r
2927 //<psf:redirectUrl>https://msnia.login.live.com/pp450/RST.srf</psf:redirectUrl>
\r
2928 //<faultstring>Authentication Failure</faultstring>
\r
2929 if (strpos($data, '<faultcode>psf:Redirect</faultcode>') !== false) {
\r
2930 preg_match("#<psf\:redirectUrl>(.*)</psf\:redirectUrl>#", $data, $matches);
\r
2931 if (count($matches) != 0) {
\r
2932 $redirect_url = $matches[1];
\r
2933 if ($redirect_url == $passport_url) {
\r
2934 $this->debug_message('*** Redirected, but to same URL!');
\r
2937 $this->debug_message("*** Redirected to $redirect_url");
\r
2938 return $this->get_passport_ticket($redirect_url);
\r
2942 // no Redurect faultcode or URL
\r
2943 // we should get the ticket here
\r
2945 // we need ticket and secret code
\r
2946 // RST1: messengerclear.live.com
\r
2947 // <wsse:BinarySecurityToken Id="Compact1">t=tick&p=</wsse:BinarySecurityToken>
\r
2948 // <wst:BinarySecret>binary secret</wst:BinarySecret>
\r
2949 // RST2: messenger.msn.com
\r
2950 // <wsse:BinarySecurityToken Id="PPToken2">t=tick</wsse:BinarySecurityToken>
\r
2951 // RST3: contacts.msn.com
\r
2952 // <wsse:BinarySecurityToken Id="Compact3">t=tick&p=</wsse:BinarySecurityToken>
\r
2953 // RST4: messengersecure.live.com
\r
2954 // <wsse:BinarySecurityToken Id="Compact4">t=tick&p=</wsse:BinarySecurityToken>
\r
2955 // RST5: spaces.live.com
\r
2956 // <wsse:BinarySecurityToken Id="Compact5">t=tick&p=</wsse:BinarySecurityToken>
\r
2957 // RST6: storage.msn.com
\r
2958 // <wsse:BinarySecurityToken Id="Compact6">t=tick&p=</wsse:BinarySecurityToken>
\r
2960 "<wsse\:BinarySecurityToken Id=\"Compact1\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2961 "<wst\:BinarySecret>(.*)</wst\:BinarySecret>(.*)".
\r
2962 "<wsse\:BinarySecurityToken Id=\"PPToken2\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2963 "<wsse\:BinarySecurityToken Id=\"Compact3\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2964 "<wsse\:BinarySecurityToken Id=\"Compact4\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2965 "<wsse\:BinarySecurityToken Id=\"Compact5\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2966 "<wsse\:BinarySecurityToken Id=\"Compact6\">(.*)</wsse\:BinarySecurityToken>(.*)".
\r
2970 // no ticket found!
\r
2971 if (count($matches) == 0) {
\r
2972 $this->debug_message('*** Could not get passport ticket!');
\r
2976 //$this->debug_message(var_export($matches, true));
\r
2977 // matches[0]: all data
\r
2978 // matches[1]: RST1 (messengerclear.live.com) ticket
\r
2979 // matches[2]: ...
\r
2980 // matches[3]: RST1 (messengerclear.live.com) binary secret
\r
2981 // matches[4]: ...
\r
2982 // matches[5]: RST2 (messenger.msn.com) ticket
\r
2983 // matches[6]: ...
\r
2984 // matches[7]: RST3 (contacts.msn.com) ticket
\r
2985 // matches[8]: ...
\r
2986 // matches[9]: RST4 (messengersecure.live.com) ticket
\r
2987 // matches[10]: ...
\r
2988 // matches[11]: RST5 (spaces.live.com) ticket
\r
2989 // matches[12]: ...
\r
2990 // matches[13]: RST6 (storage.live.com) ticket
\r
2991 // matches[14]: ...
\r
2994 // ticket => $matches[1]
\r
2995 // secret => $matches[3]
\r
2996 // web_ticket => $matches[5]
\r
2997 // contact_ticket => $matches[7]
\r
2998 // oim_ticket => $matches[9]
\r
2999 // space_ticket => $matches[11]
\r
3000 // storage_ticket => $matches[13]
\r
3002 // yes, we get ticket
\r
3003 $aTickets = array(
\r
3004 'ticket' => html_entity_decode($matches[1]),
\r
3005 'secret' => html_entity_decode($matches[3]),
\r
3006 'web_ticket' => html_entity_decode($matches[5]),
\r
3007 'contact_ticket' => html_entity_decode($matches[7]),
\r
3008 'oim_ticket' => html_entity_decode($matches[9]),
\r
3009 'space_ticket' => html_entity_decode($matches[11]),
\r
3010 'storage_ticket' => html_entity_decode($matches[13])
\r
3012 $this->ticket = $aTickets;
\r
3013 //$this->debug_message(var_export($aTickets, true));
\r
3014 $ABAuthHeaderArray = array(
\r
3015 'ABAuthHeader' => array(
\r
3016 ':' => array('xmlns' => 'http://www.msn.com/webservices/AddressBook'),
\r
3017 'ManagedGroupRequest' => false,
\r
3018 'TicketToken' => htmlspecialchars($this->ticket['contact_ticket']),
\r
3021 $this->ABAuthHeader = new SoapHeader('http://www.msn.com/webservices/AddressBook', 'ABAuthHeader', $this->Array2SoapVar($ABAuthHeaderArray));
\r
3026 * Generate the data to send a message
\r
3028 * @param string $sMessage Message
\r
3029 * @param integer $network Network
\r
3030 * @return string Message data
\r
3032 private function getMessage($sMessage, $network = 1) {
\r
3033 $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
3034 $msg_header_len = strlen($msg_header);
\r
3035 if ($network == 1)
\r
3036 $maxlen = self::MAX_MSN_MESSAGE_LEN - $msg_header_len;
\r
3038 $maxlen = self::MAX_YAHOO_MESSAGE_LEN - $msg_header_len;
\r
3039 $sMessage = str_replace("\r", '', $sMessage);
\r
3040 $msg = substr($sMessage, 0, $maxlen);
\r
3041 return $msg_header.$msg;
\r
3045 * Sleep for the given number of seconds
\r
3047 * @param integer $wait Number of seconds to sleep for
\r
3049 private function NSRetryWait($wait) {
\r
3050 $this->debug_message("*** Sleeping for $wait seconds before retrying");
\r
3055 * Sends a ping command
\r
3057 * Should be called about every 50 seconds
\r
3061 public function sendPing() {
\r
3063 $this->ns_writeln("PNG");
\r
3067 * Methods to add / call callbacks
\r
3071 * Calls User Handler
\r
3073 * Calls registered handler for a specific event.
\r
3075 * @param string $event Command (event) name (Rvous etc)
\r
3076 * @param array $data Data
\r
3077 * @see registerHandler
\r
3080 private function callHandler($event, $data = NULL) {
\r
3081 if (isset($this->myEventHandlers[$event])) {
\r
3082 if ($data !== NULL) {
\r
3083 call_user_func($this->myEventHandlers[$event], $data);
\r
3085 call_user_func($this->myEventHandlers[$event]);
\r
3091 * Registers a user handler
\r
3094 * IMIn, Pong, ConnectFailed, Reconnect,
\r
3095 * AddedToList, RemovedFromList
\r
3097 * @param string $event Event name
\r
3098 * @param string $handler User function to call
\r
3099 * @see callHandler
\r
3100 * @return boolean true if successful
\r
3102 public function registerHandler($event, $handler) {
\r
3103 if (is_callable($handler)) {
\r
3104 $this->myEventHandlers[$event] = $handler;
\r
3112 * Debugging methods
\r
3116 * Print message if debugging is enabled
\r
3118 * @param string $str Message to print
\r
3120 private function debug_message($str) {
\r
3121 if (!$this->debug) return;
\r
3126 * Dump binary data
\r
3128 * @param string $str Data string
\r
3129 * @return Binary data
\r
3131 private function dump_binary($str) {
\r
3135 $len = strlen($str);
\r
3136 for ($i = 0; $i < $len; $i++) {
\r
3137 if (($i % 16) == 0) {
\r
3138 if ($buf !== '') {
\r
3139 $buf .= "$h_str $a_str\n";
\r
3141 $buf .= sprintf("%04X:", $i);
\r
3145 $ch = ord($str[$i]);
\r
3149 $a_str .= chr($ch);
\r
3150 $h_str .= sprintf(" %02X", $ch);
\r
3152 if ($h_str !== '')
\r
3153 $buf .= "$h_str $a_str\n";
\r