/** * Decode a Punycode domain name to its Unicode counterpart * * @param string $input Domain name in Punycode * * @return string Unicode domain name */ public function decode($input) { if ($this->idnSupport === true) { return idn_to_utf8($input); } return self::$punycode->decode($input); }
/** * Get internationalized domain name * * @return null|false|string */ public function getIdn() { if (empty($this->domain)) { return null; } return @idn_to_utf8($this->domain); }
/** * Return true if a domain is a valid domain. * @link https://url.spec.whatwg.org/#valid-domain URL Standard * @param string $domain A UTF-8 string. * @return boolean */ public static function isValidDomain($domain) { $valid = mb_strlen($domain, 'UTF-8') <= self::PHP_IDN_HANDLEABLE_LENGTH; if ($valid) { $result = idn_to_ascii($domain, IDNA_USE_STD3_RULES | IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46); if (!is_string($result)) { $valid = false; } } if ($valid) { $domainNameLength = strlen($result); if ($domainNameLength < 1 || $domainNameLength > 253) { $valid = false; } } if ($valid) { foreach (explode('.', $result) as $label) { $labelLength = strlen($label); if ($labelLength < 1 || $labelLength > 63) { $valid = false; break; } } } if ($valid) { $result = idn_to_utf8($result, IDNA_USE_STD3_RULES, INTL_IDNA_VARIANT_UTS46, $idna_info); if ($idna_info['errors'] !== 0) { $valid = false; } } return $valid; }
public function filter(string $host) : string { $host = $this->validateHost($host); if ($this->isIdn) { $host = idn_to_utf8($host); } return $this->lower($host); }
public function create_identity($p) { $rcmail = rcmail::get_instance(); // prefs are set in create_user() if ($this->prefs) { if ($this->prefs['full_name']) { $p['record']['name'] = $this->prefs['full_name']; } if (($this->identities_level == 0 || $this->identities_level == 2) && $this->prefs['email_address']) { $p['record']['email'] = $this->prefs['email_address']; } if ($this->prefs['___signature___']) { $p['record']['signature'] = $this->prefs['___signature___']; } if ($this->prefs['reply_to']) { $p['record']['reply-to'] = $this->prefs['reply_to']; } if (($this->identities_level == 0 || $this->identities_level == 1) && isset($this->prefs['identities']) && $this->prefs['identities'] > 1) { for ($i = 1; $i < $this->prefs['identities']; $i++) { unset($ident_data); $ident_data = array('name' => '', 'email' => ''); // required data if ($this->prefs['full_name' . $i]) { $ident_data['name'] = $this->prefs['full_name' . $i]; } if ($this->identities_level == 0 && $this->prefs['email_address' . $i]) { $ident_data['email'] = $this->prefs['email_address' . $i]; } else { $ident_data['email'] = $p['record']['email']; } if ($this->prefs['reply_to' . $i]) { $ident_data['reply-to'] = $this->prefs['reply_to' . $i]; } if ($this->prefs['___sig' . $i . '___']) { $ident_data['signature'] = $this->prefs['___sig' . $i . '___']; } // insert identity $identid = $rcmail->user->insert_identity($ident_data); } } // copy address book $contacts = $rcmail->get_address_book(null, true); if ($contacts && count($this->abook)) { foreach ($this->abook as $rec) { // #1487096 handle multi-address and/or too long items $rec['email'] = array_shift(explode(';', $rec['email'])); if (check_email(idn_to_ascii($rec['email']))) { $rec['email'] = idn_to_utf8($rec['email']); $contacts->insert($rec, true); } } } // mark identity as complete for following hooks $p['complete'] = true; } return $p; }
/** * @param array|null $options * @return Domain[] */ public function findBy(array $options = null) { $domainObjects = []; $domainsList = $this->api->getList($options); foreach ($domainsList as $domainName) { $domain = idn_to_utf8($domainName->getFqdn()); $domainObjects[] = $this->factory->build($domain); } return $domainObjects; }
/** * Check email's domain * * @param $value * * @return bool */ public static function checkDomain($value) { static $regexData = ['pattern' => '/^(?:[0-9a-zA-Z](?:[\\-\\+\\_]*[0-9a-zA-Z])*\\.)+[0-9a-zA-Z](?:[\\-\\+\\_]*[0-9a-zA-Z])*$/u']; $explodedEmail = explode('@', $value); if (!isset($explodedEmail[1])) { return false; } $preparedDomain = idn_to_utf8($explodedEmail[1]); return stringValidator::byRegex($preparedDomain, $regexData); }
/** * Convert idn to utf8 format * * @param string $name * * @return string */ public static function convertIdnToUtf8Format($name) { if (empty($name)) { return; } if (!function_exists('idn_to_utf8')) { \DBG::msg('Idn is not supported in this system.'); } else { $name = idn_to_utf8($name); } return $name; }
/** */ public function __set($name, $value) { switch ($name) { case 'host': $value = ltrim($value, '@'); $this->_host = function_exists('idn_to_utf8') ? strtolower(idn_to_utf8($value)) : strtolower($value); break; case 'personal': $this->_personal = strlen($value) ? Horde_Mime::decode($value) : null; break; } }
public function test_invalidTld() { $tlds = [strval(bin2hex(openssl_random_pseudo_bytes(64))), '-tld-cannot-start-from-hypen', 'ąęśćżźł-there-is-no-such-idn', 'xn--fd67as67fdsa', '!@#-inavlid-chars-in-tld', 'no spaces in tld allowed', 'no--double--hypens--allowed']; if (count($tlds) === 0) { $this->markTestSkipped("Couldn't get TLD list"); } foreach ($tlds as $key => $tld) { if (strpos(mb_strtolower($tld), 'xn--') !== 0) { $tld = mb_strtolower($tld); } $this->assertFalse($this->isValid('test@example.' . idn_to_utf8($tld))); } }
/** * Generate List of Domains assigned to IPs * * @param iMSCP_pTemplate $tpl Template engine * @return void */ function listIPDomains($tpl) { $resellerId = $_SESSION['user_id']; $stmt = exec_query('SELECT reseller_ips FROM reseller_props WHERE reseller_id = ?', $resellerId); $data = $stmt->fetchRow(); $resellerIps = explode(';', substr($data['reseller_ips'], 0, -1)); $stmt = execute_query('SELECT ip_id, ip_number FROM server_ips WHERE ip_id IN (' . implode(',', $resellerIps) . ')'); while ($ip = $stmt->fetchRow(PDO::FETCH_ASSOC)) { $stmt2 = exec_query(' SELECT domain_name FROM domain INNER JOIN admin ON(admin_id = domain_admin_id) WHERE domain_ip_id = :ip_id AND created_by = :reseller_id UNION SELECT alias_name AS domain_name FROM domain_aliasses INNER JOIN domain USING(domain_id) INNER JOIN admin ON(admin_id = domain_admin_id) WHERE alias_ip_id = :ip_id AND created_by = :reseller_id ', array('ip_id' => $ip['ip_id'], 'reseller_id' => $resellerId)); $domainsCount = $stmt2->rowCount(); $tpl->assign(array('IP' => tohtml($ip['ip_number']), 'RECORD_COUNT' => tr('Total Domains') . ': ' . $domainsCount)); if ($domainsCount) { while ($data = $stmt2->fetchRow(PDO::FETCH_ASSOC)) { $tpl->assign('DOMAIN_NAME', tohtml(idn_to_utf8($data['domain_name']))); $tpl->parse('DOMAIN_ROW', '.domain_row'); } } else { $tpl->assign('DOMAIN_NAME', tr('No used yet')); $tpl->parse('DOMAIN_ROW', 'domain_row'); } $tpl->parse('IP_ROW', '.ip_row'); $tpl->assign('DOMAIN_ROW', ''); } }
/** * Validate a string only host * * @param string $str * * @return array */ protected function validateStringHost($str) { if (empty($str)) { return []; } $host = $this->lower($this->setIsAbsolute($str)); $raw_labels = explode('.', $host); $labels = array_map(function ($value) { return idn_to_ascii($value); }, $raw_labels); $this->assertValidHost($labels); $this->isIdn = $raw_labels !== $labels; return array_reverse(array_map(function ($label) { return idn_to_utf8($label); }, $labels)); }
public function setPattern($arr, $page) { list(, $alias, $toname, $host) = $this->splice($arr); $name = $orginalname = $toname . $host; if (extension_loaded('intl')) { // 国際化ドメイン対応 if (preg_match('/[^A-Za-z0-9.-]/', $host)) { $name = $toname . idn_to_ascii($host); } else { if (!$alias && strtolower(substr($host, 0, 4)) === 'xn--') { $orginalname = $toname . idn_to_utf8($host); } } } return parent::setParam($page, $name, '', 'mailto', $alias === '' ? $orginalname : $alias); }
/** * @return string */ function convert_idn_domain($domain) { // Get domain length $domain_length = strlen($domain); // Perform two idn operations, convert to ascii and convert to utf8 $idn_ascii_domain = idn_to_ascii($domain); // IDN utf8 domain detected, return converted domain. if ($domain_length != strlen($idn_ascii_domain)) { return $idn_ascii_domain; } $idn_utf8_domain = idn_to_utf8($domain); // IDN ascii domain detected, return converted domain. if ($domain_length != strlen($idn_utf8_domain)) { return $idn_utf8_domain; } return $domain; }
function init() { if (!empty(App::$primary->config['site']['domain'])) { $domain = App::$primary->config['site']['domain']; } else { $domain = implode('.', array_slice(explode('.', idn_to_utf8(INJI_DOMAIN_NAME)), -2)); } $alias = str_replace($domain, '', idn_to_utf8(INJI_DOMAIN_NAME)); $city = null; if ($alias) { $alias = str_replace('.', '', $alias); $city = Geography\City::get($alias, 'alias'); } if (!$city) { $city = Geography\City::get(1, 'default'); } Geography\City::$cur = $city; }
/** * Generate List of Domains assigned to IPs * * @param iMSCP_pTemplate $tpl * @return void */ function listIPDomains($tpl) { $stmt = execute_query('SELECT ip_id, ip_number FROM server_ips'); while ($ip = $stmt->fetchRow(PDO::FETCH_ASSOC)) { $stmt2 = exec_query(' SELECT t1.domain_name, t3.admin_name FROM domain AS t1 INNER JOIN admin AS t2 ON(t2.admin_id = t1.domain_admin_id) INNER JOIN admin as t3 ON(t3.admin_id = t2.created_by) WHERE t1.domain_ip_id = :ip_id UNION SELECT t1.alias_name AS domain_name, t4.admin_name FROM domain_aliasses AS t1 INNER JOIN domain AS t2 USING(domain_id) INNER JOIN admin AS t3 ON(admin_id = domain_admin_id) INNER JOIN admin AS t4 ON(t4.admin_id = t3.created_by) WHERE alias_ip_id = :ip_id ', array('ip_id' => $ip['ip_id'])); $domainsCount = $stmt2->rowCount(); $tpl->assign(array('IP' => tohtml($ip['ip_number']), 'RECORD_COUNT' => tr('Total Domains') . ': ' . $domainsCount)); if ($domainsCount) { while ($data = $stmt2->fetchRow(PDO::FETCH_ASSOC)) { $tpl->assign(array('DOMAIN_NAME' => tohtml(idn_to_utf8($data['domain_name'])), 'RESELLER_NAME' => tohtml($data['admin_name']))); $tpl->parse('DOMAIN_ROW', '.domain_row'); } } else { $tpl->assign('DOMAIN_NAME', tr('No used yet')); $tpl->parse('DOMAIN_ROW', 'domain_row'); } $tpl->parse('IP_ROW', '.ip_row'); $tpl->assign('DOMAIN_ROW', ''); } }
public static function toUTF8($uri, $convertHost = true) { $parseResult = static::parse($uri); if (null === $parseResult) { return null; } if ($convertHost === true && null !== $parseResult['host']) { $parseResult['host'] = idn_to_utf8($parseResult['host']); } if (null !== $parseResult['path']) { $utfPath = urldecode($parseResult['path']); $parseResult['path'] = mb_check_encoding($utfPath, 'UTF-8') ? $utfPath : $parseResult['path']; } if (null !== $parseResult['query']) { $utfQuery = urldecode($parseResult['query']); $parseResult['query'] = mb_check_encoding($utfQuery, 'UTF-8') ? $utfQuery : $parseResult['query']; } return static::build($parseResult); }
/** * Callback function when HTML page is rendered * We'll add an overlay box here. */ function render_page($p) { if ($_SESSION['plugin.newuserdialog'] && $p['template'] == 'mail') { $this->add_texts('localization'); $rcmail = rcmail::get_instance(); $identity = $rcmail->user->get_identity(); $identities_level = intval($rcmail->config->get('identities_level', 0)); // compose user-identity dialog $table = new html_table(array('cols' => 2)); $table->add('title', $this->gettext('name')); $table->add(null, html::tag('input', array('type' => 'text', 'name' => '_name', 'value' => $identity['name']))); $table->add('title', $this->gettext('email')); $table->add(null, html::tag('input', array('type' => 'text', 'name' => '_email', 'value' => idn_to_utf8($identity['email']), 'disabled' => $identities_level == 1 || $identities_level == 3))); // add overlay input box to html page $rcmail->output->add_footer(html::div(array('id' => 'newuseroverlay'), html::tag('form', array('action' => $rcmail->url('plugin.newusersave'), 'method' => 'post'), html::tag('h3', null, Q($this->gettext('identitydialogtitle'))) . html::p('hint', Q($this->gettext('identitydialoghint'))) . $table->show() . html::p(array('class' => 'formbuttons'), html::tag('input', array('type' => 'submit', 'class' => 'button mainaction', 'value' => $this->gettext('save'))))))); // disable keyboard events for messages list (#1486726) $rcmail->output->add_script("\$(document).ready(function () {\n rcmail.message_list.key_press = function(){};\n rcmail.message_list.key_down = function(){};\n \$('input[name=_name]').focus();\n });", 'foot'); $this->include_stylesheet('newuserdialog.css'); } }
/** * @param array $domains * @return array */ private function convertDomainListToUTF8(array $domains) { $data = array(); foreach ($domains as $domain => $result) { $domain = idn_to_utf8($domain); switch ($result) { case 'unavailable': $state = DomainState::STATE_UNAVAILABLE; break; case 'available': $state = DomainState::STATE_AVAILABLE; break; default: $state = DomainState::STATE_UNKNOWN; break; } $data[$domain] = $state; } return $data; }
public function init() { $callbacksData = filter_input(INPUT_POST, 'Callbacks', FILTER_REQUIRE_ARRAY); if (!empty($callbacksData)) { $callback = new \Callbacks\Callback(); $error = false; if (empty($callbacksData['text'])) { $error = true; Msg::add('Вы не написали текст отзыва'); } else { $callback->text = nl2br(htmlspecialchars($callbacksData['text'])); } if (empty($callbacksData['name'])) { $error = true; Msg::add('Вы не указали свое имя'); } else { $callback->name = htmlspecialchars($callbacksData['name']); } if (empty($callbacksData['phone'])) { $error = true; Msg::add('Вы не указали свой номер телефона'); } else { $callback->phone = htmlspecialchars($callbacksData['phone']); } $files = filter_var($_FILES['Callbacks'], FILTER_REQUIRE_ARRAY); if (!empty($files['tmp_name']['photo'])) { $callback->image_file_id = App::$cur->files->upload(['name' => $files['name']['photo'], 'tmp_name' => $files['tmp_name']['photo']]); } $callback->mail = htmlspecialchars($callbacksData['mail']); $callback->type_id = (int) $callbacksData['type']; if (!$error) { $callback->save(); if (!empty(App::$cur->config['site']['email'])) { $subject = 'Новый отзыв'; $text = 'Вы можете его посмотреть по этому адресу: <a href = "http://' . idn_to_utf8(INJI_DOMAIN_NAME) . '/admin/callbacks">http://' . idn_to_utf8(INJI_DOMAIN_NAME) . '/admin/callbacks</a>'; Tools::sendMail('noreply@' . INJI_DOMAIN_NAME, App::$cur->config['site']['email'], $subject, $text); } Tools::redirect('/', 'Ваш отзыв был получен и появится после обработки администратором', 'success'); } } }
public static function decodeHostName($encoded_hostname) { if (!preg_match('/[a-z\\d.-]{1,255}/', $encoded_hostname)) { return false; } if (function_exists('idn_to_utf8') && 0) { return idn_to_utf8($encoded_hostname); } $old_encoding = mb_internal_encoding(); mb_internal_encoding("UTF-8"); $pieces = explode(".", strtolower($encoded_hostname)); foreach ($pieces as $piece) { if (!preg_match('/^[a-z\\d][a-z\\d-]{0,62}$/i', $piece) || preg_match('/-$/', $piece)) { mb_internal_encoding($old_encoding); return $encoded_hostname; //invalid } $punycode_pieces[] = strpos($piece, "xn--") === 0 ? self::decode(substr($piece, 4)) : $piece; } mb_internal_encoding($old_encoding); return implode(".", $punycode_pieces); }
public function setPattern($arr, $page) { list(, $bracket, $alias, $scheme, $mail, $host, $uri) = $this->splice($arr); $this->has_bracket = substr($bracket, 0, 2) === '[['; $this->host = $host; if (extension_loaded('intl') && $host !== '/' && preg_match('/[^A-Za-z0-9.-]/', $host)) { $host = idn_to_ascii($host); } $name = $scheme . $mail . $host; // https?:/// -> $this->cont['ROOT_URL'] $name = preg_replace('#^(?:site:|https?:/)//#', ROOT_URI, $name) . $uri; if (!$alias) { // Punycode化されたドメインかを判別 $alias = extension_loaded('intl') && strtolower(substr($host, 0, 4)) === 'xn--' ? $scheme . $mail . idn_to_utf8($host) . $uri : $name; if (strpos($alias, '%') !== FALSE) { // TODO:mb_convert_encoding(): Unable to detect character encodingが出るので@を付加 $alias = @mb_convert_encoding(rawurldecode($alias), SOURCE_ENCODING, 'AUTO'); } } $this->alias = $alias; return parent::setParam($page, $name, null, $mail ? 'mailto' : 'url', $alias); }
/** * @throws Horde_Idna_Exception */ public static function decode($data) { switch ($backend = static::_getBackend()) { case 'INTL': case 'INTL_UTS46': $parts = explode('.', $data); foreach ($parts as &$part) { if (strpos($part, 'xn--') === 0) { switch ($backend) { case 'INTL': $part = idn_to_utf8($part); break; case 'INTL_UTS46': $part = idn_to_utf8($part, 0, INTL_IDNA_VARIANT_UTS46); break; } } } return implode('.', $parts); default: return $backend->decode($data); } }
if (!empty($_POST['partnerInvite']['name'])) { $title .= 'Ув. ' . htmlspecialchars($_POST['partnerInvite']['name']) . '. '; } if (!filter_var($_POST['partnerInvite']['email'], FILTER_VALIDATE_EMAIL)) { Tools::redirect(null, 'Вы ввели не корректный E-mail', 'danger'); } $title = \Users\User::$cur->name() . ' приглашает вас зарегистрироваться на сайте: ' . idn_to_utf8(INJI_DOMAIN_NAME); $inviteCode = Tools::randomString(60); $invite = new Users\User\Invite(); $invite->code = $inviteCode; $invite->type = 'UsersPartnerInvite'; $invite->user_id = \Users\User::$cur->id; $invite->limit = 1; $invite->save(); $text = "<h3>{$title}</h3>"; $text .= '<p>Чтобы принять приглашение, перейдите по <a href = "http://' . idn_to_utf8(INJI_DOMAIN_NAME) . '/users/registration?invite_code=' . $inviteCode . '">этой ссылке</a> и завершите процедуру регистрации</p>'; Tools::sendMail('noreply@' . INJI_DOMAIN_NAME, $_POST['partnerInvite']['email'], $title, $text); Tools::redirect(null, 'Приглашение было отправлено', 'success'); } $partners = App::$cur->users->getUserPartners(Users\User::$cur, 8); $usersSearch = []; foreach ($partners['users'] as $user) { $usersSearch[] = ['name' => $user->name(), 'id' => $user->pk(), 'translit' => Tools::translit($user->name())]; } if (!empty($_GET['info']['user_id']) && !empty($users[$_GET['info']['user_id']])) { } App::$cur->libs->loadLib('typeahead'); ?> <div class ='row'> <div class ='col-md-6'>
public static function idn_convert($input, $is_utf = false) { if ($at = strpos($input, '@')) { $user = substr($input, 0, $at); $domain = substr($input, $at + 1); } else { $domain = $input; } $domain = $is_utf ? idn_to_ascii($domain) : idn_to_utf8($domain); if ($domain === false) { return ''; } return $at ? $user . '@' . $domain : $domain; }
/** * Convert IDNA (punycode) domain into UTF-8 * * @param string $domain Domain to convert * @return string Converted string */ public static function decodeIdna($domain) { if (function_exists('idn_to_utf8')) { return idn_to_utf8($domain); } else { $decoder = new TrueBV\Punycode(); return $decoder->decode($domain); } }
public static function getUnicode($hostName) { return idn_to_utf8($hostName); }
/** * Implementation of PHP's FILTER_VALIDATE_URL with IDN support (will convert to valid) * * Example: http://трикотаж-леко.рф * * @param string $url * @param array $options Specify ('allowIDN' => false) to disallow internationalized domain names * @return string * */ protected function filterValidateURL($url, array $options) { $_url = $url; $url = filter_var($url, FILTER_VALIDATE_URL); if ($url !== false && strlen($url)) { return $url; } // if allowIDN was specifically set false, don't proceed further if (isset($options['allowIDN']) && !$options['allowIDN']) { return $url; } // if PHP doesn't support idn_* functions, we can't do anything further here if (!function_exists('idn_to_ascii') || !function_exists('idn_to_utf8')) { return $url; } // extract scheme if (strpos($_url, '//') !== false) { list($scheme, $_url) = explode('//', $_url, 2); $scheme .= '//'; } else { $scheme = ''; } // extract domain, and everything else (rest) if (strpos($_url, '/') > 0) { list($domain, $rest) = explode('/', $_url, 2); $rest = "/{$rest}"; } else { $domain = $_url; $rest = ''; } if (strpos($domain, '%') !== false) { // domain is URL encoded $domain = rawurldecode($domain); } // extract port, if present, and prepend to $rest if (strpos($domain, ':') !== false && preg_match('/^([^:]+):(\\d+)$/', $domain, $matches)) { $domain = $matches[1]; $rest = ":{$matches['2']}{$rest}"; } if ($this->nameFilter($domain, array('-', '.'), '_', false, 1024) === $domain) { // domain contains no extended characters $url = $scheme . $domain . $rest; $url = filter_var($url, FILTER_VALIDATE_URL); } else { // domain contains utf8 $domain = idn_to_ascii($domain); if ($domain === false || !strlen($domain)) { return ''; } $url = $scheme . $domain . $rest; $url = filter_var($url, FILTER_VALIDATE_URL); if (strlen($url)) { // convert back to utf8 domain $domain = idn_to_utf8($domain); if ($domain === false) { return ''; } $url = $scheme . $domain . $rest; } } return $url; }
public function postProcess($action, $httpVars, $params) { $type = $this->getFilteredOption("SHORTEN_TYPE"); if (empty($type)) { return; } $jsonData = json_decode($params["ob_output"], true); $elementId = -1; if ($jsonData != false) { $url = $jsonData["publiclet_link"]; $elementId = $jsonData["element_id"]; } else { $url = $params["ob_output"]; } switch (intval($type["shorten_type"])) { case 0: if (!isset($type["ADFLY_TYPE"]) || !isset($type["ADFLY_APIKEY"]) || !isset($type["ADFLY_UID"]) || !isset($type["ADFLY_DOMAIN"])) { print $url; $this->logError("Config", "adFly Shortener : you must set the api key!"); return; } $adfly_type = $type["ADFLY_TYPE"]; $adfly_api = $type["ADFLY_APIKEY"]; $adfly_uid = $type["ADFLY_UID"]; $adfly_dom = $type["ADFLY_DOMAIN"]; $adfly = 'http://api.adf.ly/api.php?key=' . $adfly_api . '&uid=' . $adfly_uid . '&advert_type=' . $adfly_type . '&domain=' . $adfly_dom . '&url=' . urlencode($url); $response = AJXP_Utils::getRemoteContent($adfly); $response = strip_tags($response, '<body>'); $response = strip_tags($response); if (isset($response)) { print $response; $this->updateMetaShort($httpVars["file"], $elementId, $response); } else { print $url; } break; case 1: if (!isset($type["BITLY_USER"]) || !isset($type["BITLY_APIKEY"])) { print $url; $this->logError("Config", "Bitly Shortener : you must drop the conf.shorten.bitly.inc file inside conf.php and set the login/api key!"); return; } $bitly_login = $type["BITLY_USER"]; $bitly_api = $type["BITLY_APIKEY"]; $format = 'json'; $version = '2.0.1'; $bitly = 'http://api.bit.ly/shorten?version=' . $version . '&longUrl=' . urlencode($url) . '&login='******'&apiKey=' . $bitly_api . '&format=' . $format; $response = AJXP_Utils::getRemoteContent($bitly); $json = json_decode($response, true); if (isset($json['results'][$url]['shortUrl'])) { print $json['results'][$url]['shortUrl']; $this->updateMetaShort($httpVars["file"], $elementId, $json['results'][$url]['shortUrl']); } else { print $url; } break; case 2: if (!isset($type["GOOGL_APIKEY"])) { print $url; $this->logError("Config", "Goo.gl Shortener : you must set the api key!"); return; } $data = array('longUrl' => $url, 'key' => $type["GOOGL_APIKEY"]); $options = array('http' => array('method' => 'POST', 'content' => json_encode($data), 'header' => "Content-Type: application/json\r\n" . "Accept: application/json\r\n")); $goourl = 'https://www.googleapis.com/urlshortener/v1/url'; $context = stream_context_create($options); $result = file_get_contents($goourl, false, $context); $json = (array) json_decode($result); if (isset($json['id'])) { print $json['id']; $this->updateMetaShort($httpVars["file"], $elementId, $json['id']); } else { print $url; } break; case 3: if (!isset($type["POST_APIKEY"])) { print $url; $this->logError("Config", "po.st Shortener : you must set the api key!"); return; } $post_api = $type["POST_APIKEY"]; $post = 'http://po.st/api/shorten?longUrl=' . urlencode($url) . '&apiKey=' . $post_api . '&format=txt'; $response = AJXP_Utils::getRemoteContent($post); if (isset($response)) { print $response; $this->updateMetaShort($httpVars["file"], $elementId, $response); } else { print $url; } break; case 4: if (!isset($type["YOURLS_DOMAIN"])) { print $url; $this->logError("Config", "yourls Shortener : you must set the domain name"); return; } if (!isset($type["YOURLS_APIKEY"])) { print $url; $this->logError("Config", "yourls Shortener : you must set the api key"); return; } $useidn = false; if (isset($type["YOURLS_USEIDN"])) { $useidn = $type["YOURLS_USEIDN"]; } $yourls_domain = $type["YOURLS_DOMAIN"]; $yourls_api = $type["YOURLS_APIKEY"]; $yourls = 'http://' . $yourls_domain . '/yourls-api.php?signature=' . $yourls_api . '&action=shorturl&format=simple&url=' . urlencode($url); $response = AJXP_Utils::getRemoteContent($yourls); if (isset($response)) { $shorturl = $response; if ($useidn) { // WARNING: idn_to_utf8 requires php-idn module. // WARNING: http_build_url requires php-pecl-http module. $purl = parse_url($shorturl); $purl['host'] = idn_to_utf8($purl['host']); $shorturl = http_build_url($purl); } print $shorturl; $this->updateMetaShort($httpVars["file"], $elementId, $shorturl); } else { print $url; } break; } }
public function shortener($url) { if (empty($this->yourls_domain) || empty($this->yourls_api)) { debug_event($this->name, 'YOURLS domain or api key missing', '3'); return false; } $shorturl = ''; $apiurl = 'http://' . $this->yourls_domain . '/yourls-api.php?signature=' . $this->yourls_api . '&action=shorturl&format=simple&url=' . urlencode($url); try { debug_event($this->name, 'YOURLS api call: ' . $apiurl, '5'); $request = Requests::get($apiurl); $shorturl = $request->body; if ($this->yourls_use_idn) { // WARNING: idn_to_utf8 requires php-idn module. // WARNING: http_build_url requires php-pecl-http module. $purl = parse_url($shorturl); $purl['host'] = idn_to_utf8($purl['host']); $shorturl = http_build_url($purl); } } catch (Exception $e) { debug_event($this->name, 'YOURLS api http exception: ' . $e->getMessage(), '1'); return false; } return $shorturl; }