Created
February 10, 2015 19:45
A simple GW2 chatlink class with support for IDs > 16 bit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Simple GW2 chatlink class with support for IDs > 16 bit | |
* | |
* @author Smiley <@codemasher> | |
* @license http://www.wtfpl.net/about/ WTFPL 2 | |
*/ | |
class Chatlink{ | |
/** | |
* @var array | |
* | |
* @link http://wiki.guildwars2.com/wiki/Chat_link_format | |
*/ | |
private $chatlink_types = [ | |
'coin' => 1, | |
'item' => 2, | |
'text' => 3, | |
'map' => 4, | |
'skill' => 7, | |
'trait' => 8, | |
'recipe' => 10, | |
'skin' => 11, | |
'outfit' => 12 | |
]; | |
/** | |
* @param int $type_id | |
* @param int $id | |
* | |
* @return string | |
* | |
* @author poke <@poke> | |
* @author Smiley <@codemasher> | |
* | |
* @link http://wiki.guildwars2.com/wiki/Widget:Game_link | |
*/ | |
public function encode($type_id, $id){ | |
$data = []; | |
while($id > 0){ | |
$data[] = $id & 255; | |
$id = $id >> 8; | |
} | |
while(count($data) < 4 || count($data) % 2 !== 0){ | |
$data[] = 0; | |
} | |
// add quantity if we are encoding an item | |
if($type_id === 2){ | |
array_unshift($data, 1); | |
} | |
array_unshift($data, $type_id); | |
// encode data | |
$chatlink = ''; | |
for($i = 0; $i < count($data); $i++){ | |
$chatlink .= chr($data[$i]); | |
} | |
return '[&'.base64_encode($chatlink).']'; | |
} | |
/** | |
* @param string $chatlink | |
* | |
* @return array|bool | |
* | |
* @author poke <@poke> | |
* @author Smiley <@codemasher> | |
* | |
* @link http://ideone.com/0RSpAA | |
*/ | |
public function decode($chatlink){ | |
if(preg_match('/\[&([a-z\d+\/]+=*)\]/i', $chatlink)){ | |
$data = []; | |
// decode base64 and read octets | |
foreach(str_split(base64_decode($chatlink)) as $char){ | |
$data[] = ord($char); | |
} | |
if(!in_array($data[0], $this->chatlink_types)){ | |
// invalid type | |
return false; | |
} | |
// items have the quantity first, so set an offset | |
$o = $data[0] === 2 ? 1 : 0; | |
// get id | |
$id = $data[3 + $o] << 16 | $data[2 + $o] << 8 | $data[1 + $o]; | |
// [id, type] | |
return [$id, $data[0]]; | |
} | |
// invalid chatlink | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment