Beispiel #1
0
function add_cache($tweet)
{
    global $smcFunc, $txt, $sourcedir;
    $twitterapi_url = "https://api.twitter.com/1/statuses/oembed.json?id=";
    $twitterapi_url = $twitterapi_url . $tweet;
    if (function_exists('curl_init')) {
        $curl = curl_init($twitterapi_url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        $response = curl_exec($curl);
        curl_close($curl);
    } else {
        require_once $sourcedir . '/Subs-Package.php';
        $response = fetch_web_data($twitterapi_url);
    }
    $json_content = json_decode($response, true);
    $json_content = preg_replace("/\r|\n/", "", $json_content);
    $html = $json_content['html'];
    if (!empty($html)) {
        $request = $smcFunc['db_insert']('', '{db_prefix}tweet_cache', array('tweetid' => 'raw', 'html' => 'text'), array($tweet, addslashes($html)), array('tweetid', 'html'));
        echo '{"html" : "' . addslashes($html) . '"}';
    } else {
        echo '{"html":"<p style=\\"color: #666; border: 1px dotted #666; padding: 5px; width: 490px;\\">' . $txt['autotwitter_tweeterror'] . '</p>"}';
    }
}
Beispiel #2
0
function list_getLanguagesList()
{
    global $forum_version, $context, $sourcedir, $smcFunc, $txt, $scripturl;
    // We're going to use this URL.
    $url = 'http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => '')));
    // Load the class file and stick it into an array.
    require_once $sourcedir . '/Class-Package.php';
    $language_list = new xmlArray(fetch_web_data($url), true);
    // Check that the site responded and that the language exists.
    if (!$language_list->exists('languages')) {
        $context['smf_error'] = 'no_response';
    } elseif (!$language_list->exists('languages/language')) {
        $context['smf_error'] = 'no_files';
    } else {
        $language_list = $language_list->path('languages[0]');
        $lang_files = $language_list->set('language');
        $smf_languages = array();
        foreach ($lang_files as $file) {
            // Were we searching?
            if (!empty($context['smf_search_term']) && strpos($file->fetch('name'), $smcFunc['strtolower']($context['smf_search_term'])) === false) {
                continue;
            }
            $smf_languages[] = array('id' => $file->fetch('id'), 'name' => $smcFunc['ucwords']($file->fetch('name')), 'version' => $file->fetch('version'), 'utf8' => $file->fetch('utf8') ? $txt['yes'] : $txt['no'], 'description' => $file->fetch('description'), 'install_link' => '<a href="' . $scripturl . '?action=admin;area=languages;sa=downloadlang;did=' . $file->fetch('id') . ';' . $context['session_var'] . '=' . $context['session_id'] . '">' . $txt['add_language_smf_install'] . '</a>');
        }
        if (empty($smf_languages)) {
            $context['smf_error'] = 'no_files';
        } else {
            return $smf_languages;
        }
    }
}
Beispiel #3
0
 /**
  * Retrieve server information.
  *
  * @param string $openid_url
  * @return boolean|array
  */
 public function getServerInfo($openid_url)
 {
     require_once SUBSDIR . '/Package.subs.php';
     // Get the html and parse it for the openid variable which will tell us where to go.
     $webdata = fetch_web_data($openid_url);
     if (empty($webdata)) {
         return false;
     }
     $response_data = array();
     // dirty, but .. Yadis response? Let's get the <URI>
     preg_match('~<URI.*?>(.*)</URI>~', $webdata, $uri);
     if ($uri) {
         $response_data['provider'] = $uri[1];
         $response_data['server'] = $uri[1];
         return $response_data;
     }
     // Some OpenID servers have strange but still valid HTML which makes our job hard.
     if (preg_match_all('~<link([\\s\\S]*?)/?>~i', $webdata, $link_matches) == 0) {
         fatal_lang_error('openid_server_bad_response');
     }
     foreach ($link_matches[1] as $link_match) {
         if (preg_match('~rel="([\\s\\S]*?)"~i', $link_match, $rel_match) == 0 || preg_match('~href="([\\s\\S]*?)"~i', $link_match, $href_match) == 0) {
             continue;
         }
         $rels = preg_split('~\\s+~', $rel_match[1]);
         foreach ($rels as $rel) {
             if (preg_match('~openid2?\\.(server|delegate|provider)~i', $rel, $match) != 0) {
                 $response_data[$match[1]] = $href_match[1];
             }
         }
     }
     if (empty($response_data['provider'])) {
         $response_data['server'] = $openid_url;
     } else {
         $response_data['server'] = $response_data['provider'];
     }
     return $response_data;
 }
Beispiel #4
0
function PackageDownload()
{
    global $txt, $scripturl, $boarddir, $context, $sourcedir, $db_prefix;
    // Use the downloaded sub template.
    $context['sub_template'] = 'downloaded';
    // Security is good...
    checkSession('get');
    if (isset($_GET['server'])) {
        $server = (int) $_GET['server'];
        // Query the server table to find the requested server.
        $request = db_query("\n\t\t\tSELECT name, url\n\t\t\tFROM {$db_prefix}package_servers\n\t\t\tWHERE ID_SERVER = {$server}\n\t\t\tLIMIT 1", __FILE__, __LINE__);
        list($name, $url) = mysql_fetch_row($request);
        mysql_free_result($request);
        // If server does not exist then dump out.
        if (empty($url)) {
            fatal_lang_error('smf191', false);
        }
        $url = $url . '/';
    } else {
        // Initialize the requried variables.
        $server = '';
        $url = '';
    }
    $package_name = basename($_REQUEST['package']);
    if (isset($_REQUEST['conflict']) || isset($_REQUEST['auto']) && file_exists($boarddir . '/Packages/' . $package_name)) {
        // Find the extension, change abc.tar.gz to abc_1.tar.gz...
        if (strrpos(substr($package_name, 0, -3), '.') !== false) {
            $ext = substr($package_name, strrpos(substr($package_name, 0, -3), '.'));
            $package_name = substr($package_name, 0, strrpos(substr($package_name, 0, -3), '.')) . '_';
        } else {
            $ext = '';
        }
        // Find the first available.
        $i = 1;
        while (file_exists($boarddir . '/Packages/' . $package_name . $i . $ext)) {
            $i++;
        }
        $package_name = $package_name . $i . $ext;
    }
    // First make sure it's a package.
    if (getPackageInfo($url . $_REQUEST['package']) == false) {
        fatal_lang_error('package45', false);
    }
    // Use FTP if necessary.
    packageRequireFTP($scripturl . '?action=packageget;sa=download' . (isset($_GET['server']) ? ';server=' . $_GET['server'] : '') . (isset($_REQUEST['auto']) ? ';auto' : '') . ';package=' . $_REQUEST['package'] . (isset($_REQUEST['conflict']) ? ';conflict' : '') . ';sesc=' . $context['session_id'], array($boarddir . '/Packages/' . $package_name));
    package_put_contents($boarddir . '/Packages/' . $package_name, fetch_web_data($url . $_REQUEST['package']));
    // Done!  Did we get this package automatically?
    if (preg_match('~^http://[\\w_\\-]+\\.simplemachines\\.org/~', $_REQUEST['package']) == 1 && strpos($_REQUEST['package'], 'dlattach') === false && isset($_REQUEST['auto'])) {
        redirectexit('action=packages;sa=install;package=' . $package_name . ';sesc=' . $context['session_id']);
    }
    // You just downloaded a mod from SERVER_NAME_GOES_HERE.
    $context['package_server'] = $server;
    $context['package'] = getPackageInfo($package_name);
    if (empty($context['package'])) {
        fatal_lang_error('package_cant_download', false);
    }
    if ($context['package']['type'] == 'modification') {
        $context['package']['install']['link'] = '<a href="' . $scripturl . '?action=packages;sa=install;package=' . $context['package']['filename'] . ';sesc=' . $context['session_id'] . '">[ ' . $txt['package11'] . ' ]</a>';
    } elseif ($context['package']['type'] == 'avatar') {
        $context['package']['install']['link'] = '<a href="' . $scripturl . '?action=packages;sa=install;package=' . $context['package']['filename'] . ';sesc=' . $context['session_id'] . '">[ ' . $txt['package12'] . ' ]</a>';
    } elseif ($context['package']['type'] == 'language') {
        $context['package']['install']['link'] = '<a href="' . $scripturl . '?action=packages;sa=install;package=' . $context['package']['filename'] . ';sesc=' . $context['session_id'] . '">[ ' . $txt['package13'] . ' ]</a>';
    } else {
        $context['package']['install']['link'] = '';
    }
    $context['package']['list_files']['link'] = '<a href="' . $scripturl . '?action=packages;sa=list;package=' . $context['package']['filename'] . '">[ ' . $txt['package14'] . ' ]</a>';
    // Free a little bit of memory...
    unset($context['package']['xml']);
    $context['page_title'] = $txt['smf192'];
}
Beispiel #5
0
function url_image_size($url)
{
    global $sourcedir;
    // Make sure it is a proper URL.
    $url = str_replace(' ', '%20', $url);
    // Can we pull this from the cache... please please?
    if (($temp = cache_get_data('url_image_size-' . md5($url), 240)) !== null) {
        return $temp;
    }
    $t = microtime();
    // Get the host to pester...
    preg_match('~^\\w+://(.+?)/(.*)$~', $url, $match);
    // Can't figure it out, just try the image size.
    if ($url == '' || $url == 'http://' || $url == 'https://') {
        return false;
    } elseif (!isset($match[1])) {
        $size = @getimagesize($url);
    } else {
        // Try to connect to the server... give it half a second.
        $temp = 0;
        $fp = @fsockopen($match[1], 80, $temp, $temp, 0.5);
        // Successful?  Continue...
        if ($fp != false) {
            // Send the HEAD request (since we don't have to worry about chunked, HTTP/1.1 is fine here.)
            fwrite($fp, 'HEAD /' . $match[2] . ' HTTP/1.1' . "\r\n" . 'Host: ' . $match[1] . "\r\n" . 'User-Agent: PHP/SMF' . "\r\n" . 'Connection: close' . "\r\n\r\n");
            // Read in the HTTP/1.1 or whatever.
            $test = substr(fgets($fp, 11), -1);
            fclose($fp);
            // See if it returned a 404/403 or something.
            if ($test < 4) {
                $size = @getimagesize($url);
                // This probably means allow_url_fopen is off, let's try GD.
                if ($size === false && function_exists('imagecreatefromstring')) {
                    include_once $sourcedir . '/Subs-Package.php';
                    // It's going to hate us for doing this, but another request...
                    $image = @imagecreatefromstring(fetch_web_data($url));
                    if ($image !== false) {
                        $size = array(imagesx($image), imagesy($image));
                        imagedestroy($image);
                    }
                }
            }
        }
    }
    // If we didn't get it, we failed.
    if (!isset($size)) {
        $size = false;
    }
    // If this took a long time, we may never have to do it again, but then again we might...
    if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $t)) > 0.8) {
        cache_put_data('url_image_size-' . md5($url), $size, 240);
    }
    // Didn't work.
    return $size;
}
Beispiel #6
0
function fetch_web_data($url, $post_data = '', $keep_alive = false, $redirection_level = 0)
{
    global $webmaster_email;
    static $keep_alive_dom = null, $keep_alive_fp = null;
    preg_match('~^(http|ftp)(s)?://([^/:]+)(:(\\d+))?(.+)$~', $url, $match);
    // An FTP url. We should try connecting and RETRieving it...
    if (empty($match[1])) {
        return false;
    } elseif ($match[1] == 'ftp') {
        // Include the file containing the ftp_connection class.
        loadClassFile('Class-Package.php');
        // Establish a connection and attempt to enable passive mode.
        $ftp = new ftp_connection(($match[2] ? 'ssl://' : '') . $match[3], empty($match[5]) ? 21 : $match[5], 'anonymous', $webmaster_email);
        if ($ftp->error !== false || !$ftp->passive()) {
            return false;
        }
        // I want that one *points*!
        fwrite($ftp->connection, 'RETR ' . $match[6] . "\r\n");
        // Since passive mode worked (or we would have returned already!) open the connection.
        $fp = @fsockopen($ftp->pasv['ip'], $ftp->pasv['port'], $err, $err, 5);
        if (!$fp) {
            return false;
        }
        // The server should now say something in acknowledgement.
        $ftp->check_response(150);
        $data = '';
        while (!feof($fp)) {
            $data .= fread($fp, 4096);
        }
        fclose($fp);
        // All done, right?  Good.
        $ftp->check_response(226);
        $ftp->close();
    } elseif (isset($match[1]) && $match[1] == 'http') {
        if ($keep_alive && $match[3] == $keep_alive_dom) {
            $fp = $keep_alive_fp;
        }
        if (empty($fp)) {
            // Open the socket on the port we want...
            $fp = @fsockopen(($match[2] ? 'ssl://' : '') . $match[3], empty($match[5]) ? $match[2] ? 443 : 80 : $match[5], $err, $err, 5);
            if (!$fp) {
                return false;
            }
        }
        if ($keep_alive) {
            $keep_alive_dom = $match[3];
            $keep_alive_fp = $fp;
        }
        // I want this, from there, and I'm not going to be bothering you for more (probably.)
        if (empty($post_data)) {
            fwrite($fp, 'GET ' . $match[6] . ' HTTP/1.0' . "\r\n");
            fwrite($fp, 'Host: ' . $match[3] . (empty($match[5]) ? $match[2] ? ':443' : '' : ':' . $match[5]) . "\r\n");
            fwrite($fp, 'User-Agent: PHP/SMF' . "\r\n");
            if ($keep_alive) {
                fwrite($fp, 'Connection: Keep-Alive' . "\r\n\r\n");
            } else {
                fwrite($fp, 'Connection: close' . "\r\n\r\n");
            }
        } else {
            fwrite($fp, 'POST ' . $match[6] . ' HTTP/1.0' . "\r\n");
            fwrite($fp, 'Host: ' . $match[3] . (empty($match[5]) ? $match[2] ? ':443' : '' : ':' . $match[5]) . "\r\n");
            fwrite($fp, 'User-Agent: PHP/SMF' . "\r\n");
            if ($keep_alive) {
                fwrite($fp, 'Connection: Keep-Alive' . "\r\n");
            } else {
                fwrite($fp, 'Connection: close' . "\r\n");
            }
            fwrite($fp, 'Content-Type: application/x-www-form-urlencoded' . "\r\n");
            fwrite($fp, 'Content-Length: ' . strlen($post_data) . "\r\n\r\n");
            fwrite($fp, $post_data);
        }
        $response = fgets($fp, 768);
        // Redirect in case this location is permanently or temporarily moved.
        if ($redirection_level < 3 && preg_match('~^HTTP/\\S+\\s+30[127]~i', $response) === 1) {
            $header = '';
            $location = '';
            while (!feof($fp) && trim($header = fgets($fp, 4096)) != '') {
                if (strpos($header, 'Location:') !== false) {
                    $location = trim(substr($header, strpos($header, ':') + 1));
                }
            }
            if (empty($location)) {
                return false;
            } else {
                if (!$keep_alive) {
                    fclose($fp);
                }
                return fetch_web_data($location, $post_data, $keep_alive, $redirection_level + 1);
            }
        } elseif (preg_match('~^HTTP/\\S+\\s+20[01]~i', $response) === 0) {
            return false;
        }
        // Skip the headers...
        while (!feof($fp) && trim($header = fgets($fp, 4096)) != '') {
            if (preg_match('~content-length:\\s*(\\d+)~i', $header, $match) != 0) {
                $content_length = $match[1];
            } elseif (preg_match('~connection:\\s*close~i', $header) != 0) {
                $keep_alive_dom = null;
                $keep_alive = false;
            }
            continue;
        }
        $data = '';
        if (isset($content_length)) {
            while (!feof($fp) && strlen($data) < $content_length) {
                $data .= fread($fp, $content_length - strlen($data));
            }
        } else {
            while (!feof($fp)) {
                $data .= fread($fp, 4096);
            }
        }
        if (!$keep_alive) {
            fclose($fp);
        }
    } else {
        // Umm, this shouldn't happen?
        trigger_error('fetch_web_data(): Bad URL', E_USER_NOTICE);
        $data = false;
    }
    return $data;
}
Beispiel #7
0
function scheduled_fetchSMfiles()
{
    global $sourcedir, $txt, $language, $settings, $forum_version, $modSettings, $smcFunc;
    return;
    // todo this does no longer make sense
    // What files do we want to get
    $request = smf_db_query('
		SELECT id_file, filename, path, parameters
		FROM {db_prefix}admin_info_files', array());
    $js_files = array();
    while ($row = mysql_fetch_assoc($request)) {
        $js_files[$row['id_file']] = array('filename' => $row['filename'], 'path' => $row['path'], 'parameters' => sprintf($row['parameters'], $language, urlencode($modSettings['time_format']), urlencode($forum_version)));
    }
    mysql_free_result($request);
    // We're gonna need fetch_web_data() to pull this off.
    require_once $sourcedir . '/lib/Subs-Package.php';
    // Just in case we run into a problem.
    loadEssentialThemeData();
    loadLanguage('Errors', $language, false);
    foreach ($js_files as $ID_FILE => $file) {
        // Create the url
        $server = empty($file['path']) || substr($file['path'], 0, 7) != 'http://' ? 'http://www.simplemachines.org' : '';
        $url = $server . (!empty($file['path']) ? $file['path'] : $file['path']) . $file['filename'] . (!empty($file['parameters']) ? '?' . $file['parameters'] : '');
        // Get the file
        $file_data = fetch_web_data($url);
        // If we got an error - give up - the site might be down.
        if ($file_data === false) {
            log_error(sprintf($txt['st_cannot_retrieve_file'], $url));
            return false;
        }
        // Save the file to the database.
        smf_db_query('
			UPDATE {db_prefix}admin_info_files
			SET data = SUBSTRING({string:file_data}, 1, 65534)
			WHERE id_file = {int:id_file}', array('id_file' => $ID_FILE, 'file_data' => $file_data));
    }
    return true;
}
Beispiel #8
0
/**
 * Resizes an image from a remote location or a local file.
 *
 * - Puts the resized image at the destination location.
 * - The file would have the format preferred_format if possible,
 * otherwise the default format is jpeg.
 *
 * @package Graphics
 * @param string $source
 * @param string $destination
 * @param int $max_width
 * @param int $max_height
 * @param int $preferred_format = 0
 */
function resizeImageFile($source, $destination, $max_width, $max_height, $preferred_format = 0)
{
    // Nothing to do without GD or IM
    if (!checkGD() && !checkImagick()) {
        return false;
    }
    static $default_formats = array('1' => 'gif', '2' => 'jpeg', '3' => 'png', '6' => 'bmp', '15' => 'wbmp');
    require_once SUBSDIR . '/Package.subs.php';
    // Get the image file, we have to work with something after all
    $fp_destination = fopen($destination, 'wb');
    if ($fp_destination && (substr($source, 0, 7) == 'http://' || substr($source, 0, 8) == 'https://')) {
        $fileContents = fetch_web_data($source);
        fwrite($fp_destination, $fileContents);
        fclose($fp_destination);
        $sizes = @getimagesize($destination);
    } elseif ($fp_destination) {
        $sizes = @getimagesize($source);
        $fp_source = fopen($source, 'rb');
        if ($fp_source !== false) {
            while (!feof($fp_source)) {
                fwrite($fp_destination, fread($fp_source, 8192));
            }
            fclose($fp_source);
        } else {
            $sizes = array(-1, -1, -1);
        }
        fclose($fp_destination);
    } else {
        $sizes = array(-1, -1, -1);
    }
    // See if we have -or- can get the needed memory for this operation
    if (checkGD() && !imageMemoryCheck($sizes)) {
        return false;
    }
    // A known and supported format?
    if (checkImagick() && isset($default_formats[$sizes[2]])) {
        return resizeImage(null, $destination, null, null, $max_width, $max_height, true, $preferred_format);
    } elseif (checkGD() && isset($default_formats[$sizes[2]]) && function_exists('imagecreatefrom' . $default_formats[$sizes[2]])) {
        $imagecreatefrom = 'imagecreatefrom' . $default_formats[$sizes[2]];
        if ($src_img = @$imagecreatefrom($destination)) {
            return resizeImage($src_img, $destination, imagesx($src_img), imagesy($src_img), $max_width === null ? imagesx($src_img) : $max_width, $max_height === null ? imagesy($src_img) : $max_height, true, $preferred_format);
        }
    }
    return false;
}
Beispiel #9
0
function AdminSearchOM()
{
    global $context, $sourcedir;
    $docsURL = 'docs.simplemachines.org';
    $context['doc_scripturl'] = 'http://docs.simplemachines.org/index.php';
    // Set all the parameters search might expect.
    $postVars = array('search' => $context['search_term']);
    // Encode the search data.
    foreach ($postVars as $k => $v) {
        $postVars[$k] = urlencode($k) . '=' . urlencode($v);
    }
    // This is what we will send.
    $postVars = implode('&', $postVars);
    // Get the results from the doc site.
    require_once $sourcedir . '/lib/Subs-Package.php';
    $search_results = fetch_web_data($context['doc_scripturl'] . '?action=search2&xml', $postVars);
    // If we didn't get any xml back we are in trouble - perhaps the doc site is overloaded?
    if (!$search_results || preg_match('~<' . '\\?xml\\sversion="\\d+\\.\\d+"\\sencoding=".+?"\\?' . '>\\s*(<smf>.+?</smf>)~is', $search_results, $matches) != true) {
        fatal_lang_error('cannot_connect_doc_site');
    }
    $search_results = $matches[1];
    // Otherwise we simply walk through the XML and stick it in context for display.
    $context['search_results'] = array();
    loadClassFile('Class-Package.php');
    // Get the results loaded into an array for processing!
    $results = new xmlArray($search_results, false);
    // Move through the smf layer.
    if (!$results->exists('smf')) {
        fatal_lang_error('cannot_connect_doc_site');
    }
    $results = $results->path('smf[0]');
    // Are there actually some results?
    if (!$results->exists('noresults') && !$results->exists('results')) {
        fatal_lang_error('cannot_connect_doc_site');
    } elseif ($results->exists('results')) {
        foreach ($results->set('results/result') as $result) {
            if (!$result->exists('messages')) {
                continue;
            }
            $context['search_results'][$result->fetch('id')] = array('topic_id' => $result->fetch('id'), 'relevance' => $result->fetch('relevance'), 'board' => array('id' => $result->fetch('board/id'), 'name' => $result->fetch('board/name'), 'href' => $result->fetch('board/href')), 'category' => array('id' => $result->fetch('category/id'), 'name' => $result->fetch('category/name'), 'href' => $result->fetch('category/href')), 'messages' => array());
            // Add the messages.
            foreach ($result->set('messages/message') as $message) {
                $context['search_results'][$result->fetch('id')]['messages'][] = array('id' => $message->fetch('id'), 'subject' => $message->fetch('subject'), 'body' => $message->fetch('body'), 'time' => $message->fetch('time'), 'timestamp' => $message->fetch('timestamp'), 'start' => $message->fetch('start'), 'author' => array('id' => $message->fetch('author/id'), 'name' => $message->fetch('author/name'), 'href' => $message->fetch('author/href')));
            }
        }
    }
}
function sp_rssFeed($parameters, $id, $return_parameters = false)
{
    global $smcFunc, $sourcedir, $context, $txt;
    $block_parameters = array('url' => 'text', 'show_title' => 'check', 'show_content' => 'check', 'show_date' => 'check', 'strip_preserve' => 'text', 'count' => 'int', 'limit' => 'int');
    if ($return_parameters) {
        return $block_parameters;
    }
    $feed = !empty($parameters['url']) ? un_htmlspecialchars($parameters['url']) : '';
    $show_title = !empty($parameters['show_title']);
    $show_content = !empty($parameters['show_content']);
    $show_date = !empty($parameters['show_date']);
    $strip_preserve = !empty($parameters['strip_preserve']) ? $parameters['strip_preserve'] : 'br';
    $strip_preserve = preg_match_all('~[A-Za-z0-9]+~', $strip_preserve, $match) ? $match[0] : array();
    $count = !empty($parameters['count']) ? (int) $parameters['count'] : 5;
    $limit = !empty($parameters['limit']) ? (int) $parameters['limit'] : 150;
    if (empty($feed)) {
        echo '
								', $txt['error_sp_invalid_feed'];
        return;
    }
    $rss = array();
    require_once $sourcedir . '/Subs-Package.php';
    $data = fetch_web_data($feed);
    if (function_exists('mb_convert_encoding')) {
        preg_match('~encoding="([^"]*)"~', $data, $charset);
        if (!empty($charset[1]) && $charset != $context['character_set']) {
            $data = mb_convert_encoding($data, $context['character_set'], $charset[1]);
        }
    } elseif (function_exists('iconv')) {
        preg_match('~encoding="([^"]*)"~', $data, $charset);
        if (!empty($charset[1]) && $charset != $context['character_set']) {
            $data = iconv($charset[1], $context['character_set'], $data);
        }
    }
    $data = str_replace(array("\n", "\r", "\t"), '', $data);
    $data = preg_replace('~<\\!\\[CDATA\\[(.+?)\\]\\]>~e' . ($context['utf8'] ? 'u' : ''), '\'#cdata_escape_encode#\' . $smcFunc[\'htmlspecialchars\'](\'$1\')', $data);
    preg_match_all('~<item>(.+?)</item>~', $data, $items);
    foreach ($items[1] as $item_id => $item) {
        if ($item_id === $count) {
            break;
        }
        preg_match_all('~<([A-Za-z]+)>(.+?)</\\1>~', $item, $match);
        foreach ($match[0] as $tag_id => $dummy) {
            if ($smcFunc['strpos']($match[2][$tag_id], '#cdata_escape_encode#') === 0) {
                $match[2][$tag_id] = stripslashes(un_htmlspecialchars($smcFunc['substr']($match[2][$tag_id], 21)));
            }
            $rss[$item_id][strtolower($match[1][$tag_id])] = un_htmlspecialchars($match[2][$tag_id]);
        }
    }
    if (empty($rss)) {
        echo '
								', $txt['error_sp_invalid_feed'];
        return;
    }
    $items = array();
    foreach ($rss as $item) {
        $item['title'] = isset($item['title']) ? strip_tags($item['title']) : '';
        $item['description'] = isset($item['description']) ? strip_tags($item['description'], empty($strip_preserve) ? '' : '<' . implode('><', $strip_preserve) . '>') : '';
        $items[] = array('title' => $item['title'], 'href' => $item['link'], 'link' => $item['title'] == '' ? '' : ($item['link'] == '' ? $item['title'] : '<a href="' . $item['link'] . '" target="_blank" class="new_win">' . $item['title'] . '</a>'), 'content' => $limit > 0 && $smcFunc['strlen']($item['description']) > $limit ? $smcFunc['substr']($item['description'], 0, $limit) . '...' : $item['description'], 'date' => !empty($item['pubdate']) ? timeformat(strtotime($item['pubdate']), '%d %B') : '');
    }
    if (empty($items)) {
        echo '
								', $txt['error_sp_invalid_feed'];
        return;
    } else {
        $items[count($items) - 1]['is_last'] = true;
    }
    if ($show_content) {
        echo '
								<div class="sp_rss_flow">
									<ul class="sp_list">';
        foreach ($items as $item) {
            if ($show_title && !empty($item['link'])) {
                echo '
										<li class="sp_list_top">', sp_embed_image('post'), ' <strong>', $item['link'], '</strong>', $show_date && !empty($item['date']) ? ' - ' . $item['date'] : '', '</li>';
            }
            echo '
										<li', empty($item['is_last']) ? ' class="sp_list_divider"' : '', '>', $item['content'], '</li>';
        }
        echo '
									</ul>
								</div>';
    } else {
        echo '
								<ul class="sp_list">';
        foreach ($items as $item) {
            echo '
									<li>', sp_embed_image('dot_feed'), ' ', $item['link'], $show_date && !empty($item['date']) ? ' - ' . $item['date'] : '', '</li>';
        }
        echo '
								</ul>';
    }
}
Beispiel #11
0
/**
 * Gets a list of available languages from the mother ship
 *
 * - Will return a subset if searching, otherwise all available
 *
 * @package Languages
 * @return string
 */
function list_getLanguagesList()
{
    global $forum_version, $context, $txt, $scripturl;
    // We're going to use this URL.
    // @todo no we are not, this needs to be changed - again
    $url = 'http://download.elkarte.net/fetch_language.php?version=' . urlencode(strtr($forum_version, array('ElkArte ' => '')));
    // Load the class file and stick it into an array.
    require_once SUBSDIR . '/XmlArray.class.php';
    $language_list = new Xml_Array(fetch_web_data($url), true);
    // Check that the site responded and that the language exists.
    if (!$language_list->exists('languages')) {
        $context['langfile_error'] = 'no_response';
    } elseif (!$language_list->exists('languages/language')) {
        $context['langfile_error'] = 'no_files';
    } else {
        $language_list = $language_list->path('languages[0]');
        $lang_files = $language_list->set('language');
        $languages = array();
        foreach ($lang_files as $file) {
            // Were we searching?
            if (!empty($context['elk_search_term']) && strpos($file->fetch('name'), Util::strtolower($context['elk_search_term'])) === false) {
                continue;
            }
            $languages[] = array('id' => $file->fetch('id'), 'name' => Util::ucwords($file->fetch('name')), 'version' => $file->fetch('version'), 'utf8' => $txt['yes'], 'description' => $file->fetch('description'), 'install_link' => '<a href="' . $scripturl . '?action=admin;area=languages;sa=downloadlang;did=' . $file->fetch('id') . ';' . $context['session_var'] . '=' . $context['session_id'] . '">' . $txt['add_language_elk_install'] . '</a>');
        }
        if (empty($languages)) {
            $context['langfile_error'] = 'no_files';
        } else {
            return $languages;
        }
    }
}
 public static function fb_do_agree()
 {
     global $sourcedir, $context, $boarddir, $boardurl, $user_info, $fb_hook_object;
     require_once $sourcedir . '/Subs-Package.php';
     if (isset($_GET['agree'])) {
         loadLanguage('Login');
         $context['sub_template'] = 'regfb_agree';
         if (file_exists($boarddir . '/agreement.' . $user_info['language'] . '.txt')) {
             $context['agreement'] = parse_bbc(fetch_web_data($boardurl . '/agreement.' . $user_info['language'] . '.txt'), true, 'agreement_' . $user_info['language']);
         } elseif (file_exists($boarddir . '/agreement.txt')) {
             $context['agreement'] = parse_bbc(fetch_web_data($boardurl . '/agreement.txt'), true, 'agreement');
         } else {
             $context['agreement'] = '';
         }
     } else {
         if (!isset($_POST['accept_agreement']) && !empty($fb_hook_object->modSettings['requireAgreement'])) {
             redirectexit('action=facebookintegrate;area=connect;agree');
         }
     }
 }
Beispiel #13
0
function downloadAvatar($url, $memID, $max_width, $max_height)
{
    global $modSettings, $db_prefix, $sourcedir, $gd2;
    $destName = 'avatar_' . $memID . '.' . (!empty($modSettings['avatar_download_png']) ? 'png' : 'jpeg');
    $default_formats = array('1' => 'gif', '2' => 'jpeg', '3' => 'png', '6' => 'bmp', '15' => 'wbmp');
    // Check to see if GD is installed and what version.
    $testGD = get_extension_funcs('gd');
    // If GD is not installed, this function is pointless.
    if (empty($testGD)) {
        return false;
    }
    // Just making sure there is a non-zero member.
    if (empty($memID)) {
        return false;
    }
    // GD 2 maybe?
    $gd2 = in_array('imagecreatetruecolor', $testGD) && function_exists('imagecreatetruecolor');
    unset($testGD);
    require_once $sourcedir . '/ManageAttachments.php';
    removeAttachments('a.ID_MEMBER = ' . $memID);
    $avatar_hash = empty($modSettings['custom_avatar_enabled']) ? getAttachmentFilename($destName, false, true) : '';
    db_query("\n\t\tINSERT INTO {$db_prefix}attachments\n\t\t\t(ID_MEMBER, attachmentType, filename, file_hash, size)\n\t\tVALUES ({$memID}, " . (empty($modSettings['custom_avatar_enabled']) ? '0' : '1') . ", '{$destName}', '" . (empty($avatar_hash) ? "" : "{$avatar_hash}") . "', 1)", __FILE__, __LINE__);
    $attachID = db_insert_id();
    $destName = (empty($modSettings['custom_avatar_enabled']) ? $modSettings['attachmentUploadDir'] : $modSettings['custom_avatar_dir']) . '/' . $destName . '.tmp';
    $success = false;
    $sizes = url_image_size($url);
    require_once $sourcedir . '/Subs-Package.php';
    $fp = fopen($destName, 'wb');
    if ($fp && substr($url, 0, 7) == 'http://') {
        $fileContents = fetch_web_data($url);
        // Though not an exhaustive list, better safe than sorry.
        if (preg_match('~(iframe|\\<\\?php|\\<\\?[\\s=]|\\<%[\\s=]|html|eval|body|script\\W)~', $fileContents) === 1) {
            fclose($fp);
            return false;
        }
        fwrite($fp, $fileContents);
        fclose($fp);
    } elseif ($fp) {
        $fp2 = fopen($url, 'rb');
        $prev_chunk = '';
        while (!feof($fp2)) {
            $cur_chunk = fread($fp2, 8192);
            // Make sure nothing odd came through.
            if (preg_match('~(iframe|\\<\\?php|\\<\\?[\\s=]|\\<%[\\s=]|html|eval|body|script\\W)~', $prev_chunk . $cur_chunk) === 1) {
                fclose($fp2);
                fclose($fp);
                unlink($destName);
                return false;
            }
            fwrite($fp, $cur_chunk);
            $prev_chunk = $cur_chunk;
        }
        fclose($fp2);
        fclose($fp);
    } else {
        $sizes = array(-1, -1, -1);
    }
    // Gif? That might mean trouble if gif support is not available.
    if ($sizes[2] == 1 && !function_exists('imagecreatefromgif') && function_exists('imagecreatefrompng')) {
        // Download it to the temporary file... use the special gif library... and save as png.
        if ($img = @gif_loadFile($destName) && gif_outputAsPng($img, $destName)) {
            $sizes[2] = 3;
        }
    }
    // A known and supported format?
    if (isset($default_formats[$sizes[2]]) && function_exists('imagecreatefrom' . $default_formats[$sizes[2]])) {
        $imagecreatefrom = 'imagecreatefrom' . $default_formats[$sizes[2]];
        if ($src_img = @$imagecreatefrom($destName)) {
            resizeImage($src_img, $destName, imagesx($src_img), imagesy($src_img), $max_width, $max_height);
            $success = true;
        }
    }
    // Remove the .tmp extension.
    $destName = substr($destName, 0, -4);
    if ($success) {
        // Remove the .tmp extension from the attachment.
        if (rename($destName . '.tmp', empty($avatar_hash) ? $destName : $modSettings['attachmentUploadDir'] . '/' . $attachID . '_' . $avatar_hash)) {
            $destName = empty($avatar_hash) ? $destName : $modSettings['attachmentUploadDir'] . '/' . $attachID . '_' . $avatar_hash;
            list($width, $height) = getimagesize($destName);
            // Write filesize in the database.
            db_query("\n\t\t\t\tUPDATE {$db_prefix}attachments\n\t\t\t\tSET size = " . filesize($destName) . ", width = " . (int) $width . ", height = " . (int) $height . "\n\t\t\t\tWHERE ID_ATTACH = {$attachID}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__);
            return true;
        } else {
            return false;
        }
    } else {
        db_query("\n\t\t\tDELETE FROM {$db_prefix}attachments\n\t\t\tWHERE ID_ATTACH = {$attachID}\n\t\t\tLIMIT 1", __FILE__, __LINE__);
        @unlink($destName . '.tmp');
        return false;
    }
}
/**
 * RSS Block, Displays rss feed in a block.
 *
 * @param mixed[] $parameters
 *		'url' => url of the feed
 *		'show_title' => Show the feed title
 *		'show_content' => Show the content of the feed
 *		'show_date' => Show the date of the feed item
 *		'strip_preserve' => preserve tags
 * 		'count' => number of items to show
 * 		'limit' => number of characters of content to show
 * @param int $id - not used in this block
 * @param boolean $return_parameters if true returns the configuration options for the block
 */
function sp_rssFeed($parameters, $id, $return_parameters = false)
{
    global $txt;
    $block_parameters = array('url' => 'text', 'show_title' => 'check', 'show_content' => 'check', 'show_date' => 'check', 'strip_preserve' => 'text', 'count' => 'int', 'limit' => 'int');
    if ($return_parameters) {
        return $block_parameters;
    }
    $feed = !empty($parameters['url']) ? un_htmlspecialchars($parameters['url']) : '';
    $show_title = !empty($parameters['show_title']);
    $show_content = !empty($parameters['show_content']);
    $show_date = !empty($parameters['show_date']);
    $strip_preserve = !empty($parameters['strip_preserve']) ? $parameters['strip_preserve'] : 'br';
    $strip_preserve = preg_match_all('~[A-Za-z0-9]+~', $strip_preserve, $match) ? $match[0] : array();
    $count = !empty($parameters['count']) ? (int) $parameters['count'] : 5;
    $limit = !empty($parameters['limit']) ? (int) $parameters['limit'] : 0;
    // Need a feed name to load it
    if (empty($feed)) {
        echo '
								', $txt['error_sp_invalid_feed'];
        return;
    }
    $rss = array();
    require_once SUBSDIR . '/Package.subs.php';
    $data = fetch_web_data($feed);
    $data_save = $data;
    // Convert it to UTF8 if we can and its not already
    preg_match('~encoding="([^"]*)"~', $data, $charset);
    if (!empty($charset[1]) && $charset != 'UTF-8') {
        // Use iconv if its available
        if (function_exists('iconv')) {
            $data = @iconv($charset[1], 'UTF-8' . '//TRANSLIT//IGNORE', $data);
        }
        // No iconv or a false response from it
        if (!function_exists('iconv') || $data == false) {
            // PHP (some 5.4 versions) mishandles //TRANSLIT//IGNORE and returns false: see https://bugs.php.net/bug.php?id=61484
            if ($data == false) {
                $data = $data_save;
            }
            if (function_exists('mb_convert_encoding')) {
                // Replace unknown characters with a space
                @ini_set('mbstring.substitute_character', '32');
                $data = @mb_convert_encoding($data, 'UTF-8', $charset[1]);
            } elseif (function_exists('recode_string')) {
                $data = @recode_string($charset[1] . '..' . 'UTF-8', $data);
            }
        }
    }
    $data = str_replace(array("\n", "\r", "\t"), '', $data);
    $data = preg_replace('~<\\!\\[CDATA\\[(.+?)\\]\\]>~eu', '\'#cdata_escape_encode#\' . Util::htmlspecialchars(\'$1\')', $data);
    // Find all the feed items
    preg_match_all('~<item>(.+?)</item>~', $data, $items);
    foreach ($items[1] as $item_id => $item) {
        if ($item_id === $count) {
            break;
        }
        preg_match_all('~<([A-Za-z]+)>(.+?)</\\1>~', $item, $match);
        foreach ($match[0] as $tag_id => $dummy) {
            if (Util::strpos($match[2][$tag_id], '#cdata_escape_encode#') === 0) {
                $match[2][$tag_id] = stripslashes(un_htmlspecialchars(Util::substr($match[2][$tag_id], 21)));
            }
            $rss[$item_id][strtolower($match[1][$tag_id])] = un_htmlspecialchars($match[2][$tag_id]);
        }
    }
    // Nothing, say its invalid
    if (empty($rss)) {
        echo '
								', $txt['error_sp_invalid_feed'];
        return;
    }
    // Add all the items to an array
    $items = array();
    foreach ($rss as $item) {
        $item['title'] = isset($item['title']) ? strip_tags($item['title']) : '';
        $item['description'] = isset($item['description']) ? strip_tags($item['description'], empty($strip_preserve) ? '' : '<' . implode('><', $strip_preserve) . '>') : '';
        $items[] = array('title' => $item['title'], 'href' => $item['link'], 'link' => $item['title'] == '' ? '' : ($item['link'] == '' ? $item['title'] : '<a href="' . $item['link'] . '" target="_blank" class="new_win">' . $item['title'] . '</a>'), 'content' => $limit > 0 ? Util::shorten_text($item['description'], $limit, true) : $item['description'], 'date' => !empty($item['pubdate']) ? standardTime(strtotime($item['pubdate']), '%d %B') : '');
    }
    // No items in the feed
    if (empty($items)) {
        echo '
								', $txt['error_sp_invalid_feed'];
        return;
    } else {
        $items[count($items) - 1]['is_last'] = true;
    }
    if ($show_content) {
        echo '
								<div class="sp_rss_flow">
									<ul class="sp_list">';
        foreach ($items as $item) {
            if ($show_title && !empty($item['link'])) {
                echo '
										<li ', sp_embed_class('post', '', 'sp_list_top'), '><strong>', $item['link'], '</strong>', $show_date && !empty($item['date']) ? ' - ' . $item['date'] : '', '</li>';
            }
            echo '
										<li', empty($item['is_last']) ? ' class="sp_list_divider"' : '', '>', $item['content'], '</li>';
        }
        echo '
									</ul>
								</div>';
    } else {
        echo '
								<ul class="sp_list">';
        foreach ($items as $item) {
            echo '
									<li ', sp_embed_class('dot_feed'), '> ', $item['link'], $show_date && !empty($item['date']) ? ' - ' . $item['date'] : '', '</li>';
        }
        echo '
								</ul>';
    }
}
 /**
  * Install a smiley set.
  */
 public function action_install()
 {
     global $modSettings, $scripturl, $context, $txt, $user_info;
     isAllowedTo('manage_smileys');
     checkSession('request');
     // One of these two may be necessary
     loadLanguage('Errors');
     loadLanguage('Packages');
     require_once SUBSDIR . '/Smileys.subs.php';
     require_once SUBSDIR . '/Package.subs.php';
     // Installing unless proven otherwise
     $testing = false;
     $destination = '';
     $name = '';
     if (isset($_REQUEST['set_gz'])) {
         $base_name = strtr(basename($_REQUEST['set_gz']), ':/', '-_');
         $name = Util::htmlspecialchars(strtok(basename($_REQUEST['set_gz']), '.'));
         $name_pr = preg_replace(array('/\\s/', '/\\.[\\.]+/', '/[^\\w_\\.\\-]/'), array('_', '.', ''), $name);
         $context['filename'] = $base_name;
         // Check that the smiley is from simplemachines.org, for now... maybe add mirroring later.
         if (!isAuthorizedServer($_REQUEST['set_gz']) == 0) {
             fatal_lang_error('not_valid_server');
         }
         $destination = BOARDDIR . '/packages/' . $base_name;
         if (file_exists($destination)) {
             fatal_lang_error('package_upload_error_exists');
         }
         // Let's copy it to the packages directory
         file_put_contents($destination, fetch_web_data($_REQUEST['set_gz']));
         $testing = true;
     } elseif (isset($_REQUEST['package'])) {
         $base_name = basename($_REQUEST['package']);
         $name = Util::htmlspecialchars(strtok(basename($_REQUEST['package']), '.'));
         $name_pr = preg_replace(array('/\\s/', '/\\.[\\.]+/', '/[^\\w_\\.\\-]/'), array('_', '.', ''), $name);
         $context['filename'] = $base_name;
         $destination = BOARDDIR . '/packages/' . basename($_REQUEST['package']);
     }
     if (!file_exists($destination)) {
         fatal_lang_error('package_no_file', false);
     }
     // Make sure temp directory exists and is empty.
     if (file_exists(BOARDDIR . '/packages/temp')) {
         deltree(BOARDDIR . '/packages/temp', false);
     }
     if (!mktree(BOARDDIR . '/packages/temp', 0755)) {
         deltree(BOARDDIR . '/packages/temp', false);
         if (!mktree(BOARDDIR . '/packages/temp', 0777)) {
             deltree(BOARDDIR . '/packages/temp', false);
             // @todo not sure about url in destination_url
             create_chmod_control(array(BOARDDIR . '/packages/temp/delme.tmp'), array('destination_url' => $scripturl . '?action=admin;area=smileys;sa=install;set_gz=' . $_REQUEST['set_gz'], 'crash_on_error' => true));
             deltree(BOARDDIR . '/packages/temp', false);
             if (!mktree(BOARDDIR . '/packages/temp', 0777)) {
                 fatal_lang_error('package_cant_download', false);
             }
         }
     }
     $extracted = read_tgz_file($destination, BOARDDIR . '/packages/temp');
     // @todo needs to change the URL in the next line ;)
     if (!$extracted) {
         fatal_lang_error('packageget_unable', false, array('http://custom.elkarte.net/index.php?action=search;type=12;basic_search=' . $name));
     }
     if ($extracted && !file_exists(BOARDDIR . '/packages/temp/package-info.xml')) {
         foreach ($extracted as $file) {
             if (basename($file['filename']) == 'package-info.xml') {
                 $base_path = dirname($file['filename']) . '/';
                 break;
             }
         }
     }
     if (!isset($base_path)) {
         $base_path = '';
     }
     if (!file_exists(BOARDDIR . '/packages/temp/' . $base_path . 'package-info.xml')) {
         fatal_lang_error('package_get_error_missing_xml', false);
     }
     $smileyInfo = getPackageInfo($context['filename']);
     if (!is_array($smileyInfo)) {
         fatal_lang_error($smileyInfo);
     }
     // See if it is installed?
     if (isSmileySetInstalled($smileyInfo['id'])) {
         fata_lang_error('package_installed_warning1');
     }
     // Everything is fine, now it's time to do something, first we test
     $actions = parsePackageInfo($smileyInfo['xml'], true, 'install');
     $context['post_url'] = $scripturl . '?action=admin;area=smileys;sa=install;package=' . $base_name;
     $context['has_failure'] = false;
     $context['actions'] = array();
     $context['ftp_needed'] = false;
     foreach ($actions as $action) {
         if ($action['type'] == 'readme' || $action['type'] == 'license') {
             $type = 'package_' . $action['type'];
             if (file_exists(BOARDDIR . '/packages/temp/' . $base_path . $action['filename'])) {
                 $context[$type] = htmlspecialchars(trim(file_get_contents(BOARDDIR . '/packages/temp/' . $base_path . $action['filename']), "\n\r"), ENT_COMPAT, 'UTF-8');
             } elseif (file_exists($action['filename'])) {
                 $context[$type] = htmlspecialchars(trim(file_get_contents($action['filename']), "\n\r"), ENT_COMPAT, 'UTF-8');
             }
             if (!empty($action['parse_bbc'])) {
                 require_once SUBSDIR . '/Post.subs.php';
                 preparsecode($context[$type]);
                 $context[$type] = parse_bbc($context[$type]);
             } else {
                 $context[$type] = nl2br($context[$type]);
             }
             continue;
         } elseif ($action['type'] == 'require-dir') {
             // Do this one...
             $thisAction = array('type' => $txt['package_extract'] . ' ' . ($action['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']), 'action' => Util::htmlspecialchars(strtr($action['destination'], array(BOARDDIR => '.'))));
             $file = BOARDDIR . '/packages/temp/' . $base_path . $action['filename'];
             if (isset($action['filename']) && (!file_exists($file) || !is_writable(dirname($action['destination'])))) {
                 $context['has_failure'] = true;
                 $thisAction += array('description' => $txt['package_action_error'], 'failed' => true);
             }
             // Show a description for the action if one is provided
             if (empty($thisAction['description'])) {
                 $thisAction['description'] = isset($action['description']) ? $action['description'] : '';
             }
             $context['actions'][] = $thisAction;
         } elseif ($action['type'] == 'credits') {
             // Time to build the billboard
             $credits_tag = array('url' => $action['url'], 'license' => $action['license'], 'copyright' => $action['copyright'], 'title' => $action['title']);
         }
     }
     if ($testing) {
         $context['sub_template'] = 'view_package';
         $context['uninstalling'] = false;
         $context['is_installed'] = false;
         $context['package_name'] = $smileyInfo['name'];
         loadTemplate('Packages');
     } else {
         $actions = parsePackageInfo($smileyInfo['xml'], false, 'install');
         foreach ($context['actions'] as $action) {
             updateSettings(array('smiley_sets_known' => $modSettings['smiley_sets_known'] . ',' . basename($action['action']), 'smiley_sets_names' => $modSettings['smiley_sets_names'] . "\n" . $smileyInfo['name'] . (count($context['actions']) > 1 ? ' ' . (!empty($action['description']) ? Util::htmlspecialchars($action['description']) : basename($action['action'])) : '')));
         }
         package_flush_cache();
         // Time to tell pacman we have a new package installed!
         package_put_contents(BOARDDIR . '/packages/installed.list', time());
         // Credits tag?
         $credits_tag = empty($credits_tag) ? '' : serialize($credits_tag);
         $installed = array('filename' => $smileyInfo['filename'], 'name' => $smileyInfo['name'], 'package_id' => $smileyInfo['id'], 'version' => $smileyInfo['filename'], 'id_member' => $user_info['id'], 'member_name' => $user_info['name'], 'credits_tag' => $credits_tag);
         logPackageInstall($installed);
         logAction('install_package', array('package' => Util::htmlspecialchars($smileyInfo['name']), 'version' => Util::htmlspecialchars($smileyInfo['version'])), 'admin');
         cache_put_data('parsing_smileys', null, 480);
         cache_put_data('posting_smileys', null, 480);
     }
     if (file_exists(BOARDDIR . '/packages/temp')) {
         deltree(BOARDDIR . '/packages/temp');
     }
     if (!$testing) {
         redirectexit('action=admin;area=smileys');
     }
 }
Beispiel #16
0
/**
 * Just like the built in one, but setup for CLI to not use themes.
 */
function cli_scheduled_fetchFiles()
{
    global $language, $forum_version, $modSettings;
    $db = database();
    if (empty($modSettings['time_format'])) {
        $modSettings['time_format'] = '%B %d, %Y, %I:%M:%S %p';
    }
    // What files do we want to get
    $request = $db->query('', '
		SELECT id_file, filename, path, parameters
		FROM {db_prefix}admin_info_files', array());
    $js_files = array();
    while ($row = $db->fetch_assoc($request)) {
        $js_files[$row['id_file']] = array('filename' => $row['filename'], 'path' => $row['path'], 'parameters' => sprintf($row['parameters'], $language, urlencode($modSettings['time_format']), urlencode($forum_version)));
    }
    $db->free_result($request);
    // We're gonna need fetch_web_data() to pull this off.
    require_once SUBSDIR . '/Package.subs.php';
    foreach ($js_files as $ID_FILE => $file) {
        // Create the url
        $server = empty($file['path']) || substr($file['path'], 0, 7) != 'http://' ? 'http://www.elkarte.net' : '';
        $url = $server . (!empty($file['path']) ? $file['path'] : $file['path']) . $file['filename'] . (!empty($file['parameters']) ? '?' . $file['parameters'] : '');
        // Get the file
        $file_data = fetch_web_data($url);
        // If we got an error - give up - the site might be down.
        if ($file_data === false) {
            return throw_error(sprintf('Could not retrieve the file %1$s.', $url));
        }
        // Save the file to the database.
        $db->query('substring', '
			UPDATE {db_prefix}admin_info_files
			SET data = SUBSTRING({string:file_data}, 1, 65534)
			WHERE id_file = {int:id_file}', array('id_file' => $ID_FILE, 'file_data' => $file_data));
    }
    return true;
}
Beispiel #17
0
function fetch_install_info()
{
    $install_info = fetch_web_data('http://www.simplemachines.org/smf/mirrors.xml');
    if ($install_info === false) {
        return false;
    }
    $info = array('mirrors' => array(), 'install' => array(), 'languages' => array());
    $vers = array();
    // Get mirrors.
    preg_match_all('~<mirror name="([^"]+)">([^<]+)</mirror>~', $install_info, $matches, PREG_SET_ORDER);
    foreach ($matches as $match) {
        $info['mirrors'][$match[2]] = $match[1];
    }
    // Get install packages.
    preg_match_all('~<install access="([^"]+)" name="([^"]+)">([^<]+)</install>~', $install_info, $matches, PREG_SET_ORDER);
    foreach ($matches as $match) {
        if (in_array($match[1], $_SESSION['webinstall_state']['access'])) {
            $info['install'][$match[3]] = $match[2];
            $vers[] = str_replace('SMF ', '', $match[2]);
        }
    }
    // Get language packages.
    preg_match_all('~<language name="([^"]+)" versions="([^"]+)">([^<]+)</language>~', $install_info, $matches, PREG_SET_ORDER);
    foreach ($matches as $match) {
        $versions = explode(', ', $match[2]);
        foreach ($versions as $id => $ver) {
            if (!in_array($ver, $vers)) {
                unset($versions[$ver]);
            }
        }
        if (empty($versions)) {
            continue;
        }
        $info['languages'][$match[3]] = array('name' => $match[1], 'versions' => explode(', ', $match[2]));
    }
    // Put it into the session data for later use.
    $_SESSION['webinstall_state']['install_info'] = $info;
    return $info;
}
Beispiel #18
0
function resizeImageURL($sourceURL, $destinationFile, $max_width, $max_height)
{
    global $sourcedir;
    static $default_formats = array('1' => 'gif', '2' => 'jpeg', '3' => 'png', '6' => 'bmp', '15' => 'wbmp');
    require_once $sourcedir . '/Subs-Package.php';
    $success = false;
    $sizes = url_image_size($sourceURL);
    $fp_destination = fopen($destinationFile, 'wb');
    if ($fp_destination && substr($sourceURL, 0, 7) == 'http://') {
        $fileContents = fetch_web_data($sourceURL);
        fwrite($fp_destination, $fileContents);
        fclose($fp_destination);
    } elseif ($fp_destination) {
        $fp_source = fopen($sourceURL, 'rb');
        if ($fp_source !== false) {
            while (!feof($fp_source)) {
                fwrite($fp_destination, fread($fp_source, 8192));
            }
            fclose($fp_source);
        } else {
            $sizes = array(-1, -1, -1);
        }
        fclose($fp_destination);
    } else {
        $sizes = array(-1, -1, -1);
    }
    // Gif? That might mean trouble if gif support is not available.
    if ($sizes[2] == 1 && !function_exists('imagecreatefromgif') && function_exists('imagecreatefrompng')) {
        // Download it to the temporary file... use the special gif library... and save as png.
        if ($img = @gif_loadFile($destinationFile) && gif_outputAsPng($img, $destinationFile)) {
            $sizes[2] = 3;
        }
    }
    // A known and supported format?
    if (isset($default_formats[$sizes[2]]) && function_exists('imagecreatefrom' . $default_formats[$sizes[2]])) {
        $imagecreatefrom = 'imagecreatefrom' . $default_formats[$sizes[2]];
        if ($src_img = @$imagecreatefrom($destinationFile)) {
            resizeImage($src_img, $destinationFile, imagesx($src_img), imagesy($src_img), $max_width === null ? imagesx($src_img) : $max_width, $max_height === null ? imagesy($src_img) : $max_height, true);
            $success = true;
        }
    }
    return $success;
}
Beispiel #19
0
/**
 * This file allows the user to search the SM online manual for a little of help.
 */
function AdminSearchOM()
{
    global $context, $sourcedir;
    $context['doc_apiurl'] = 'http://wiki.simplemachines.org/api.php';
    $context['doc_scripturl'] = 'http://wiki.simplemachines.org/smf/';
    // Set all the parameters search might expect.
    $postVars = explode(' ', $context['search_term']);
    // Encode the search data.
    foreach ($postVars as $k => $v) {
        $postVars[$k] = urlencode($v);
    }
    // This is what we will send.
    $postVars = implode('+', $postVars);
    // Get the results from the doc site.
    require_once $sourcedir . '/Subs-Package.php';
    // Demo URL:
    // http://wiki.simplemachines.org/api.php?action=query&list=search&srprop=timestamp|snippet&format=xml&srwhat=text&srsearch=template+eval
    $search_results = fetch_web_data($context['doc_apiurl'] . '?action=query&list=search&srprop=timestamp|snippet&format=xml&srwhat=text&srsearch=' . $postVars);
    // If we didn't get any xml back we are in trouble - perhaps the doc site is overloaded?
    if (!$search_results || preg_match('~<' . '\\?xml\\sversion="\\d+\\.\\d+"\\?>\\s*(<api>.+?</api>)~is', $search_results, $matches) != true) {
        fatal_lang_error('cannot_connect_doc_site');
    }
    $search_results = $matches[1];
    // Otherwise we simply walk through the XML and stick it in context for display.
    $context['search_results'] = array();
    require_once $sourcedir . '/Class-Package.php';
    // Get the results loaded into an array for processing!
    $results = new xmlArray($search_results, false);
    // Move through the api layer.
    if (!$results->exists('api')) {
        fatal_lang_error('cannot_connect_doc_site');
    }
    // Are there actually some results?
    if ($results->exists('api/query/search/p')) {
        $relevance = 0;
        foreach ($results->set('api/query/search/p') as $result) {
            $context['search_results'][$result->fetch('@title')] = array('title' => $result->fetch('@title'), 'relevance' => $relevance++, 'snippet' => str_replace('class=\'searchmatch\'', 'class="highlight"', un_htmlspecialchars($result->fetch('@snippet'))));
        }
    }
}
Beispiel #20
0
function getPackageInfo($gzfilename)
{
    global $boarddir;
    // Extract package-info.xml from downloaded file. (*/ is used because it could be in any directory.)
    if (strpos($gzfilename, 'http://') !== false) {
        $packageInfo = read_tgz_data(fetch_web_data($gzfilename, '', true), '*/package-info.xml', true);
    } else {
        if (!file_exists($boarddir . '/Packages/' . $gzfilename)) {
            return false;
        }
        if (is_file($boarddir . '/Packages/' . $gzfilename)) {
            $packageInfo = read_tgz_file($boarddir . '/Packages/' . $gzfilename, '*/package-info.xml', true);
        } elseif (file_exists($boarddir . '/Packages/' . $gzfilename . '/package-info.xml')) {
            $packageInfo = file_get_contents($boarddir . '/Packages/' . $gzfilename . '/package-info.xml');
        } else {
            return false;
        }
    }
    // Parse package-info.xml into an xmlArray.
    $packageInfo = new xmlArray($packageInfo);
    // !!! Error message of some sort?
    if (!$packageInfo->exists('package-info[0]')) {
        return false;
    }
    $packageInfo = $packageInfo->path('package-info[0]');
    $package = $packageInfo->to_array();
    $package['xml'] = $packageInfo;
    $package['filename'] = $gzfilename;
    if (!isset($package['type'])) {
        $package['type'] = 'modification';
    }
    return $package;
}
function AddLanguage()
{
    global $context, $sourcedir, $forum_version, $boarddir, $txt, $smcFunc, $scripturl;
    // Are we searching for new languages courtesy of Simple Machines?
    if (!empty($_POST['smf_add_sub'])) {
        // Need fetch_web_data.
        require_once $sourcedir . '/Subs-Package.php';
        $context['smf_search_term'] = htmlspecialchars(trim($_POST['smf_add']));
        // We're going to use this URL.
        $url = 'http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => '')));
        // Load the class file and stick it into an array.
        loadClassFile('Class-Package.php');
        $language_list = new xmlArray(fetch_web_data($url), true);
        // Check it exists.
        if (!$language_list->exists('languages')) {
            $context['smf_error'] = 'no_response';
        } else {
            $language_list = $language_list->path('languages[0]');
            $lang_files = $language_list->set('language');
            $context['smf_languages'] = array();
            foreach ($lang_files as $file) {
                // Were we searching?
                if (!empty($context['smf_search_term']) && strpos($file->fetch('name'), $smcFunc['strtolower']($context['smf_search_term'])) === false) {
                    continue;
                }
                $context['smf_languages'][] = array('id' => $file->fetch('id'), 'name' => $smcFunc['ucwords']($file->fetch('name')), 'version' => $file->fetch('version'), 'utf8' => $file->fetch('utf8'), 'description' => $file->fetch('description'), 'link' => $scripturl . '?action=admin;area=languages;sa=downloadlang;did=' . $file->fetch('id') . ';' . $context['session_var'] . '=' . $context['session_id']);
            }
            if (empty($context['smf_languages'])) {
                $context['smf_error'] = 'no_files';
            }
        }
    }
    $context['sub_template'] = 'add_language';
}
Beispiel #22
0
/**
 *
 * Enter description here ...
 * @param string $openid_url
 * @return bool|array
 */
function smf_openID_getServerInfo($openid_url)
{
    global $sourcedir;
    require_once $sourcedir . '/Subs-Package.php';
    // Get the html and parse it for the openid variable which will tell us where to go.
    $webdata = fetch_web_data($openid_url);
    if (empty($webdata)) {
        return false;
    }
    $response_data = array();
    // Some OpenID servers have strange but still valid HTML which makes our job hard.
    if (preg_match_all('~<link([\\s\\S]*?)/?>~i', $webdata, $link_matches) == 0) {
        fatal_lang_error('openid_server_bad_response');
    }
    foreach ($link_matches[1] as $link_match) {
        if (preg_match('~rel="([\\s\\S]*?)"~i', $link_match, $rel_match) == 0 || preg_match('~href="([\\s\\S]*?)"~i', $link_match, $href_match) == 0) {
            continue;
        }
        $rels = preg_split('~\\s+~', $rel_match[1]);
        foreach ($rels as $rel) {
            if (preg_match('~openid2?\\.(server|delegate|provider)~i', $rel, $match) != 0) {
                $response_data[$match[1]] = $href_match[1];
            }
        }
    }
    if (empty($response_data['server'])) {
        if (empty($response_data['provider'])) {
            fatal_lang_error('openid_server_bad_response');
        } else {
            $response_data['server'] = $response_data['provider'];
        }
    }
    return $response_data;
}
function sp_validate_php($code)
{
    global $boardurl, $boarddir, $sourcedir, $modSettings;
    $id = time();
    $token = md5(mt_rand() . session_id() . (string) microtime() . $modSettings['rand_seed']);
    $error = false;
    $filename = 'sp_tmp_' . $id . '.php';
    $code = trim($code);
    if (substr($code, 0, 5) == '<?php') {
        $code = substr($code, 5);
    }
    if (substr($code, -2) == '?>') {
        $code = substr($code, 0, -2);
    }
    require_once $sourcedir . '/Subs-Package.php';
    $content = '<?php

if (empty($_GET[\'token\']) || $_GET[\'token\'] !== \'' . $token . '\')
	exit();

require_once(\'' . $boarddir . '/SSI.php\');

' . $code . '

?>';
    $fp = fopen($boarddir . '/' . $filename, 'w');
    fwrite($fp, $content);
    fclose($fp);
    if (!file_exists($boarddir . '/' . $filename)) {
        return false;
    }
    $result = fetch_web_data($boardurl . '/' . $filename . '?token=' . $token);
    if ($result === false) {
        $error = 'database';
    } elseif (preg_match('~ <b>(\\d+)</b><br( /)?' . '>$~i', $result) != 0) {
        $error = 'syntax';
    }
    unlink($boarddir . '/' . $filename);
    return $error;
}
Beispiel #24
0
function profileSaveAvatarData(&$value)
{
    global $modSettings, $sourcedir, $smcFunc, $profile_vars, $cur_profile, $context;
    $memID = $context['id_member'];
    if (empty($memID) && !empty($context['password_auth_failed'])) {
        return false;
    }
    require_once $sourcedir . '/ManageAttachments.php';
    // We need to know where we're going to be putting it..
    if (!empty($modSettings['custom_avatar_enabled'])) {
        $uploadDir = $modSettings['custom_avatar_dir'];
        $id_folder = 1;
    } elseif (!empty($modSettings['currentAttachmentUploadDir'])) {
        if (!is_array($modSettings['attachmentUploadDir'])) {
            $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
        }
        // Just use the current path for temp files.
        $uploadDir = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
        $id_folder = $modSettings['currentAttachmentUploadDir'];
    } else {
        $uploadDir = $modSettings['attachmentUploadDir'];
        $id_folder = 1;
    }
    $downloadedExternalAvatar = false;
    if ($value == 'external' && allowedTo('profile_remote_avatar') && strtolower(substr($_POST['userpicpersonal'], 0, 7)) == 'http://' && strlen($_POST['userpicpersonal']) > 7 && !empty($modSettings['avatar_download_external'])) {
        if (!is_writable($uploadDir)) {
            fatal_lang_error('attachments_no_write', 'critical');
        }
        require_once $sourcedir . '/Subs-Package.php';
        $url = parse_url($_POST['userpicpersonal']);
        $contents = fetch_web_data('http://' . $url['host'] . (empty($url['port']) ? '' : ':' . $url['port']) . str_replace(' ', '%20', trim($url['path'])));
        if ($contents != false && ($tmpAvatar = fopen($uploadDir . '/avatar_tmp_' . $memID, 'wb'))) {
            fwrite($tmpAvatar, $contents);
            fclose($tmpAvatar);
            $downloadedExternalAvatar = true;
            $_FILES['attachment']['tmp_name'] = $uploadDir . '/avatar_tmp_' . $memID;
        }
    }
    if ($value == 'none') {
        $profile_vars['avatar'] = '';
        // Reset the attach ID.
        $cur_profile['id_attach'] = 0;
        $cur_profile['attachment_type'] = 0;
        $cur_profile['filename'] = '';
        removeAttachments(array('id_member' => $memID));
    } elseif ($value == 'server_stored' && allowedTo('profile_server_avatar')) {
        $profile_vars['avatar'] = strtr(empty($_POST['file']) ? empty($_POST['cat']) ? '' : $_POST['cat'] : $_POST['file'], array('&amp;' => '&'));
        $profile_vars['avatar'] = preg_match('~^([\\w _!@%*=\\-#()\\[\\]&.,]+/)?[\\w _!@%*=\\-#()\\[\\]&.,]+$~', $profile_vars['avatar']) != 0 && preg_match('/\\.\\./', $profile_vars['avatar']) == 0 && file_exists($modSettings['avatar_directory'] . '/' . $profile_vars['avatar']) ? $profile_vars['avatar'] == 'blank.gif' ? '' : $profile_vars['avatar'] : '';
        // Clear current profile...
        $cur_profile['id_attach'] = 0;
        $cur_profile['attachment_type'] = 0;
        $cur_profile['filename'] = '';
        // Get rid of their old avatar. (if uploaded.)
        removeAttachments(array('id_member' => $memID));
    } elseif ($value == 'external' && allowedTo('profile_remote_avatar') && strtolower(substr($_POST['userpicpersonal'], 0, 7)) == 'http://' && empty($modSettings['avatar_download_external'])) {
        // We need these clean...
        $cur_profile['id_attach'] = 0;
        $cur_profile['attachment_type'] = 0;
        $cur_profile['filename'] = '';
        // Remove any attached avatar...
        removeAttachments(array('id_member' => $memID));
        $profile_vars['avatar'] = str_replace('%20', '', preg_replace('~action(?:=|%3d)(?!dlattach)~i', 'action-', $_POST['userpicpersonal']));
        if ($profile_vars['avatar'] == 'http://' || $profile_vars['avatar'] == 'http:///') {
            $profile_vars['avatar'] = '';
        } elseif (substr($profile_vars['avatar'], 0, 7) != 'http://') {
            return 'bad_avatar';
        } elseif (!empty($modSettings['avatar_max_height_external']) || !empty($modSettings['avatar_max_width_external'])) {
            // Now let's validate the avatar.
            $sizes = url_image_size($profile_vars['avatar']);
            if (is_array($sizes) && ($sizes[0] > $modSettings['avatar_max_width_external'] && !empty($modSettings['avatar_max_width_external']) || $sizes[1] > $modSettings['avatar_max_height_external'] && !empty($modSettings['avatar_max_height_external']))) {
                // Houston, we have a problem. The avatar is too large!!
                if ($modSettings['avatar_action_too_large'] == 'option_refuse') {
                    return 'bad_avatar';
                } elseif ($modSettings['avatar_action_too_large'] == 'option_download_and_resize') {
                    require_once $sourcedir . '/Subs-Graphics.php';
                    if (downloadAvatar($profile_vars['avatar'], $memID, $modSettings['avatar_max_width_external'], $modSettings['avatar_max_height_external'])) {
                        $profile_vars['avatar'] = '';
                        $cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
                        $cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
                        $cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
                    } else {
                        return 'bad_avatar';
                    }
                }
            }
        }
    } elseif ($value == 'upload' && allowedTo('profile_upload_avatar') || $downloadedExternalAvatar) {
        if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '' || $downloadedExternalAvatar) {
            // Get the dimensions of the image.
            if (!$downloadedExternalAvatar) {
                if (!is_writable($uploadDir)) {
                    fatal_lang_error('attachments_no_write', 'critical');
                }
                if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadDir . '/avatar_tmp_' . $memID)) {
                    fatal_lang_error('attach_timeout', 'critical');
                }
                $_FILES['attachment']['tmp_name'] = $uploadDir . '/avatar_tmp_' . $memID;
            }
            $sizes = @getimagesize($_FILES['attachment']['tmp_name']);
            // No size, then it's probably not a valid pic.
            if ($sizes === false) {
                return 'bad_avatar';
            } elseif (!empty($modSettings['avatar_max_width_upload']) && $sizes[0] > $modSettings['avatar_max_width_upload'] || !empty($modSettings['avatar_max_height_upload']) && $sizes[1] > $modSettings['avatar_max_height_upload']) {
                if (!empty($modSettings['avatar_resize_upload'])) {
                    // Attempt to chmod it.
                    @chmod($uploadDir . '/avatar_tmp_' . $memID, 0644);
                    require_once $sourcedir . '/Subs-Graphics.php';
                    if (!downloadAvatar($uploadDir . '/avatar_tmp_' . $memID, $memID, $modSettings['avatar_max_width_upload'], $modSettings['avatar_max_height_upload'])) {
                        return 'bad_avatar';
                    }
                    // Reset attachment avatar data.
                    $cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
                    $cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
                    $cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
                } else {
                    return 'bad_avatar';
                }
            } elseif (is_array($sizes)) {
                // Now try to find an infection.
                require_once $sourcedir . '/Subs-Graphics.php';
                if (!checkImageContents($_FILES['attachment']['tmp_name'], !empty($modSettings['avatar_paranoid']))) {
                    // It's bad. Try to re-encode the contents?
                    if (empty($modSettings['avatar_reencode']) || !reencodeImage($_FILES['attachment']['tmp_name'], $sizes[2])) {
                        return 'bad_avatar';
                    }
                    // We were successful. However, at what price?
                    $sizes = @getimagesize($_FILES['attachment']['tmp_name']);
                    // Hard to believe this would happen, but can you bet?
                    if ($sizes === false) {
                        return 'bad_avatar';
                    }
                }
                $extensions = array('1' => 'gif', '2' => 'jpg', '3' => 'png', '6' => 'bmp');
                $extension = isset($extensions[$sizes[2]]) ? $extensions[$sizes[2]] : 'bmp';
                $mime_type = 'image/' . ($extension === 'jpg' ? 'jpeg' : ($extension === 'bmp' ? 'x-ms-bmp' : $extension));
                $destName = 'avatar_' . $memID . '_' . time() . '.' . $extension;
                list($width, $height) = getimagesize($_FILES['attachment']['tmp_name']);
                $file_hash = empty($modSettings['custom_avatar_enabled']) ? getAttachmentFilename($destName, false, null, true) : '';
                // Remove previous attachments this member might have had.
                removeAttachments(array('id_member' => $memID));
                $smcFunc['db_insert']('', '{db_prefix}attachments', array('id_member' => 'int', 'attachment_type' => 'int', 'filename' => 'string', 'file_hash' => 'string', 'fileext' => 'string', 'size' => 'int', 'width' => 'int', 'height' => 'int', 'mime_type' => 'string', 'id_folder' => 'int'), array($memID, empty($modSettings['custom_avatar_enabled']) ? 0 : 1, $destName, $file_hash, $extension, filesize($_FILES['attachment']['tmp_name']), (int) $width, (int) $height, $mime_type, $id_folder), array('id_attach'));
                $cur_profile['id_attach'] = $smcFunc['db_insert_id']('{db_prefix}attachments', 'id_attach');
                $cur_profile['filename'] = $destName;
                $cur_profile['attachment_type'] = empty($modSettings['custom_avatar_enabled']) ? 0 : 1;
                $destinationPath = $uploadDir . '/' . (empty($file_hash) ? $destName : $cur_profile['id_attach'] . '_' . $file_hash);
                if (!rename($_FILES['attachment']['tmp_name'], $destinationPath)) {
                    // I guess a man can try.
                    removeAttachments(array('id_member' => $memID));
                    fatal_lang_error('attach_timeout', 'critical');
                }
                // Attempt to chmod it.
                @chmod($uploadDir . '/' . $destinationPath, 0644);
            }
            $profile_vars['avatar'] = '';
            // Delete any temporary file.
            if (file_exists($uploadDir . '/avatar_tmp_' . $memID)) {
                @unlink($uploadDir . '/avatar_tmp_' . $memID);
            }
        } else {
            $profile_vars['avatar'] = '';
        }
    } else {
        $profile_vars['avatar'] = '';
    }
    // Setup the profile variables so it shows things right on display!
    $cur_profile['avatar'] = $profile_vars['avatar'];
    return false;
}
Beispiel #25
0
function PackageDownload()
{
    global $txt, $scripturl, $boarddir, $context, $sourcedir, $smcFunc;
    // Use the downloaded sub template.
    $context['sub_template'] = 'downloaded';
    // Security is good...
    checkSession('get');
    // To download something, we need a valid server or url.
    if (empty($_GET['server']) && (!empty($_GET['get']) && !empty($_REQUEST['package']))) {
        fatal_lang_error('package_get_error_is_zero', false);
    }
    if (isset($_GET['server'])) {
        $server = (int) $_GET['server'];
        // Query the server table to find the requested server.
        $request = $smcFunc['db_query']('', '
			SELECT name, url
			FROM {db_prefix}package_servers
			WHERE id_server = {int:current_server}
			LIMIT 1', array('current_server' => $server));
        list($name, $url) = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);
        // If server does not exist then dump out.
        if (empty($url)) {
            fatal_lang_error('couldnt_connect', false);
        }
        $url = $url . '/';
    } else {
        // Initialize the requried variables.
        $server = '';
        $url = '';
    }
    if (isset($_REQUEST['byurl']) && !empty($_POST['filename'])) {
        $package_name = basename($_REQUEST['filename']);
    } else {
        $package_name = basename($_REQUEST['package']);
    }
    if (isset($_REQUEST['conflict']) || isset($_REQUEST['auto']) && file_exists($boarddir . '/Packages/' . $package_name)) {
        // Find the extension, change abc.tar.gz to abc_1.tar.gz...
        if (strrpos(substr($package_name, 0, -3), '.') !== false) {
            $ext = substr($package_name, strrpos(substr($package_name, 0, -3), '.'));
            $package_name = substr($package_name, 0, strrpos(substr($package_name, 0, -3), '.')) . '_';
        } else {
            $ext = '';
        }
        // Find the first available.
        $i = 1;
        while (file_exists($boarddir . '/Packages/' . $package_name . $i . $ext)) {
            $i++;
        }
        $package_name = $package_name . $i . $ext;
    }
    // First make sure it's a package.
    $packageInfo = getPackageInfo($url . $_REQUEST['package']);
    if (!is_array($packageInfo)) {
        fatal_lang_error($packageInfo);
    }
    // Use FTP if necessary.
    create_chmod_control(array($boarddir . '/Packages/' . $package_name), array('destination_url' => $scripturl . '?action=admin;area=packages;get;sa=download' . (isset($_GET['server']) ? ';server=' . $_GET['server'] : '') . (isset($_REQUEST['auto']) ? ';auto' : '') . ';package=' . $_REQUEST['package'] . (isset($_REQUEST['conflict']) ? ';conflict' : '') . ';' . $context['session_var'] . '=' . $context['session_id'], 'crash_on_error' => true));
    package_put_contents($boarddir . '/Packages/' . $package_name, fetch_web_data($url . $_REQUEST['package']));
    // Done!  Did we get this package automatically?
    if (preg_match('~^http://[\\w_\\-]+\\.simplemachines\\.org/~', $_REQUEST['package']) == 1 && strpos($_REQUEST['package'], 'dlattach') === false && isset($_REQUEST['auto'])) {
        redirectexit('action=admin;area=packages;sa=install;package=' . $package_name);
    }
    // You just downloaded a mod from SERVER_NAME_GOES_HERE.
    $context['package_server'] = $server;
    $context['package'] = getPackageInfo($package_name);
    if (!is_array($context['package'])) {
        fatal_lang_error('package_cant_download', false);
    }
    if ($context['package']['type'] == 'modification') {
        $context['package']['install']['link'] = '<a href="' . $scripturl . '?action=admin;area=packages;sa=install;package=' . $context['package']['filename'] . '">[ ' . $txt['install_mod'] . ' ]</a>';
    } elseif ($context['package']['type'] == 'avatar') {
        $context['package']['install']['link'] = '<a href="' . $scripturl . '?action=admin;area=packages;sa=install;package=' . $context['package']['filename'] . '">[ ' . $txt['use_avatars'] . ' ]</a>';
    } elseif ($context['package']['type'] == 'language') {
        $context['package']['install']['link'] = '<a href="' . $scripturl . '?action=admin;area=packages;sa=install;package=' . $context['package']['filename'] . '">[ ' . $txt['add_languages'] . ' ]</a>';
    } else {
        $context['package']['install']['link'] = '';
    }
    $context['package']['list_files']['link'] = '<a href="' . $scripturl . '?action=admin;area=packages;sa=list;package=' . $context['package']['filename'] . '">[ ' . $txt['list_files'] . ' ]</a>';
    // Free a little bit of memory...
    unset($context['package']['xml']);
    $context['page_title'] = $txt['download_success'];
}
Beispiel #26
0
function makeAvatarChanges($memID, &$post_errors)
{
    global $modSettings, $sourcedir, $db_prefix;
    if (!isset($_POST['avatar_choice']) || empty($memID)) {
        return;
    }
    require_once $sourcedir . '/ManageAttachments.php';
    $uploadDir = empty($modSettings['custom_avatar_enabled']) ? $modSettings['attachmentUploadDir'] : $modSettings['custom_avatar_dir'];
    $downloadedExternalAvatar = false;
    if ($_POST['avatar_choice'] == 'external' && allowedTo('profile_remote_avatar') && strtolower(substr($_POST['userpicpersonal'], 0, 7)) == 'http://' && strlen($_POST['userpicpersonal']) > 7 && !empty($modSettings['avatar_download_external'])) {
        if (!is_writable($uploadDir)) {
            fatal_lang_error('attachments_no_write');
        }
        require_once $sourcedir . '/Subs-Package.php';
        $url = parse_url($_POST['userpicpersonal']);
        $contents = fetch_web_data('http://' . $url['host'] . (empty($url['port']) ? '' : ':' . $url['port']) . $url['path']);
        if ($contents != false && ($tmpAvatar = fopen($uploadDir . '/avatar_tmp_' . $memID, 'wb'))) {
            fwrite($tmpAvatar, $contents);
            fclose($tmpAvatar);
            $downloadedExternalAvatar = true;
            $_FILES['attachment']['tmp_name'] = $uploadDir . '/avatar_tmp_' . $memID;
        }
    }
    if ($_POST['avatar_choice'] == 'server_stored' && allowedTo('profile_server_avatar')) {
        $_POST['avatar'] = strtr(empty($_POST['file']) ? empty($_POST['cat']) ? '' : $_POST['cat'] : $_POST['file'], array('&amp;' => '&'));
        $_POST['avatar'] = preg_match('~^([\\w _!@%*=\\-#()\\[\\]&.,]+/)?[\\w _!@%*=\\-#()\\[\\]&.,]+$~', $_POST['avatar']) != 0 && preg_match('/\\.\\./', $_POST['avatar']) == 0 && file_exists($modSettings['avatar_directory'] . '/' . $_POST['avatar']) ? $_POST['avatar'] == 'blank.gif' ? '' : $_POST['avatar'] : '';
        // Get rid of their old avatar. (if uploaded.)
        removeAttachments('a.ID_MEMBER = ' . $memID);
    } elseif ($_POST['avatar_choice'] == 'external' && allowedTo('profile_remote_avatar') && strtolower(substr($_POST['userpicpersonal'], 0, 7)) == 'http://' && empty($modSettings['avatar_download_external'])) {
        // Remove any attached avatar...
        removeAttachments('a.ID_MEMBER = ' . $memID);
        $_POST['avatar'] = preg_replace('~action(=|%3d)(?!dlattach)~i', 'action-', $_POST['userpicpersonal']);
        if ($_POST['avatar'] == 'http://' || $_POST['avatar'] == 'http:///') {
            $_POST['avatar'] = '';
        } elseif (substr($_POST['avatar'], 0, 7) != 'http://') {
            $post_errors[] = 'bad_avatar';
        } elseif (!empty($modSettings['avatar_max_height_external']) || !empty($modSettings['avatar_max_width_external'])) {
            // Now let's validate the avatar.
            $sizes = url_image_size($_POST['avatar']);
            if (is_array($sizes) && ($sizes[0] > $modSettings['avatar_max_width_external'] && !empty($modSettings['avatar_max_width_external']) || $sizes[1] > $modSettings['avatar_max_height_external'] && !empty($modSettings['avatar_max_height_external']))) {
                // Houston, we have a problem. The avatar is too large!!
                if ($modSettings['avatar_action_too_large'] == 'option_refuse') {
                    $post_errors[] = 'bad_avatar';
                } elseif ($modSettings['avatar_action_too_large'] == 'option_download_and_resize') {
                    require_once $sourcedir . '/Subs-Graphics.php';
                    if (downloadAvatar($_POST['avatar'], $memID, $modSettings['avatar_max_width_external'], $modSettings['avatar_max_height_external'])) {
                        $_POST['avatar'] = '';
                    } else {
                        $post_errors[] = 'bad_avatar';
                    }
                }
            }
        }
    } elseif ($_POST['avatar_choice'] == 'upload' && allowedTo('profile_upload_avatar') || $downloadedExternalAvatar) {
        if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '' || $downloadedExternalAvatar) {
            // Get the dimensions of the image.
            if (!$downloadedExternalAvatar) {
                if (!is_writable($uploadDir)) {
                    fatal_lang_error('attachments_no_write');
                }
                if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadDir . '/avatar_tmp_' . $memID)) {
                    fatal_lang_error('smf124');
                }
                $_FILES['attachment']['tmp_name'] = $uploadDir . '/avatar_tmp_' . $memID;
            }
            $sizes = @getimagesize($_FILES['attachment']['tmp_name']);
            // No size, then it's probably not a valid pic.
            if ($sizes === false) {
                $post_errors[] = 'bad_avatar';
            } elseif (!empty($modSettings['avatar_max_width_upload']) && $sizes[0] > $modSettings['avatar_max_width_upload'] || !empty($modSettings['avatar_max_height_upload']) && $sizes[1] > $modSettings['avatar_max_height_upload']) {
                if (!empty($modSettings['avatar_resize_upload'])) {
                    // Attempt to chmod it.
                    @chmod($uploadDir . '/avatar_tmp_' . $memID, 0644);
                    require_once $sourcedir . '/Subs-Graphics.php';
                    downloadAvatar($uploadDir . '/avatar_tmp_' . $memID, $memID, $modSettings['avatar_max_width_upload'], $modSettings['avatar_max_height_upload']);
                } else {
                    $post_errors[] = 'bad_avatar';
                }
            } elseif (is_array($sizes)) {
                // Though not an exhaustive list, better safe than sorry.
                $fp = fopen($_FILES['attachment']['tmp_name'], 'rb');
                if (!$fp) {
                    fatal_lang_error('smf124');
                }
                // Now try to find an infection.
                while (!feof($fp)) {
                    if (preg_match('~(iframe|\\<\\?php|\\<\\?[\\s=]|\\<%[\\s=]|html|eval|body|script\\W)~', fgets($fp, 4096)) === 1) {
                        if (file_exists($uploadDir . '/avatar_tmp_' . $memID)) {
                            @unlink($uploadDir . '/avatar_tmp_' . $memID);
                        }
                        fatal_lang_error('smf124');
                    }
                }
                fclose($fp);
                $extensions = array('1' => '.gif', '2' => '.jpg', '3' => '.png', '6' => '.bmp');
                $extension = isset($extensions[$sizes[2]]) ? $extensions[$sizes[2]] : '.bmp';
                $destName = 'avatar_' . $memID . $extension;
                list($width, $height) = getimagesize($_FILES['attachment']['tmp_name']);
                // Remove previous attachments this member might have had.
                removeAttachments('a.ID_MEMBER = ' . $memID);
                $file_hash = empty($modSettings['custom_avatar_enabled']) ? getAttachmentFilename($destName, false, true) : '';
                db_query("\n\t\t\t\t\tINSERT INTO {$db_prefix}attachments\n\t\t\t\t\t\t(ID_MEMBER, attachmentType, filename, file_hash, size, width, height)\n\t\t\t\t\tVALUES ({$memID}, " . (empty($modSettings['custom_avatar_enabled']) ? '0' : '1') . ", '{$destName}', '" . (empty($file_hash) ? "" : "{$file_hash}") . "', " . filesize($_FILES['attachment']['tmp_name']) . ", " . (int) $width . ", " . (int) $height . ")", __FILE__, __LINE__);
                $attachID = db_insert_id();
                // Try to move this avatar.
                $destinationPath = $uploadDir . '/' . (empty($file_hash) ? $destName : $attachID . '_' . $file_hash);
                if (!rename($_FILES['attachment']['tmp_name'], $destinationPath)) {
                    // The move failed, get rid of it and die.
                    db_query("\n\t\t\t\t\t\tDELETE FROM {$db_prefix}attachments\n\t\t\t\t\t\tWHERE ID_ATTACH = {$attachID}", __FILE__, __LINE__);
                    fatal_lang_error('smf124');
                }
                // Attempt to chmod it.
                @chmod($destinationPath, 0644);
            }
            $_POST['avatar'] = '';
            // Delete any temporary file.
            if (file_exists($uploadDir . '/avatar_tmp_' . $memID)) {
                @unlink($uploadDir . '/avatar_tmp_' . $memID);
            }
        } else {
            $_POST['avatar'] = '';
        }
    } else {
        $_POST['avatar'] = '';
    }
}
Beispiel #27
0
function resizeImageFile($source, $destination, $max_width, $max_height, $preferred_format = 0)
{
    global $sourcedir;
    // Nothing to do without GD
    if (!checkGD()) {
        return false;
    }
    static $default_formats = array('1' => 'gif', '2' => 'jpeg', '3' => 'png', '6' => 'bmp', '15' => 'wbmp');
    require_once $sourcedir . '/Subs-Package.php';
    @ini_set('memory_limit', '90M');
    $success = false;
    // Get the image file, we have to work with something after all
    $fp_destination = fopen($destination, 'wb');
    if ($fp_destination && substr($source, 0, 7) == 'http://') {
        $fileContents = fetch_web_data($source);
        fwrite($fp_destination, $fileContents);
        fclose($fp_destination);
        $sizes = @getimagesize($destination);
    } elseif ($fp_destination) {
        $sizes = @getimagesize($source);
        $fp_source = fopen($source, 'rb');
        if ($fp_source !== false) {
            while (!feof($fp_source)) {
                fwrite($fp_destination, fread($fp_source, 8192));
            }
            fclose($fp_source);
        } else {
            $sizes = array(-1, -1, -1);
        }
        fclose($fp_destination);
    } else {
        $sizes = array(-1, -1, -1);
    }
    // Gif? That might mean trouble if gif support is not available.
    if ($sizes[2] == 1 && !function_exists('imagecreatefromgif') && function_exists('imagecreatefrompng')) {
        // Download it to the temporary file... use the special gif library... and save as png.
        if ($img = @gif_loadFile($destination) && gif_outputAsPng($img, $destination)) {
            $sizes[2] = 3;
        }
    }
    // A known and supported format?
    if (isset($default_formats[$sizes[2]]) && function_exists('imagecreatefrom' . $default_formats[$sizes[2]])) {
        $imagecreatefrom = 'imagecreatefrom' . $default_formats[$sizes[2]];
        if ($src_img = @$imagecreatefrom($destination)) {
            resizeImage($src_img, $destination, imagesx($src_img), imagesy($src_img), $max_width === null ? imagesx($src_img) : $max_width, $max_height === null ? imagesy($src_img) : $max_height, true, $preferred_format);
            $success = true;
        }
    }
    return $success;
}
Beispiel #28
0
 public static function facebook_dokeys()
 {
     global $sourcedir, $modSettings, $scripturl, $context;
     if (isset($_GET['code']) && !empty($_SESSION['safbKeys']) && $context['user']['is_logged'] && allowedTo('admin_forum')) {
         require_once $sourcedir . '/Subs-Package.php';
         //die($_GET['code']);
         ////////////////////////////access token/////////////////////////////////////
         $code = $_REQUEST['code'];
         //die($code);
         $token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $modSettings['fb_app_id'] . "&redirect_uri=" . urlencode($scripturl) . "&client_secret=" . $modSettings['fb_app_secret'] . "&code=" . $code;
         $fb_data = fetch_web_data($token_url);
         $params = null;
         parse_str($fb_data, $params);
         if (!empty($params['access_token'])) {
             updateSettings(array('fb_replytoken' => $params['access_token']));
         }
         /////////////////////////////App access token////////////////////////////////////
         $pub_data = $modSettings['fb_app_id'] . '|' . $modSettings['fb_app_secret'];
         updateSettings(array('fb_atoken' => $pub_data));
         /*$pubtoken_url = "https://graph.facebook.com/oauth/access_token?client_id=" .$modSettings['fb_app_id']."&client_secret=".$modSettings['fb_app_secret']."&type=client_cred";
         
         			$pub_data = fetch_web_data($pubtoken_url);
         
         			if (strpos($pub_data,'access_token=') !== false) {
         				$pub_data = str_replace('access_token=','',$pub_data);
         			}
         
         			updateSettings(array('fb_atoken' => $pub_data));*/
         /////////////////////////////Page access token////////////////////////////////////
         if (!empty($modSettings['fb_admin_pid'])) {
             $facebook = new Facebook(array('appId' => $modSettings['fb_app_id'], 'secret' => $modSettings['fb_app_secret']));
             $page_info = $facebook->api('/' . $modSettings['fb_admin_pid'] . '?fields=access_token');
             if (!empty($page_info['access_token'])) {
                 updateSettings(array('fb_app_atokenpage' => $page_info['access_token']));
             }
         }
         $_SESSION['safbKeys'] = false;
         redirectexit('action=admin;area=facebook;sa=publisher');
     }
 }
Beispiel #29
0
function template_include($filename, $once = false)
{
    global $context, $settings, $options, $txt, $scripturl, $modSettings;
    global $language_dir, $user_info, $boardurl, $boarddir, $sourcedir;
    global $maintenance, $mtitle, $mmessage;
    static $templates = array();
    // We want to be able to figure out any errors...
    @ini_set('track_errors', '1');
    // Don't include the file more than once, if $once is true.
    if ($once && in_array($filename, $templates)) {
        return;
    } else {
        $templates[] = $filename;
    }
    // Are we going to use eval?
    if (empty($modSettings['disableTemplateEval'])) {
        $file_found = file_exists($filename) && eval('?' . '>' . rtrim(file_get_contents($filename))) !== false;
        $settings['current_include_filename'] = $filename;
    } else {
        $file_found = file_exists($filename);
        if ($once && $file_found) {
            require_once $filename;
        } elseif ($file_found) {
            require $filename;
        }
    }
    if ($file_found !== true) {
        ob_end_clean();
        if (!empty($modSettings['enableCompressedOutput'])) {
            @ob_start('ob_gzhandler');
        } else {
            ob_start();
        }
        if (isset($_GET['debug']) && !WIRELESS) {
            header('Content-Type: application/xhtml+xml; charset=' . (empty($context['character_set']) ? 'ISO-8859-1' : $context['character_set']));
        }
        // Don't cache error pages!!
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: no-cache');
        if (!isset($txt['template_parse_error'])) {
            $txt['template_parse_error'] = 'Template Parse Error!';
            $txt['template_parse_error_message'] = 'It seems something has gone sour on the forum with the template system.  This problem should only be temporary, so please come back later and try again.  If you continue to see this message, please contact the administrator.<br /><br />You can also try <a href="javascript:location.reload();">refreshing this page</a>.';
            $txt['template_parse_error_details'] = 'There was a problem loading the <tt><b>%1$s</b></tt> template or language file.  Please check the syntax and try again - remember, single quotes (<tt>\'</tt>) often have to be escaped with a slash (<tt>\\</tt>).  To see more specific error information from PHP, try <a href="' . $boardurl . '%1$s" target="_blank">accessing the file directly</a>.<br /><br />You may want to try to <a href="javascript:location.reload();">refresh this page</a> or <a href="' . $scripturl . '?theme=1">use the default theme</a>.';
        }
        // First, let's get the doctype and language information out of the way.
        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"', !empty($context['right_to_left']) ? ' dir="rtl"' : '', '>
	<head>';
        //		echo '<META HTTP-EQUIV="'.'control-cache''" CONTENT="no-cache">';
        if (isset($context['character_set'])) {
            echo '
		<meta http-equiv="Content-Type" content="text/html; charset=', $context['character_set'], '" />';
        }
        if (!empty($maintenance) && !allowedTo('admin_forum')) {
            echo '
		<title>', $mtitle, '</title>
	</head>
	<body>
		<h3>', $mtitle, '</h3>
		', $mmessage, '
	</body>
</html>';
        } elseif (!allowedTo('admin_forum')) {
            echo '
		<title>', $txt['template_parse_error'], '</title>
	</head>
	<body>
		<h3>', $txt['template_parse_error'], '</h3>
		', $txt['template_parse_error_message'], '
	</body>
</html>';
        } else {
            require_once $sourcedir . '/Subs-Package.php';
            $error = fetch_web_data($boardurl . strtr($filename, array($boarddir => '', strtr($boarddir, '\\', '/') => '')));
            if (empty($error)) {
                $error = $php_errormsg;
            }
            echo '
		<title>', $txt['template_parse_error'], '</title>
	</head>
	<body>
		<h3>', $txt['template_parse_error'], '</h3>
		', sprintf($txt['template_parse_error_details'], strtr($filename, array($boarddir => '', strtr($boarddir, '\\', '/') => '')));
            if (!empty($error)) {
                echo '
		<hr />

		<div style="margin: 0 20px;"><tt>', strtr(strtr($error, array('<b>' . $boarddir => '<b>...', '<b>' . strtr($boarddir, '\\', '/') => '<b>...')), '\\', '/'), '</tt></div>';
            }
            // I know, I know... this is VERY COMPLICATED.  Still, it's good.
            if (preg_match('~ <b>(\\d+)</b><br( /)?' . '>$~i', $error, $match) != 0) {
                $data = file($filename);
                $data2 = highlight_php_code(implode('', $data));
                $data2 = preg_split('~\\<br( /)?\\>~', $data2);
                // Fix the PHP code stuff...
                if ($context['browser']['is_ie4'] || $context['browser']['is_ie5'] || $context['browser']['is_ie5.5']) {
                    $data2 = str_replace("\t", "<pre style=\"display: inline;\">\t</pre>", $data2);
                } elseif (!$context['browser']['is_gecko']) {
                    $data2 = str_replace("\t", "<span style=\"white-space: pre;\">\t</span>", $data2);
                } else {
                    $data2 = str_replace("<pre style=\"display: inline;\">\t</pre>", "\t", $data2);
                }
                // Now we get to work around a bug in PHP where it doesn't escape <br />s!
                $j = -1;
                foreach ($data as $line) {
                    $j++;
                    if (substr_count($line, '<br />') == 0) {
                        continue;
                    }
                    $n = substr_count($line, '<br />');
                    for ($i = 0; $i < $n; $i++) {
                        $data2[$j] .= '&lt;br /&gt;' . $data2[$j + $i + 1];
                        unset($data2[$j + $i + 1]);
                    }
                    $j += $n;
                }
                $data2 = array_values($data2);
                array_unshift($data2, '');
                echo '
		<div style="margin: 2ex 20px; width: 96%; overflow: auto;"><pre style="margin: 0;">';
                // Figure out what the color coding was before...
                $line = max($match[1] - 9, 1);
                $last_line = '';
                for ($line2 = $line - 1; $line2 > 1; $line2--) {
                    if (strpos($data2[$line2], '<') !== false) {
                        if (preg_match('~(<[^/>]+>)[^<]*$~', $data2[$line2], $color_match) != 0) {
                            $last_line = $color_match[1];
                        }
                        break;
                    }
                }
                // Show the relevant lines...
                for ($n = min($match[1] + 4, count($data2) + 1); $line <= $n; $line++) {
                    if ($line == $match[1]) {
                        echo '</pre><div style="background-color: #ffb0b5;"><pre style="margin: 0;">';
                    }
                    echo '<span style="color: black;">', sprintf('%' . strlen($n) . 's', $line), ':</span> ';
                    if ($data2[$line] != '') {
                        echo substr($data2[$line], 0, 2) == '</' ? preg_replace('~^</[^>]+>~', '', $data2[$line]) : $last_line . $data2[$line];
                    }
                    if (preg_match('~(<[^/>]+>)[^<]*$~', $data2[$line], $color_match) != 0) {
                        $last_line = $color_match[1];
                        echo '</', substr($last_line, 1, 4), '>';
                    } elseif ($last_line != '' && strpos($data2[$line], '<') !== false) {
                        $last_line = '';
                    } elseif ($last_line != '' && $data2[$line] != '') {
                        echo '</', substr($last_line, 1, 4), '>';
                    }
                    if ($line == $match[1]) {
                        echo '</pre></div><pre style="margin: 0;">';
                    } else {
                        echo "\n";
                    }
                }
                echo '</pre></div>';
            }
            echo '
	</body>
</html>';
        }
        die;
    }
}
function getFile($adkfile = '')
{
    global $sourcedir, $context, $getFile, $txt;
    require_once $sourcedir . '/Subs-Package.php';
    if (empty($adkfile)) {
        $getFile = '';
    } else {
        $checkUrl = checkUrl($adkfile);
        if (!$checkUrl) {
            $getFile = '';
        } else {
            $getFile = fetch_web_data($adkfile);
        }
    }
    return $getFile;
}