function churl_reachability($churl_reachable, $url, $keyword = '') { global $ydb; preg_match('!^[a-zA-Z0-9\\+\\.-]+:(//)?!', $url, $matches); $protocol = isset($matches[0]) ? $matches[0] : ''; $different_protocols = array('http://', 'https://'); if ($protocol == '') { $protocol = 'http://'; $url = 'http://' . $url; } $check_url = in_array($protocol, $different_protocols); // Return to normal routine if non-http(s) protocol is valid if ($check_url == false) { return false; } // Check if the long URL is reachable $resURL = curl_init(); curl_setopt($resURL, CURLOPT_URL, $url); curl_setopt($resURL, CURLOPT_BINARYTRANSFER, 1); curl_setopt($resURL, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback'); curl_setopt($resURL, CURLOPT_FAILONERROR, 1); curl_exec($resURL); $intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE); curl_close($resURL); // Return error if the entered URL is unreachable if ($intReturnCode == '' || $intReturnCode == 404) { $return['status'] = 'fail'; $return['code'] = 'error:url'; $return['message'] = 'The entered URL is unreachable. Check the URL or try again later.'; $return['statusCode'] = 200; // regardless of result, this is still a valid request return yourls_apply_filter('add_new_link_fail_unreachable', $return, $url, $keyword, $title); } return false; }
/** * Init KSES globals if not already defined (by a plugin) * * @since 1.6 * */ function yourls_kses_init() { global $yourls_allowedentitynames, $yourls_allowedprotocols; if (!$yourls_allowedentitynames) { $yourls_allowedentitynames = yourls_apply_filter('kses_allowed_entities', yourls_kses_allowed_entities()); } if (!$yourls_allowedprotocols) { $yourls_allowedprotocols = yourls_apply_filter('kses_allowed_protocols', yourls_kses_allowed_protocols()); } /** See NOTE ABOUT GLOBALS ** if( ! $yourls_allowedtags_all ) { $yourls_allowedtags_all = yourls_kses_allowed_tags_all(); $yourls_allowedtags_all = array_map( '_yourls_add_global_attributes', $yourls_allowedtags_all ); $yourls_allowedtags_all = yourls_apply_filter( 'kses_allowed_tags_all', $yourls_allowedtags_all ); } else { // User defined: let's sanitize $yourls_allowedtags_all = yourls_kses_array_lc( $yourls_allowedtags_all ); } if( ! $yourls_allowedtags ) { $yourls_allowedtags = yourls_kses_allowed_tags(); $yourls_allowedtags = array_map( '_yourls_add_global_attributes', $yourls_allowedtags ); $yourls_allowedtags = yourls_apply_filter( 'kses_allowed_tags', $yourls_allowedtags ); } else { // User defined: let's sanitize $yourls_allowedtags = yourls_kses_array_lc( $yourls_allowedtags ); } /**/ }
/** * Return list of all shorturls associated to the same long URL. Returns NULL or array of keywords. * */ function yourls_get_duplicate_keywords($longurl) { yourls_deprecated_function(__FUNCTION__, '1.7', 'yourls_get_longurl_keywords'); if (!yourls_allow_duplicate_longurls()) { return NULL; } return yourls_apply_filter('get_duplicate_keywords', yourls_get_longurl_keywords($longurl), $longurl); }
function fix_long_url($url, $unsafe_url) { $search = array('%2520', '%2521', '%2522', '%2523', '%2524', '%2525', '%2526', '%2527', '%2528', '%2529', '%252A', '%252B', '%252C', '%252D', '%252E', '%252F', '%253A', '%253D', '%253F', '%255C', '%255F'); $replace = array('%20', '%21', '%22', '%23', '%24', '%25', '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', '%2D', '%2E', '%2F', '%3A', '%3D', '%3F', '%5C', '%5F'); $url = str_ireplace($search, $replace, $url); // Remove any trailing spaces from the long URL while (substr($url, -strlen('%20')) == '%20') { $url = preg_replace('/%20$/', '', $url); } return yourls_apply_filter('after_fix_long_url', $url, $unsafe_url); }
function allow_aliases() { yourls_do_action('pre_get_request'); // Ignore protocol & www. prefix $root = str_replace(array('https://', 'http://', 'https://www.', 'http://www.'), '', YOURLS_SITE); // Use the configured domain instead of $_SERVER['HTTP_HOST'] $root_host = parse_url(YOURLS_SITE); // Case insensitive comparison of the YOURLS root to match both http://Sho.rt/blah and http://sho.rt/blah $request = preg_replace("!{$root}/!i", '', $root_host['host'] . $_SERVER['REQUEST_URI'], 1); // Unless request looks like a full URL (ie request is a simple keyword) strip query string if (!preg_match("@^[a-zA-Z]+://.+@", $request)) { $request = current(explode('?', $request)); } return yourls_apply_filter('get_request', $request); }
function insensitive_get_keyword_infos($keyword, $use_cache = true) { global $ydb; $keyword = yourls_sanitize_string($keyword); yourls_do_action('pre_get_keyword', $keyword, $use_cache); if (isset($ydb->infos[$keyword]) && $use_cache == true) { return yourls_apply_filter('get_keyword_infos', $ydb->infos[$keyword], $keyword); } yourls_do_action('get_keyword_not_cached', $keyword); $table = YOURLS_DB_TABLE_URL; $infos = $ydb->get_row("SELECT * FROM `{$table}` WHERE LOWER(`keyword`) = LOWER('{$keyword}')"); if ($infos) { $infos = (array) $infos; $ydb->infos[$keyword] = $infos; } else { $ydb->infos[$keyword] = false; } return yourls_apply_filter('get_keyword_infos', $ydb->infos[$keyword], $keyword); }
function ozh_yourls_antispam_is_blacklisted($url) { $parsed = parse_url($url); if (!isset($parsed['host'])) { return yourls_apply_filter('ozh_yourls_antispam_malformed', 'malformed'); } // Remove www. from domain (but not from www.com) $parsed['host'] = preg_replace('/^www\\.(.+\\.)/i', '$1', $parsed['host']); // Major blacklists. There's a filter if you want to manipulate this. $blacklists = yourls_apply_filter('ozh_yourls_antispam_list', array('dbl.spamhaus.org', 'multi.surbl.org', 'black.uribl.com')); // Check against each blacklist, exit if blacklisted foreach ($blacklists as $blacklist) { $domain = $parsed['host'] . '.' . $blacklist . '.'; $record = @dns_get_record($domain); if ($record && count($record) > 0) { return yourls_apply_filter('ozh_yourls_antispam_blacklisted', true); } } // All clear, probably not spam return yourls_apply_filter('ozh_yourls_antispam_clean', false); }
/** * Send a filerable content type header * * @since 1.7 * @param string $type content type ('text/html', 'application/json', ...) * @return bool whether header was sent */ function yourls_content_type_header($type) { yourls_do_action('content_type_header', $type); if (!headers_sent()) { $charset = yourls_apply_filter('content_type_header_charset', 'utf-8'); header("Content-Type: {$type}; charset={$charset}"); return true; } return false; }
/** * PHP emulation of JS's encodeURI * * @link https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURI * @param $url * @return string */ function yourls_encodeURI($url) { // Decode URL all the way $result = yourls_rawurldecode_while_encoded($url); // Encode once $result = strtr(rawurlencode($result), array('%3B' => ';', '%2C' => ',', '%2F' => '/', '%3F' => '?', '%3A' => ':', '%40' => '@', '%26' => '&', '%3D' => '=', '%2B' => '+', '%24' => '$', '%21' => '!', '%2A' => '*', '%27' => '\'', '%28' => '(', '%29' => ')', '%23' => '#')); // @TODO: // Known limit: this will most likely break IDN URLs such as http://www.académie-française.fr/ // To fully support IDN URLs, advocate use of a plugin. return yourls_apply_filter('encodeURI', $result, $url); }
function yourls_http_user_agent() { return yourls_apply_filter('http_user_agent', 'YOURLS v' . YOURLS_VERSION . ' +http://yourls.org/ (running on ' . YOURLS_SITE . ')'); }
/** * Expand short url to long url * */ function yourls_api_expand($shorturl) { $keyword = str_replace(YOURLS_SITE . '/', '', $shorturl); // accept either 'http://ozh.in/abc' or 'abc' $keyword = yourls_sanitize_string($keyword); $longurl = yourls_get_keyword_longurl($keyword); if ($longurl) { $return = array('keyword' => $keyword, 'shorturl' => YOURLS_SITE . "/{$keyword}", 'longurl' => $longurl, 'simple' => $longurl, 'message' => 'success', 'statusCode' => 200); } else { $return = array('keyword' => $keyword, 'simple' => 'not found', 'message' => 'Error: short URL not found', 'errorCode' => 404); } return yourls_apply_filter('api_expand', $return, $shorturl); }
$url = $_REQUEST['url']; $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : ''; $title = isset($_REQUEST['title']) ? $_REQUEST['title'] : ''; $text = isset($_REQUEST['text']) ? $_REQUEST['text'] : ''; // Create short URL, receive array $return with various information $return = yourls_add_new_link($url, $keyword, $title); $shorturl = isset($return['shorturl']) ? $return['shorturl'] : ''; $message = isset($return['message']) ? $return['message'] : ''; $title = isset($return['title']) ? $return['title'] : ''; $status = isset($return['status']) ? $return['status'] : ''; // Stop here if bookmarklet with a JSON callback function ("instant" bookmarklets) if (isset($_GET['jsonp']) && $_GET['jsonp'] == 'yourls') { $short = $return['shorturl'] ? $return['shorturl'] : ''; $message = "Short URL (Ctrl+C to copy)"; header('Content-type: application/json'); echo yourls_apply_filter('bookmarklet_jsonp', "yourls_callback({'short_url':'{$short}','message':'{$message}'});"); die; } } // Part to be executed if FORM has been submitted if (isset($_REQUEST['url']) && $_REQUEST['url'] != 'http://') { // Display result message of short link creation if (isset($message)) { echo "<h2><center>{$message}</h2></center>"; } if ($status == 'success') { echo "<h3><center>Short: {$shorturl}</h3></center>"; // Include the Copy box and the Quick Share box // yourls_share_box( $url, $shorturl, $title, $text ); // Initialize clipboard -- requires js/share.js and js/jquery.zclip.min.js to be properly loaded in the <head> // echo "<script>init_clipboard();</script>\n";
function muAdminUrl($page = '') { $admin = YOURLS_SITE . '/user/plugins/multi-user/' . $page; return yourls_apply_filter('admin_url', $admin, $page); }
/** * Display the admin menu * */ function yourls_html_menu() { // Build menu links if (defined('YOURLS_USER')) { $logout_link = yourls_apply_filter('logout_link', sprintf(yourls__('Hello <strong>%s</strong>'), YOURLS_USER) . ' (<a href="?action=logout" title="' . yourls_esc_attr__('Logout') . '">' . yourls__('Logout') . '</a>)'); } else { $logout_link = yourls_apply_filter('logout_link', ''); } $help_link = yourls_apply_filter('help_link', '<a href="' . yourls_site_url(false) . '/readme.html">' . yourls__('Help') . '</a>'); $admin_links = array(); $admin_sublinks = array(); $admin_links['admin'] = array('url' => yourls_admin_url('index.php'), 'title' => yourls__('Go to the admin interface'), 'anchor' => yourls__('Admin interface')); if (yourls_is_admin()) { $admin_links['tools'] = array('url' => yourls_admin_url('tools.php'), 'anchor' => yourls__('Tools')); $admin_links['plugins'] = array('url' => yourls_admin_url('plugins.php'), 'anchor' => yourls__('Manage Plugins')); $admin_sublinks['plugins'] = yourls_list_plugin_admin_pages(); } $admin_links = yourls_apply_filter('admin_links', $admin_links); $admin_sublinks = yourls_apply_filter('admin_sublinks', $admin_sublinks); // Now output menu echo '<ul id="admin_menu">' . "\n"; if (yourls_is_private() && !empty($logout_link)) { echo '<li id="admin_menu_logout_link">' . $logout_link . '</li>'; } foreach ((array) $admin_links as $link => $ar) { if (isset($ar['url'])) { $anchor = isset($ar['anchor']) ? $ar['anchor'] : $link; $title = isset($ar['title']) ? 'title="' . $ar['title'] . '"' : ''; printf('<li id="admin_menu_%s_link" class="admin_menu_toplevel"><a href="%s" %s>%s</a>', $link, $ar['url'], $title, $anchor); } // Output submenu if any. TODO: clean up, too many code duplicated here if (isset($admin_sublinks[$link])) { echo "<ul>\n"; foreach ($admin_sublinks[$link] as $link => $ar) { if (isset($ar['url'])) { $anchor = isset($ar['anchor']) ? $ar['anchor'] : $link; $title = isset($ar['title']) ? 'title="' . $ar['title'] . '"' : ''; printf('<li id="admin_menu_%s_link" class="admin_menu_sublevel admin_menu_sublevel_%s"><a href="%s" %s>%s</a>', $link, $link, $ar['url'], $title, $anchor); } } echo "</ul>\n"; } } if (isset($help_link)) { echo '<li id="admin_menu_help_link">' . $help_link . '</li>'; } yourls_do_action('admin_menu'); echo "</ul>\n"; yourls_do_action('admin_notices'); yourls_do_action('admin_notice'); // because I never remember if it's 'notices' or 'notice' /* To display a notice: $message = "<div>OMG, dude, I mean!</div>" ); yourls_add_action( 'admin_notices', create_function( '', "echo '$message';" ) ); */ }
/** * Marks a function as deprecated and informs when it has been used. Stolen from WP. * * There is a hook deprecated_function that will be called that can be used * to get the backtrace up to what file and function called the deprecated * function. * * The current behavior is to trigger a user error if YOURLS_DEBUG is true. * * This function is to be used in every function that is deprecated. * * @since 1.6 * @uses yourls_do_action() Calls 'deprecated_function' and passes the function name, what to use instead, * and the version the function was deprecated in. * @uses yourls_apply_filter() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do * trigger or false to not trigger error. * * @param string $function The function that was called * @param string $version The version of WordPress that deprecated the function * @param string $replacement Optional. The function that should have been called */ function yourls_deprecated_function($function, $version, $replacement = null) { yourls_do_action('deprecated_function', $function, $replacement, $version); // Allow plugin to filter the output error trigger if (YOURLS_DEBUG && yourls_apply_filter('deprecated_function_trigger_error', true)) { if (!is_null($replacement)) { trigger_error(sprintf(yourls__('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement)); } else { trigger_error(sprintf(yourls__('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version)); } } }
/** * Loads a custom translation file (for a plugin, a theme, a public interface...) if locale is defined * * The .mo file should be named based on the domain with a dash, and then the locale exactly, * eg 'myplugin-pt_BR.mo' * * @since 1.6 * * @param string $domain Unique identifier (the "domain") for retrieving translated strings * @param string $path Full path to directory containing MO files. * @return mixed Returns nothing if locale undefined, otherwise return bool: true on success, false on failure */ function yourls_load_custom_textdomain($domain, $path) { $locale = yourls_apply_filter('load_custom_textdomain', yourls_get_locale(), $domain); if (!empty($locale)) { $mofile = rtrim($path, '/') . '/' . $domain . '-' . $locale . '.mo'; return yourls_load_textdomain($domain, $mofile); } }
/** * Store new cookie. No $user will delete the cookie. * */ function yourls_store_cookie($user = null) { if (!$user) { $pass = null; $time = time() - 3600; } else { global $yourls_user_passwords; if (isset($yourls_user_passwords[$user])) { $pass = $yourls_user_passwords[$user]; } else { die('Stealing cookies?'); // This should never happen } $time = time() + YOURLS_COOKIE_LIFE; } $domain = yourls_apply_filter('setcookie_domain', parse_url(YOURLS_SITE, 1)); $secure = yourls_apply_filter('setcookie_secure', yourls_is_ssl()); $httponly = yourls_apply_filter('setcookie_httponly', true); // Some browsers refuse to store localhost cookie if ($domain == 'localhost') { $domain = ''; } if (!headers_sent($filename, $linenum)) { // Set httponly if the php version is >= 5.2.0 if (version_compare(phpversion(), '5.2.0', 'ge')) { setcookie(yourls_cookie_name(), yourls_salt($user), $time, '/', $domain, $secure, $httponly); } else { setcookie(yourls_cookie_name(), yourls_salt($user), $time, '/', $domain, $secure); } } else { // For some reason cookies were not stored: action to be able to debug that yourls_do_action('setcookie_failed', $user); yourls_debug_log("Could not store cookie: headers already sent in {$filename} on line {$linenum}"); } }
/** * Checks and cleans a URL before printing it. Stolen from WP. * * A number of characters are removed from the URL. If the URL is for displaying * (the default behaviour) ampersands are also replaced. * * @since 1.6 * * @param string $url The URL to be cleaned. * @param string $context 'display' or something else. Use yourls_sanitize_url() for database or redirection usage. * @param array $protocols Optional. Array of allowed protocols, defaults to global $yourls_allowedprotocols * @return string The cleaned $url */ function yourls_esc_url($url, $context = 'display', $protocols = array()) { // make sure there's only one 'http://' at the beginning (prevents pasting a URL right after the default 'http://') $url = str_replace(array('http://*****:*****@$\\|*\'()\\x80-\\xff]|i', '', $url); // Previous regexp in YOURLS was '|[^a-z0-9-~+_.?\[\]\^#=!&;,/:%@$\|*`\'<>"()\\x80-\\xff\{\}]|i' // TODO: check if that was it too destructive $strip = array('%0d', '%0a', '%0D', '%0A'); $url = yourls_deep_replace($strip, $url); $url = str_replace(';//', '://', $url); // Replace ampersands and single quotes only when displaying. if ('display' == $context) { $url = yourls_kses_normalize_entities($url); $url = str_replace('&', '&', $url); $url = str_replace("'", ''', $url); } if (!is_array($protocols) or !$protocols) { global $yourls_allowedprotocols; $protocols = yourls_apply_filter('esc_url_protocols', $yourls_allowedprotocols); // Note: $yourls_allowedprotocols is also globally filterable in functions-kses.php/yourls_kses_init() } if (!yourls_is_allowed_protocol($url, $protocols)) { return ''; } // I didn't use KSES function kses_bad_protocol() because it doesn't work the way I liked (returns //blah from illegal://blah) $url = substr($url, 0, 1999); return yourls_apply_filter('esc_url', $url, $original_url, $context); }
function authmgr_user_has_role($username, $rolename) { return yourls_apply_filter(AUTHMGR_HASROLE, false, $username, $rolename); }
/** * Echoes an image tag of Google Charts line graph from array of values (eg 'number of clicks'). * * $legend1_list & legend2_list are values used for the 2 x-axis labels. $id is an HTML/JS id * */ function yourls_stats_line($values, $id = null) { yourls_do_action('pre_stats_line'); // if $id is null then assign a random string if ($id === null) { $id = uniqid('yourls_stats_line_'); } // If we have only 1 day of data, prepend a fake day with 0 hits for a prettier graph if (count($values) == 1) { array_unshift($values, 0); } // Keep only a subset of values to keep graph smooth $values = yourls_array_granularity($values, 30); $data = array_merge(array('Time' => 'Hits'), $values); $data = yourls_google_array_to_data_table($data); $options = array("legend" => "none", "pointSize" => "3", "theme" => "maximized", "curveType" => "function", "width" => 430, "height" => 220, "hAxis" => "{minTextSpacing: 80, maxTextLines: 1, maxAlternation: 1}", "vAxis" => "{minValue: -0.5, format: '#'}", "colors" => "['#2a85b3']"); $options = yourls_apply_filter('stats_line_options', $options); $lineChart = yourls_google_viz_code('LineChart', $data, $options, $id); echo yourls_apply_filter('stats_line', $lineChart, $values, $options, $id); }
/** * Return the URL of the directory a plugin */ function yourls_plugin_url($file) { $url = YOURLS_PLUGINURL . '/' . yourls_plugin_basename($file); if (yourls_is_ssl() or yourls_needs_ssl()) { $url = str_replace('http://', 'https://', $url); } return yourls_apply_filter('plugin_url', $url, $file); }
/** * Determine if we want to check for a newer YOURLS version (and check if applicable) * * Currently checks are performed every 24h and only when someone is visiting an admin page. * In the future (1.8?) maybe check with cronjob emulation instead. * * @since 1.7 * @return bool true if a check was needed and successfully performed, false otherwise */ function yourls_maybe_check_core_version() { // Allow plugins to short-circuit the whole function $pre = yourls_apply_filter('shunt_maybe_check_core_version', null); if (null !== $pre) { return $pre; } if (defined('YOURLS_NO_VERSION_CHECK') && YOURLS_NO_VERSION_CHECK) { return false; } if (!yourls_is_admin()) { return false; } $checks = yourls_get_option('core_version_checks'); /* We don't want to check if : - last_result is set (a previous check was performed) - and it was less than 24h ago (or less than 2h ago if it wasn't successful) - and version checked matched version running Otherwise, we want to check. */ if (!empty($checks->last_result) and ($checks->failed_attempts == 0 && time() - $checks->last_attempt < 24 * 3600 or $checks->failed_attempts > 0 && time() - $checks->last_attempt < 2 * 3600) and $checks->version_checked == YOURLS_VERSION) { return false; } // We want to check if there's a new version $new_check = yourls_check_core_version(); // Could not check for a new version, and we don't have ancient data if (false == $new_check && !isset($checks->last_result->latest)) { return false; } return true; }
/** * Create MySQL tables. Return array( 'success' => array of success strings, 'errors' => array of error strings ) * * @since 1.3 * @return array An array like array( 'success' => array of success strings, 'errors' => array of error strings ) */ function yourls_create_sql_tables() { // Allow plugins (most likely a custom db.php layer in user dir) to short-circuit the whole function $pre = yourls_apply_filter('shunt_yourls_create_sql_tables', null); // your filter function should return an array of ( 'success' => $success_msg, 'error' => $error_msg ), see below if (null !== $pre) { return $pre; } global $ydb; $error_msg = array(); $success_msg = array(); // Create Table Query $create_tables = array(); $create_tables[YOURLS_DB_TABLE_URL] = 'CREATE TABLE IF NOT EXISTS `' . YOURLS_DB_TABLE_URL . '` (' . '`keyword` varchar(200) BINARY NOT NULL,' . '`url` text BINARY NOT NULL,' . '`title` text CHARACTER SET utf8,' . '`timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,' . '`ip` VARCHAR(41) NOT NULL,' . '`clicks` INT(10) UNSIGNED NOT NULL,' . ' PRIMARY KEY (`keyword`),' . ' KEY `timestamp` (`timestamp`),' . ' KEY `ip` (`ip`)' . ');'; $create_tables[YOURLS_DB_TABLE_OPTIONS] = 'CREATE TABLE IF NOT EXISTS `' . YOURLS_DB_TABLE_OPTIONS . '` (' . '`option_id` bigint(20) unsigned NOT NULL auto_increment,' . '`option_name` varchar(64) NOT NULL default "",' . '`option_value` longtext NOT NULL,' . 'PRIMARY KEY (`option_id`,`option_name`),' . 'KEY `option_name` (`option_name`)' . ') AUTO_INCREMENT=1 ;'; $create_tables[YOURLS_DB_TABLE_LOG] = 'CREATE TABLE IF NOT EXISTS `' . YOURLS_DB_TABLE_LOG . '` (' . '`click_id` int(11) NOT NULL auto_increment,' . '`click_time` datetime NOT NULL,' . '`shorturl` varchar(200) BINARY NOT NULL,' . '`referrer` varchar(200) NOT NULL,' . '`user_agent` varchar(255) NOT NULL,' . '`ip_address` varchar(41) NOT NULL,' . '`country_code` char(2) NOT NULL,' . 'PRIMARY KEY (`click_id`),' . 'KEY `shorturl` (`shorturl`)' . ') AUTO_INCREMENT=1 ;'; $create_table_count = 0; $ydb->show_errors = true; // Create tables foreach ($create_tables as $table_name => $table_query) { $ydb->query($table_query); $create_success = $ydb->query("SHOW TABLES LIKE '{$table_name}'"); if ($create_success) { $create_table_count++; $success_msg[] = yourls_s("Table '%s' created.", $table_name); } else { $error_msg[] = yourls_s("Error creating table '%s'.", $table_name); } } // Initializes the option table if (!yourls_initialize_options()) { $error_msg[] = yourls__('Could not initialize options'); } // Insert sample links if (!yourls_insert_sample_links()) { $error_msg[] = yourls__('Could not insert sample short URLs'); } // Check results of operations if (sizeof($create_tables) == $create_table_count) { $success_msg[] = yourls__('YOURLS tables successfully created.'); } else { $error_msg[] = yourls__('Error creating YOURLS tables.'); } return array('success' => $success_msg, 'error' => $error_msg); }
function yourls_die($message = '', $title = '', $header_code = 200) { yourls_status_header($header_code); yourls_html_head(); yourls_html_logo(); echo yourls_apply_filter('die_title', "<h2>{$title}</h2>"); echo yourls_apply_filter('die_message', "<p>{$message}</p>"); yourls_do_action('yourls_die'); yourls_html_footer(); die; }
yourls_share_box('', '', '', '', '', '', true); } else { echo '<script type="text/javascript">$(document).ready(function(){ feedback( "' . $return['message'] . '", "' . $return['status'] . '"); init_clipboard(); });</script>'; } yourls_do_action('admin_page_before_table'); yourls_table_head(); if (!$is_bookmark) { $params = array('search' => $search, 'search_text' => $search_text, 'search_in' => $search_in, 'sort_by' => $sort_by, 'sort_order' => $sort_order, 'page' => $page, 'perpage' => $perpage, 'click_filter' => $click_filter, 'click_limit' => $click_limit, 'total_pages' => $total_pages, 'date_filter' => $date_filter, 'date_first' => $date_first, 'date_second' => $date_second); yourls_html_tfooter($params); } yourls_table_tbody_start(); // Main Query $where = yourls_apply_filter('admin_list_where', $where); $url_results = $ydb->get_results("SELECT * FROM `{$table_url}` WHERE 1=1 {$where} ORDER BY `{$sort_by}` {$sort_order} LIMIT {$offset}, {$perpage};"); $found_rows = false; if ($url_results) { $found_rows = true; foreach ($url_results as $url_result) { $keyword = yourls_sanitize_string($url_result->keyword); $timestamp = strtotime($url_result->timestamp); $url = stripslashes($url_result->url); $ip = $url_result->ip; $title = $url_result->title ? $url_result->title : ''; $clicks = $url_result->clicks; echo yourls_table_add_row($keyword, $url, $title, $ip, $clicks, $timestamp); } } $display = $found_rows ? 'display:none' : '';
/* * YOURLS API * * Note about translation : this file should NOT be translation ready * API messages and returns are supposed to be programmatically tested, so default English is expected * */ define('YOURLS_API', true); require_once dirname(__FILE__) . '/includes/load-yourls.php'; yourls_maybe_require_auth(); $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null; yourls_do_action('api', $action); // Define standard API actions $api_actions = array('shorturl' => 'yourls_api_action_shorturl', 'stats' => 'yourls_api_action_stats', 'db-stats' => 'yourls_api_action_db_stats', 'url-stats' => 'yourls_api_action_url_stats', 'expand' => 'yourls_api_action_expand', 'version' => 'yourls_api_action_version'); $api_actions = yourls_apply_filters('api_actions', $api_actions); // Register API actions foreach ((array) $api_actions as $_action => $_callback) { yourls_add_filter('api_action_' . $_action, $_callback, 99); } // Try requested API method. Properly registered actions should return an array. $return = yourls_apply_filter('api_action_' . $action, false); if (false === $return) { $return = array('errorCode' => 400, 'message' => 'Unknown or missing "action" parameter', 'simple' => 'Unknown or missing "action" parameter'); } if (isset($_REQUEST['callback'])) { $return['callback'] = $_REQUEST['callback']; } $format = isset($_REQUEST['format']) ? $_REQUEST['format'] : 'xml'; yourls_api_output($format, $return); die;
// If the $last_24h doesn't have all the hours, insert missing hours with value 0 $last_24h[$h] = array_key_exists($h, $_last_24h) ? $_last_24h[$h] : 0; } unset($_last_24h); // *** Queries all done, phew *** // Filter all this junk if applicable. Be warned, some are possibly huge datasets. $referrers = yourls_apply_filter('pre_yourls_info_referrers', $referrers); $referrer_sort = yourls_apply_filter('pre_yourls_info_referrer_sort', $referrer_sort); $direct = yourls_apply_filter('pre_yourls_info_direct', $direct); $notdirect = yourls_apply_filter('pre_yourls_info_notdirect', $notdirect); $dates = yourls_apply_filter('pre_yourls_info_dates', $dates); $list_of_days = yourls_apply_filter('pre_yourls_info_list_of_days', $list_of_days); $list_of_months = yourls_apply_filter('pre_yourls_info_list_of_months', $list_of_months); $list_of_years = yourls_apply_filter('pre_yourls_info_list_of_years', $list_of_years); $last_24h = yourls_apply_filter('pre_yourls_info_last_24h', $last_24h); $countries = yourls_apply_filter('pre_yourls_info_countries', $countries); // I can haz debug data /** echo "<pre>"; echo "referrers: "; print_r( $referrers ); echo "referrer sort: "; print_r( $referrer_sort ); echo "direct: $direct\n"; echo "notdirect: $notdirect\n"; echo "dates: "; print_r( $dates ); echo "list of days: "; print_r( $list_of_days ); echo "list_of_months: "; print_r( $list_of_months ); echo "list_of_years: "; print_r( $list_of_years ); echo "last_24h: "; print_r( $last_24h ); echo "countries: "; print_r( $countries ); die(); /**/
/** * Get relative URL (eg 'abc' from 'http://sho.rt/abc') * * Treat indifferently http & https. If a URL isn't relative to the YOURLS install, return it as is * or return empty string if $strict is true * * @since 1.6 * @param string $url URL to relativize * @param bool $strict if true and if URL isn't relative to YOURLS install, return empty string * @return string URL */ function yourls_get_relative_url($url, $strict = true) { $url = yourls_sanitize_url($url); // Remove protocols to make it easier $noproto_url = str_replace('https:', 'http:', $url); $noproto_site = str_replace('https:', 'http:', YOURLS_SITE); // Trim URL from YOURLS root URL : if no modification made, URL wasn't relative $_url = str_replace($noproto_site . '/', '', $noproto_url); if ($_url == $noproto_url) { $_url = $strict ? '' : $url; } return yourls_apply_filter('get_relative_url', $_url, $url); }
/** * Return true if DB server is responding * * This function is supposed to be called right after yourls_get_all_options() has fired. It is not designed (yet) to * check for a responding server after several successful operation to check if the server has gone MIA * * @since 1.7.1 */ function yourls_is_db_alive() { global $ydb; $alive = false; switch ($ydb->DB_driver) { case 'pdo': $alive = isset($ydb->dbh); break; case 'mysql': $alive = isset($ydb->dbh) && false !== $ydb->dbh; break; case 'mysqli': $alive = null == mysqli_connect_error(); break; // Custom DB driver & class : delegate check // Custom DB driver & class : delegate check default: $alive = yourls_apply_filter('is_db_alive_custom', false); } return $alive; }
<?php $auth = yourls_apply_filter('is_valid_user', yourls_is_valid_user()); if ($auth !== true) { // API mode, if (yourls_is_API()) { $format = isset($_REQUEST['format']) ? $_REQUEST['format'] : 'xml'; yourls_api_output($format, array('simple' => $auth, 'message' => $auth, 'errorCode' => 403)); // Regular mode } else { yourls_login_screen($auth); } die; }