コード例 #1
0
ファイル: sitemap.php プロジェクト: erico-deh/ocPortal
/**
 * Top level function to (re)generate a Sitemap (xml file, Google-style).
 */
function sitemaps_build()
{
    $GLOBALS['NO_QUERY_LIMIT'] = true;
    $path = get_custom_file_base() . '/ocp_sitemap.xml';
    if (!file_exists($path)) {
        if (!is_writable_wrap(dirname($path))) {
            warn_exit(do_lang_tempcode('WRITE_ERROR_CREATE', escape_html('/')));
        }
    } else {
        if (!is_writable_wrap($path)) {
            warn_exit(do_lang_tempcode('WRITE_ERROR', escape_html('ocp_sitemap.xml')));
        }
    }
    // Runs via a callback mechanism, so we don't need to load an arbitrary complex structure into memory.
    sitemaps_xml_initialise($path);
    spawn_page_crawl('pagelink_to_sitemapsxml', $GLOBALS['FORUM_DRIVER']->get_guest_id(), NULL, DEPTH__ENTRIES);
    sitemaps_xml_finished();
    // Ping search engines
    if (get_option('auto_submit_sitemap') == '1') {
        $ping = true;
        $base_url = get_base_url();
        $not_local = substr($base_url, 0, 16) != 'http://localhost' && substr($base_url, 0, 16) != 'http://127.0.0.1' && substr($base_url, 0, 15) != 'http://192.168.' && substr($base_url, 0, 10) != 'http://10.';
        if ($ping && get_option('site_closed') == '0' && $not_local) {
            // Submit to search engines
            $services = array('http://www.google.com/webmasters/tools/ping?sitemap=', 'http://submissions.ask.com/ping?sitemap=', 'http://www.bing.com/webmaster/ping.aspx?siteMap=', 'http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=SitemapWriter&url=');
            foreach ($services as $service) {
                http_download_file($service . urlencode(get_custom_base_url() . '/ocp_sitemap.xml'), NULL, false);
            }
        }
    }
}
コード例 #2
0
ファイル: version2.php プロジェクト: erico-deh/ocPortal
/**
 * Get information about new versions of ocPortal (or more accurately, what's wrong with this version).
 *
 * @return tempcode		Information about the installed ocPortal version
 */
function get_future_version_information()
{
    require_lang('version');
    $url = 'http://ocportal.com/version.php?version=' . rawurlencode(ocp_version_full()) . '&lang=' . rawurlencode(user_lang());
    $data = http_download_file($url, NULL, false);
    if (!is_null($data)) {
        $data = str_replace('"../upgrader.php"', '"' . get_base_url() . '/upgrader.php"', $data);
        if ($GLOBALS['XSS_DETECT']) {
            ocp_mark_as_escaped($data);
        }
        require_code('character_sets');
        $data = convert_to_internal_encoding($data);
        $table = new ocp_tempcode();
        $lines = explode(chr(10), $data);
        foreach ($lines as $line) {
            if (trim($line) != '') {
                $table->attach(paragraph($line));
            }
        }
        $table = make_string_tempcode(preg_replace('#<p>\\s*</p>#', '', $table->evaluate()));
    } else {
        $table = paragraph(do_lang_tempcode('CANNOT_CONNECT_HOME'), 'dfsdff32ffd');
    }
    require_code('xhtml');
    /*$table->attach('<script type="text/javascript">// <![CDATA[
    		window.open(\''.$url.'\');
    	//]]></script>');*/
    return make_string_tempcode(xhtmlise_html($table->evaluate()));
}
コード例 #3
0
 function retrieveGoogleSearch($searchTerms = "ocportal", $searchURL = "related:ocportal.com")
 {
     require_code('files');
     $googleBaseUrl = "http://ajax.googleapis.com/ajax/services/search/web";
     $googleBaseQuery = "?v=1.0&rsz=large&q=";
     $googleFullUrl = $googleBaseUrl . $googleBaseQuery . $searchURL . "%20" . $searchTerms;
     $returnGoogleSearch = http_download_file($googleFullUrl);
     $returnGoogleSearch = json_decode($returnGoogleSearch, true);
     return $returnGoogleSearch["responseData"]["results"];
 }
コード例 #4
0
 function testAdminZone()
 {
     if (function_exists('set_time_limit')) {
         @set_time_limit(0);
     }
     $result = http_download_file(get_base_url() . '/_tests/codechecker/phpdoc_parser.php', NULL, true, false, 'ocPortal', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 10000.0);
     foreach (explode('<br />', $result) as $line) {
         $this->assertTrue(trim($line) == '' || substr($line, 0, 4) == 'Done' || substr($line, 0, 6) == 'FINAL ' || strpos($line, 'TODO') !== false || strpos($line, 'HACKHACK') !== false, $line);
     }
 }
コード例 #5
0
ファイル: cqc_database.php プロジェクト: erico-deh/ocPortal
 function testDatabase()
 {
     if (function_exists('set_time_limit')) {
         @set_time_limit(0);
     }
     $result = http_download_file(get_base_url() . '/_tests/codechecker/code_quality.php?subdir=sources/database&api=1', NULL, true, false, 'ocPortal', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 10000.0);
     foreach (explode('<br />', $result) as $line) {
         $this->assertTrue(trim($line) == '' || substr($line, 0, 5) == 'SKIP:' || substr($line, 0, 5) == 'DONE ' || substr($line, 0, 6) == 'FINAL ' || strpos($line, 'TODO') !== false || strpos($line, 'HACKHACK') !== false, $line);
     }
 }
コード例 #6
0
ファイル: facebook.php プロジェクト: erico-deh/ocPortal
 /**
  * If we can handle this URL, get the thumbnail URL.
  *
  * @param  URLPATH		Video URL
  * @return ?string		The thumbnail URL (NULL: no match).
  */
 function get_video_thumbnail($src_url)
 {
     $matches = array();
     if (preg_match('#^http://www\\.facebook\\.com/video/video\\.php\\?v=(\\w+)#', $src_url, $matches) != 0) {
         require_code('files');
         $contents = http_download_file($src_url);
         if (preg_match('#addVariable\\("thumb_url", "([^"]*)"\\);#', $contents, $matches) != 0) {
             return rawurldecode(str_replace('\\u0025', '%', $matches[1]));
         }
     }
     return NULL;
 }
コード例 #7
0
ファイル: feedback.php プロジェクト: erico-deh/ocPortal
 /**
  * Standard modular run function for OcCLE hooks.
  *
  * @param  array	The options with which the command was called
  * @param  array	The parameters with which the command was called
  * @param  array	A reference to the OcCLE filesystem object
  * @return array	Array of stdcommand, stdhtml, stdout, and stderr responses
  */
 function run($options, $parameters, &$occle_fs)
 {
     if (array_key_exists('h', $options) || array_key_exists('help', $options)) {
         return array('', do_command_help('feedback', array('h'), array(true)), '', '');
     } else {
         if (!array_key_exists(0, $parameters)) {
             return array('', '', '', do_lang('MISSING_PARAM', '1', 'feedback'));
         }
         $url = 'http://ocportal.com/pg/feedback';
         $post = array('title' => 'OcCLE feedback', 'post' => '(From "' . get_custom_base_url() . '" via OcCLE.)[quote]' . $parameters[0] . '[/quote]');
         http_download_file($url, NULL, true, true, 'ocPortal', $post);
         return array('', '', do_lang('SUCCESS'), '');
     }
 }
コード例 #8
0
function run()
{
    $file = basename(rawurldecode($_GET['url']));
    //get old media file data
    $get_old_file = $GLOBALS['SITE_DB']->query('SELECT url FROM ' . get_table_prefix() . 'videos WHERE url LIKE "uploads/galleries/' . rawurlencode(basename(basename($file, '.m4v'), '.mp3')) . '%"');
    $type = 'galleries';
    if (!array_key_exists(0, $get_old_file)) {
        $get_old_file = $GLOBALS['SITE_DB']->query('SELECT a_url AS url FROM ' . get_table_prefix() . 'attachments WHERE a_url LIKE "uploads/attachments/' . rawurlencode(basename(basename($file, '.m4v'), '.mp3')) . '%"');
        $type = 'attachments';
        if (!array_key_exists(0, $get_old_file)) {
            $get_old_file = $GLOBALS['SITE_DB']->query('SELECT cv_value AS url FROM ' . get_table_prefix() . 'catalogue_efv_short WHERE cv_value LIKE "uploads/catalogues/' . rawurlencode(basename(basename($file, '.m4v'), '.mp3')) . '%"');
            $type = 'catalogues';
        }
    }
    require_code('files');
    $file_handle = @fopen(get_custom_file_base() . '/uploads/' . $type . '/' . $file, 'wb') or intelligent_write_error(get_custom_file_base() . '/uploads/' . $type . '/' . $file);
    http_download_file($_GET['url'], NULL, false, false, 'ocPortal', NULL, NULL, NULL, NULL, NULL, $file_handle, NULL, NULL, 6.0);
    fclose($file_handle);
    //move the old media file to the archive directory - '/uploads/'.$type.'/archive/'
    $new_url = 'uploads/' . $type . '/' . rawurlencode($file);
    if (isset($get_old_file[0]['url']) && is_string($get_old_file[0]['url']) && $get_old_file[0]['url'] != $new_url && strlen($get_old_file[0]['url']) > 0) {
        $movedir = dirname(str_replace('/uploads/' . $type . '/', '/uploads/' . $type . '_archive_addon/', str_replace('\\', '/', get_custom_file_base()) . '/' . rawurldecode($get_old_file[0]['url'])));
        @mkdir($movedir, 0777);
        require_code('files');
        fix_permissions($movedir, 0777);
        rename(str_replace('\\', '/', get_custom_file_base()) . '/' . rawurldecode($get_old_file[0]['url']), str_replace('/uploads/' . $type . '/', '/uploads/' . $type . '_archive_addon/', str_replace('\\', '/', get_custom_file_base()) . '/' . rawurldecode($get_old_file[0]['url'])));
    }
    switch ($type) {
        case 'galleries':
            $GLOBALS['SITE_DB']->query('UPDATE ' . get_table_prefix() . 'videos SET video_width=600,video_height=400,url="' . db_escape_string($new_url) . '" WHERE url LIKE "uploads/' . $type . '/' . db_escape_string(rawurlencode(basename(basename($file, '.m4v'), '.mp3'))) . '%"');
            // Replaces row that referenced $file without .m4v on the end (the original filename) with row that references the new $file we just copied
            break;
        case 'attachments':
            $GLOBALS['SITE_DB']->query('UPDATE ' . get_table_prefix() . 'attachments SET a_url="' . db_escape_string($new_url) . '" WHERE a_url LIKE "uploads/' . $type . '/' . db_escape_string(rawurlencode(basename(basename($file, '.m4v'), '.mp3'))) . '%"');
            // Replaces row that referenced $file without .m4v on the end (the original filename) with row that references the new $file we just copied
            break;
        case 'catalogues':
            $GLOBALS['SITE_DB']->query('UPDATE ' . get_table_prefix() . 'catalogue_efv_short SET cv_value="' . db_escape_string($new_url) . '" WHERE cv_value LIKE "uploads/' . $type . '/' . db_escape_string(rawurlencode(basename(basename($file, '.m4v'), '.mp3'))) . '%"');
            // Replaces row that referenced $file without .m4v on the end (the original filename) with row that references the new $file we just copied
            break;
    }
    $transcoding_server = get_option('transcoding_server', true);
    if (is_null($transcoding_server)) {
        //add option and default value
        add_config_option('TRANSCODING_SERVER', 'transcoding_server', 'line', 'return \'http://localhost/convertor\';', 'FEATURE', 'GALLERIES');
        $transcoding_server = get_option('transcoding_server', true);
    }
    file_get_contents($transcoding_server . '/move_to_sent.php?file=' . $_GET['url']);
}
コード例 #9
0
ファイル: side_network.php プロジェクト: erico-deh/ocPortal
 /**
  * Standard modular run function.
  *
  * @param  array		A map of parameters.
  * @return tempcode	The result of execution.
  */
 function run($map)
 {
     unset($map);
     require_css('side_blocks');
     $netlinks = get_option('network_links');
     if (strlen($netlinks) > 0) {
         require_code('character_sets');
         $data = http_download_file($netlinks, NULL, false);
         if (is_null($data)) {
             $if_network = do_lang_tempcode('HTTP_DOWNLOAD_NO_SERVER', escape_html($netlinks));
         } else {
             $if_network = make_string_tempcode(convert_to_internal_encoding($data));
         }
         return do_template('BLOCK_SIDE_NETWORK', array('_GUID' => '5fe8867b9f69670ad61e6c78b956fab2', 'CONTENT' => $if_network));
     }
     return new ocp_tempcode();
 }
コード例 #10
0
/**
 * Function to process the file upload process
 */
function incoming_uploads_script()
{
    $image_url_sub_for = get_param('image_url_sub_for', NULL);
    if ($image_url_sub_for !== NULL) {
        require_code('files');
        if (!url_is_local($image_url_sub_for) || strpos($image_url_sub_for, '/incoming/') !== false) {
            $url_to = 'uploads/website_specific/' . md5(uniqid('', true)) . '.png';
        } else {
            $url_to = dirname($image_url_sub_for) . '/' . md5(uniqid('', true)) . '.png';
        }
        $write_to_file = fopen($url_to, 'wb');
        http_download_file(either_param('imageurl'), NULL, true, false, 'ocPortal', NULL, NULL, NULL, NULL, NULL, $write_to_file);
        fclose($write_to_file);
        $GLOBALS['SITE_DB']->query_insert('image_url_sub_for', array('url_from' => $image_url_sub_for, 'url_to' => $url_to, 'member_id' => get_member(), 'expire' => time() + 60 * 60 * 24));
        exit;
    }
    non_overrided__incoming_uploads_script();
}
コード例 #11
0
ファイル: xmlrpc.php プロジェクト: erico-deh/ocPortal
/**
 * Do a highly-simplified XML-RPC request (no actual calling supported - just messaging).
 *
 * @param  URLPATH	The XML-RPC call URL
 * @param  string		The method name to call.
 * @param  array		An array of parameters.
 * @param  boolean	Whether to accept failure.
 * @return ?string	The result (NULL: failed).
 */
function xml_rpc($url, $method, $params, $accept_failure = false)
{
    $rpc = "\n<" . "?xml version=\"1.0\"?" . ">\n<methodCall>\n <methodName>{$method}</methodName>\n <params>\n";
    foreach ($params as $_value) {
        $value = _xml_rpc_type_convert($_value);
        $rpc .= <<<END

\t  <param>
\t\t\t<value>{$value}</value>
\t  </param>
END;
    }
    $rpc .= <<<END

 </params>
</methodCall>
END;
    $result = http_download_file($url, NULL, true, false, 'ocPortal', array('_' => $rpc));
    return $result;
}
コード例 #12
0
 /**
  * This will get the XML file from ocportal.com.
  *
  * @param  ?ID_TEXT		The ID to do under (NULL: root)
  * @return string			The XML file
  */
 function get_file($id)
 {
     $stub = get_param_integer('localhost', 0) == 1 ? get_base_url() : 'http://ocportal.com';
     $v = 'Version ' . float_to_raw_string(ocp_version_number(), 1);
     if (!is_null($id)) {
         $v = $id;
     }
     $url = $stub . '/data/ajax_tree.php?hook=choose_download&id=' . rawurlencode($v) . '&file_type=tar';
     require_code('character_sets');
     $contents = http_download_file($url);
     $utf = $GLOBALS['HTTP_CHARSET'] == 'utf-8';
     // We have to use 'U' in the regexp to work around a Chrome parser bug (we can't rely on convert_to_internal_encoding being 100% correct)
     require_code('character_sets');
     $contents = convert_to_internal_encoding($contents);
     $contents = preg_replace('#^\\s*\\<' . '\\?xml version="1.0" encoding="[^"]*"\\?' . '\\>\\<request\\>#' . ($utf ? 'U' : ''), '', $contents);
     $contents = preg_replace('#</request>#' . ($utf ? 'U' : ''), '', $contents);
     $contents = preg_replace('#<category [^>]*has_children="false"[^>]*>[^>]*</category>#' . ($utf ? 'U' : ''), '', $contents);
     $contents = preg_replace('#<category [^>]*title="Manual install required"[^>]*>[^>]*</category>#' . ($utf ? 'U' : ''), '', $contents);
     return $contents;
 }
コード例 #13
0
 /**
  * Standard modular run function.
  *
  * @param  array		A map of parameters.
  * @return tempcode	The result of execution.
  */
 function run($map)
 {
     require_lang('newsletter');
     require_lang('javascript');
     $newsletter_id = array_key_exists('param', $map) ? intval($map['param']) : db_get_first_id();
     $_newsletter_title = $GLOBALS['SITE_DB']->query_value_null_ok('newsletters', 'title', array('id' => $newsletter_id));
     if (is_null($_newsletter_title)) {
         return paragraph(do_lang_tempcode('MISSING_RESOURCE'));
     }
     $newsletter_title = get_translated_text($_newsletter_title);
     $address = post_param('address' . strval($newsletter_id), '');
     if ($address != '') {
         require_code('newsletter');
         require_code('type_validation');
         if (!is_valid_email_address($address)) {
             $msg = do_template('INLINE_WIP_MESSAGE', array('MESSAGE' => do_lang_tempcode('INVALID_EMAIL_ADDRESS')));
             return do_template('BLOCK_MAIN_NEWSLETTER_SIGNUP', array('URL' => get_self_url(), 'MSG' => $msg));
         }
         if (!array_key_exists('path', $map)) {
             $map['path'] = 'uploads/website_specific/signup.txt';
         }
         require_code('character_sets');
         $password = basic_newsletter_join($address, 4, NULL, !file_exists(get_custom_file_base() . '/' . $map['path']), $newsletter_id, post_param('firstname' . strval($newsletter_id), ''), post_param('lastname' . strval($newsletter_id), ''));
         if ($password == '') {
             return do_template('INLINE_WIP_MESSAGE', array('MESSAGE' => do_lang_tempcode('NEWSLETTER_THIS_ALSO')));
         }
         if ($password == do_lang('NA')) {
             $manage_url = build_url(array('page' => 'newsletter', 'email' => $address), get_module_zone('newsletter'));
             return do_template('INLINE_WIP_MESSAGE', array('MESSAGE' => do_lang_tempcode('ALREADY_EMAIL_ADDRESS', escape_html($manage_url->evaluate()))));
         }
         require_code('mail');
         if (file_exists(get_custom_file_base() . '/' . $map['path'])) {
             $url = (url_is_local($map['path']) ? get_custom_base_url() . '/' : '') . $map['path'];
             mail_wrap(array_key_exists('subject', $map) ? $map['subject'] : do_lang('WELCOME'), convert_to_internal_encoding(http_download_file($url)), array($address), array_key_exists('to', $map) ? $map['to'] : '', '', '', 3, NULL, false, NULL, true);
         }
         return do_template('BLOCK_MAIN_NEWSLETTER_SIGNUP_DONE', array('_GUID' => '9953c83685df4970de8f23fcd5dd15bb', 'NEWSLETTER_TITLE' => $newsletter_title, 'NID' => strval($newsletter_id), 'PASSWORD' => $password));
     } else {
         return do_template('BLOCK_MAIN_NEWSLETTER_SIGNUP', array('NEWSLETTER_TITLE' => $newsletter_title, 'NID' => strval($newsletter_id), 'URL' => get_self_url()));
     }
 }
コード例 #14
0
ファイル: occlechat.php プロジェクト: erico-deh/ocPortal
 /**
  * Standard modular run function for OcCLE hooks.
  *
  * @param  array	The options with which the command was called
  * @param  array	The parameters with which the command was called
  * @param  array	A reference to the OcCLE filesystem object
  * @return array	Array of stdcommand, stdhtml, stdout, and stderr responses
  */
 function run($options, $parameters, &$occle_fs)
 {
     if (array_key_exists('h', $options) || array_key_exists('help', $options)) {
         return array('', do_command_help('occlechat', array('h'), array(true, true)), '', '');
     } else {
         if (!array_key_exists(0, $parameters)) {
             return array('', '', '', do_lang('MISSING_PARAM', '1', 'occlechat'));
         }
         if (!array_key_exists(1, $parameters)) {
             return array('', '', '', do_lang('MISSING_PARAM', '2', 'occlechat'));
         }
         $GLOBALS['SITE_DB']->query_insert('occlechat', array('c_message' => $parameters[1], 'c_url' => $parameters[0], 'c_incoming' => 0, 'c_timestamp' => time()));
         $url = $parameters[0] . '/data/occle.php?action=message&base_url=' . urlencode(get_base_url()) . '&message=' . urlencode($parameters[1]);
         $return = http_download_file($url, NULL, false);
         if (is_null($return)) {
             return array('', '', '', do_lang('HTTP_DOWNLOAD_NO_SERVER', $parameters[0]));
         } elseif ($return == '1') {
             return array('', '', do_lang('SUCCESS'), '');
         } else {
             return array('', '', '', do_lang('INCOMPLETE_ERROR'));
         }
     }
 }
コード例 #15
0
ファイル: fix_perms.php プロジェクト: erico-deh/ocPortal
 /**
  * Standard modular run function for OcCLE hooks.
  *
  * @param  array	The options with which the command was called
  * @param  array	The parameters with which the command was called
  * @param  array	A reference to the OcCLE filesystem object
  * @return array	Array of stdcommand, stdhtml, stdout, and stderr responses
  */
 function run($options, $parameters, &$occle_fs)
 {
     require_code('xhtml');
     if (array_key_exists('h', $options) || array_key_exists('help', $options)) {
         return array('', do_command_help('fix_perms', array('h'), array(true, true, true)), '', '');
     } else {
         if (!array_key_exists(0, $parameters)) {
             return array('', '', '', do_lang('MISSING_PARAM', '1', 'fix_perms'));
         }
         if (!array_key_exists(1, $parameters)) {
             return array('', '', '', do_lang('MISSING_PARAM', '2', 'fix_perms'));
         }
         if (!array_key_exists(2, $parameters)) {
             return array('', '', '', do_lang('MISSING_PARAM', '3', 'fix_perms'));
         }
         $return = http_download_file(get_base_url() . '/upgrader.php?check_perms=1&user='******'&pass='******'&root=' . $parameters[2], NULL, false);
         if (is_null($return)) {
             return array('', '', '', do_lang('HTTP_DOWNLOAD_NO_SERVER', get_base_url() . '/upgrader.php?check_perms=1'));
         } else {
             return array('', occle_make_normal_html_visible(extract_html_body($return)), '', '');
         }
     }
 }
コード例 #16
0
/**
 * Convert Comcode-Text to Comcode-XML.
 *
 * @param  LONG_TEXT		The comcode to convert
 * @param  boolean		Whether to not include a wrapper element (<comcode>)
 * @return LONG_TEXT		The converted comcode
 */
function comcode_text__to__comcode_xml($comcode, $skip_wrapper = false)
{
    require_code('comcode_xml');
    require_code('comcode_text');
    require_code('comcode_renderer');
    if (substr($comcode, 0, 8) == '<comcode') {
        if ($skip_wrapper) {
            return str_replace('<comcode>', '', str_replace('</comcode>', '', $comcode));
        }
        return $comcode;
    }
    $xml = '';
    global $ALLOWED_ENTITIES, $CODE_TAGS, $DANGEROUS_TAGS, $VALID_COMCODE_TAGS, $BLOCK_TAGS, $POTENTIAL_JS_NAUGHTY_ARRAY, $TEXTUAL_TAGS, $LEET_FILTER, $IMPORTED_CUSTOM_COMCODE, $REPLACE_TARGETS;
    $len = strlen($comcode);
    require_lang('comcode');
    require_code('type_validation');
    if (function_exists('set_time_limit') && ini_get('max_execution_time') != '0') {
        @set_time_limit(300);
    }
    $comcode_dangerous = true;
    $comcode_dangerous_html = true;
    // Tag level
    $current_tag = '';
    $attribute_map = array();
    $continuation = '';
    $close = mixed();
    // Properties that come from our tag
    $white_space_area = true;
    $textual_area = true;
    $formatting_allowed = true;
    $in_html = false;
    $in_semihtml = false;
    $in_separate_parse_section = false;
    // Not escaped because it has to be passed to a secondary filter
    $in_code_tag = false;
    $lax = false;
    // Our state
    $status = CCP_NO_MANS_LAND;
    $tag_stack = array();
    $pos = 0;
    $line_starting = true;
    $just_ended = false;
    $none_wrap_length = 0;
    $just_new_line = true;
    // So we can detect lists starting right away
    $just_title = false;
    global $NUM_LINES;
    $NUM_LINES = 0;
    $wrap_pos = 60;
    $preparse_mode = false;
    $is_all_semihtml = false;
    $smilies = $GLOBALS['FORUM_DRIVER']->find_emoticons();
    // We'll be needing the smiley array
    $shortcuts = array('(c)' => '&copy;', '(r)' => '&reg;', '--' => '&ndash;', '---' => '&mdash;');
    // Text syntax possibilities, that get maintained as our cursor moves through the text block
    $list_indent = 0;
    $list_type = 'ul';
    while ($pos < $len) {
        $next = $comcode[$pos];
        ++$pos;
        // State machine
        switch ($status) {
            case CCP_NO_MANS_LAND:
                if ($next == '[') {
                    // Look ahead to make sure it's a valid tag. If it's not then it's considered normal user input, not a tag at all
                    $dif = $pos < $len && $comcode[$pos] == '/' ? 1 : 0;
                    $ahead = substr($comcode, $pos + $dif, 19);
                    $equal_pos = strpos($ahead, '=');
                    $space_pos = strpos($ahead, ' ');
                    $end_pos = strpos($ahead, ']');
                    $cl_pos = strpos($ahead, chr(10));
                    if ($equal_pos === false) {
                        $equal_pos = 22;
                    }
                    if ($space_pos === false) {
                        $space_pos = 22;
                    }
                    if ($end_pos === false) {
                        $end_pos = 22;
                    }
                    if ($cl_pos === false) {
                        $cl_pos = 22;
                    }
                    $use_pos = min($equal_pos, $space_pos, $end_pos, $cl_pos);
                    $potential_tag = strtolower(substr($ahead, 0, $use_pos));
                    if ($use_pos != 22 && (!$in_html || $potential_tag == 'html' || $potential_tag == 'semihtml') && (!$in_code_tag || isset($CODE_TAGS[$potential_tag]))) {
                        if (!isset($VALID_COMCODE_TAGS[$potential_tag])) {
                            if (!$IMPORTED_CUSTOM_COMCODE) {
                                _custom_comcode_import($GLOBALS['SITE_DB']);
                            }
                        }
                        if (isset($VALID_COMCODE_TAGS[$potential_tag]) && substr($ahead, 0, 2) != 'i ') {
                            $close = false;
                            $current_tag = '';
                            $xml .= $continuation;
                            $continuation = '';
                            if ($potential_tag == 'html' || $potential_tag == 'semihtml') {
                                list($close_list, $list_indent) = _convert_close_open_lists($list_indent);
                                $xml .= $close_list;
                            }
                            $status = CCP_STARTING_TAG;
                            continue;
                        }
                    }
                }
                if ($in_html || $in_semihtml && ($next == '<' || $next == '>')) {
                    $ahead = substr($comcode, $pos - 1, 20);
                    $ahead_lower = strtolower($ahead);
                    if ($next == chr(10)) {
                        ++$NUM_LINES;
                    }
                    $continuation .= $next;
                } else {
                    // Text-format possibilities
                    if ($just_new_line && $formatting_allowed) {
                        $xml .= $continuation;
                        $continuation = '';
                        // List
                        $found_list = false;
                        $old_list_indent = $list_indent;
                        if ($pos + 1 < $len && is_numeric($next) && $comcode[$pos] == ')' && $comcode[$pos + 1] == ' ') {
                            if ($list_indent != 0 && $list_type == 'ul') {
                                list($temp_tpl, $old_list_indent) = _close_open_lists($list_indent, $list_type);
                                $xml .= $temp_tpl;
                            }
                            $list_indent = 1;
                            $found_list = true;
                            $scan_pos = $pos;
                            $list_type = '1';
                        } elseif ($pos + 1 < $len && ord($next) >= ord('a') && ord($next) <= ord('z') && $comcode[$pos] == ')' && $comcode[$pos + 1] == ' ') {
                            if ($list_indent != 0 && $list_type == 'ul') {
                                list($temp_tpl, $old_list_indent) = _close_open_lists($list_indent, $list_type);
                                $xml .= $temp_tpl;
                            }
                            $list_indent = 1;
                            $found_list = true;
                            $scan_pos = $pos;
                            $list_type = 'a';
                        } elseif ($next == ' ') {
                            if ($old_list_indent != 0 && $list_type != 'ul') {
                                list($temp_tpl, $old_list_indent) = _close_open_lists($list_indent, $list_type);
                                $xml .= $temp_tpl;
                            }
                            $scan_pos = $pos - 1;
                            $list_indent = 0;
                            while ($scan_pos < $len) {
                                $scan_next = $comcode[$scan_pos];
                                if ($scan_next == '-' && $comcode[$scan_pos + 1] == ' ') {
                                    $found_list = true;
                                    break;
                                } else {
                                    if ($scan_next == ' ') {
                                        ++$list_indent;
                                    } else {
                                        break;
                                    }
                                }
                                ++$scan_pos;
                            }
                            if (!$found_list) {
                                $list_indent = 0;
                            }
                        } else {
                            list($close_list, $list_indent) = _convert_close_open_lists($list_indent);
                            $xml .= $close_list;
                            if ($next == '-' && !$just_title) {
                                $scan_pos = $pos;
                                $found_rule = true;
                                while ($scan_pos < $len) {
                                    $scan_next = $comcode[$scan_pos];
                                    if ($scan_next != '-') {
                                        if ($scan_next == chr(10)) {
                                            ++$NUM_LINES;
                                            break;
                                        } else {
                                            $found_rule = false;
                                        }
                                    }
                                    ++$scan_pos;
                                }
                                if ($found_rule) {
                                    $xml .= '<rule />';
                                    $pos = $scan_pos + 1;
                                    $just_ended = true;
                                    $none_wrap_length = 0;
                                    continue;
                                }
                            }
                        }
                        // List handling
                        if ($list_indent == $old_list_indent && $old_list_indent != 0) {
                            $xml .= '</listElement>';
                        }
                        for ($i = $list_indent; $i < $old_list_indent; ++$i) {
                            $xml .= '</listElement>';
                            $xml .= '</list>';
                        }
                        if ($list_indent < $old_list_indent && $list_indent != 0) {
                            $xml .= '</listElement>';
                        }
                        if ($found_list) {
                            if ($list_indent - $old_list_indent > 1 && !$lax) {
                                $error = comcode_parse_error($preparse_mode, array('CCP_LIST_JUMPYNESS'), $pos, $comcode);
                                return $error->evaluate();
                            }
                            for ($i = $old_list_indent; $i < $list_indent; ++$i) {
                                switch ($list_type) {
                                    case 'ul':
                                        $xml .= '<list>';
                                        break;
                                    case '1':
                                        $xml .= '<list type="1">';
                                        break;
                                    case 'a':
                                        $xml .= '<list type="a">';
                                        break;
                                }
                                if ($i < $list_indent - 1) {
                                    $xml .= '<listElement>';
                                }
                            }
                            $xml .= '<listElement>';
                            $just_ended = true;
                            $none_wrap_length = 0;
                            $next = '';
                            $pos = $scan_pos + 2;
                        }
                    }
                    if ($next == chr(10) && $white_space_area && !$just_ended) {
                        ++$NUM_LINES;
                        $line_starting = true;
                        $xml .= $continuation;
                        $continuation = '';
                        $just_new_line = true;
                        $none_wrap_length = 0;
                        if ($list_indent == 0) {
                            $xml .= '<br />' . chr(10);
                        }
                    } else {
                        $just_new_line = false;
                        if ($next == ' ' && $white_space_area) {
                            if ($line_starting || $pos != 0 && $comcode[$pos - 2] == ' ') {
                                $next = '&nbsp;';
                                ++$none_wrap_length;
                            } else {
                                $none_wrap_length = 0;
                            }
                            $continuation .= $next;
                        } elseif ($next == "\t" && $white_space_area) {
                            $xml .= $continuation;
                            $continuation = '';
                            $tab_tpl = do_template('COMCODE_TEXTCODE_TAB');
                            // &nbsp;&nbsp;&nbsp;&nbsp;
                            $_tab_tpl = $tab_tpl->evaluate();
                            $none_wrap_length += strlen($_tab_tpl);
                            $xml .= $tab_tpl->evaluate();
                        } else {
                            if ($next == ' ' || $next == "\t" || $just_ended) {
                                $none_wrap_length = 0;
                            } else {
                                if (!is_null($wrap_pos) && $none_wrap_length >= $wrap_pos && $textual_area && !$in_semihtml) {
                                    $xml .= $continuation;
                                    $continuation = '';
                                    $xml .= '<br />' . chr(10);
                                    $none_wrap_length = 0;
                                } elseif ($textual_area) {
                                    ++$none_wrap_length;
                                }
                            }
                            $line_starting = false;
                            $just_ended = false;
                            $differented = false;
                            // If somehow via lookahead we've changed this to HTML and thus won't use it in raw form
                            // Symbol lookahead
                            if (!$in_code_tag) {
                                if ($next == '{' && ($comcode[$pos] == '$' || $comcode[$pos] == '+' || $comcode[$pos] == '!') && $comcode_dangerous) {
                                    $xml .= $continuation;
                                    $continuation = '';
                                    if ($comcode[$pos] == '+') {
                                        $p_end = $pos + 5;
                                        while ($p_end < $len) {
                                            $p_portion = substr($comcode, $pos - 1, $p_end - ($pos - 1) + 5);
                                            if (substr_count($p_portion, '{+START') == substr_count($p_portion, '{+END')) {
                                                break;
                                            }
                                            $p_end++;
                                        }
                                        $p_len = 1;
                                        while ($pos + $p_len < $len) {
                                            $p_portion = substr($comcode, $pos - 1, $p_len);
                                            if (substr_count($p_portion, '{') == substr_count($p_portion, '}')) {
                                                break;
                                            }
                                            $p_len++;
                                        }
                                        $p_len--;
                                        $p_portion = substr($comcode, $pos + $p_len, $p_end - ($pos + $p_len));
                                        $_ret = template_to_tempcode_static(substr($comcode, $pos - 1, $p_len + 1) . '!' . substr($comcode, $p_end, 6));
                                        $ret = '<directive type="' . escape_html($_ret->bits[0][2]) . '">';
                                        foreach ($_ret->bits[0][3] as $val) {
                                            $ret .= '<directiveParam>' . escape_html($val->evaluate()) . '</directiveParam>';
                                        }
                                        $ret .= comcode_text__to__comcode_xml($p_portion, true);
                                        $ret .= '</directive>';
                                        $pos = $p_end + 6;
                                    } else {
                                        $_ret = new ocp_tempcode();
                                        $_ret->bits = array(read_single_uncompiled_variable($comcode, $pos, $len));
                                        if ($_ret->bits[0][1] == TC_SYMBOL) {
                                            $ret = '<symbol>';
                                            if (isset($_ret->bits[0][3])) {
                                                foreach ($_ret->bits[0][3] as $val) {
                                                    $ret .= '<symbolParam>' . escape_html($val) . '</symbolParam>';
                                                }
                                            }
                                            $ret .= $_ret->bits[0][2] . '</symbol>';
                                        } else {
                                            $ret = '<language>';
                                            if (isset($_ret->bits[0][3])) {
                                                foreach ($_ret->bits[0][3] as $val) {
                                                    $ret .= '<languageParam>' . escape_html($val) . '</languageParam>';
                                                }
                                            }
                                            $ret .= $_ret->bits[0][2] . '</language>';
                                        }
                                    }
                                    $differented = true;
                                    $xml .= $ret;
                                }
                            }
                            // Escaping of comcode tag starts lookahead
                            if ($next == '\\' && !$in_code_tag) {
                                if ($pos != $len && $comcode[$pos] == '"') {
                                    $continuation .= '"';
                                    ++$pos;
                                    $differented = true;
                                } elseif ($pos != $len && $comcode[$pos] == '[') {
                                    $continuation .= '[';
                                    ++$pos;
                                    $differented = true;
                                } elseif ($pos != $len && $comcode[$pos] == '{') {
                                    $continuation .= '{';
                                    ++$pos;
                                    $differented = true;
                                } elseif ($pos == $len || $comcode[$pos] == '\\') {
                                    $continuation .= '\\';
                                    ++$pos;
                                    $differented = true;
                                }
                            }
                            // Smiley lookahead
                            if (!$differented) {
                                if (($textual_area || $in_semihtml) && trim($next) != '') {
                                    foreach ($smilies as $smiley => $imgcode) {
                                        if ($in_semihtml) {
                                            $smiley = ' ' . $smiley . ' ';
                                        }
                                        if ($next == $smiley[0]) {
                                            if (substr($comcode, $pos - 1, strlen($smiley)) == $smiley) {
                                                $xml .= $continuation;
                                                $continuation = '';
                                                $pos += strlen($smiley) - 1;
                                                $differented = true;
                                                $xml .= '<emoticon>' . escape_html($imgcode) . '</emoticon>';
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            if ($textual_area && trim($next) != '' && !$differented && addon_installed('cedi')) {
                                // CEDI pages
                                if ($pos < $len && $next == '[') {
                                    $matches = array();
                                    if (preg_match('#^\\[([^\\[\\]]*)\\]\\]#', substr($comcode, $pos, 40), $matches) != 0) {
                                        $cedi_page_name = $matches[1];
                                        $xml .= $continuation;
                                        $continuation = '';
                                        $hash_pos = strpos($cedi_page_name, '#');
                                        if ($hash_pos !== false) {
                                            $jump_to = substr($cedi_page_name, $hash_pos + 1);
                                            $cedi_page_name = substr($cedi_page_name, 0, $hash_pos);
                                            $xml .= '<cedi anchor="' . escape_html($jump_to) . '">' . escape_html($cedi_page_name) . '</cedi>';
                                        } else {
                                            $xml .= '<cedi>' . escape_html($cedi_page_name) . '</cedi>';
                                        }
                                        $pos += strlen($matches[1]) + 3;
                                        $differented = true;
                                    }
                                }
                                // Usernames
                                if ($pos < $len && $next == '{') {
                                    $matches = array();
                                    if (preg_match('#^\\{([^"{}&\'\\$<>]*)\\}\\}#', substr($comcode, $pos, 40), $matches) != 0) {
                                        $xml .= $continuation;
                                        $continuation = '';
                                        $username = $matches[1];
                                        if ($username[0] == '?') {
                                            $username = substr($username, 1);
                                            $xml .= '<member boxed="1">' . escape_html($username) . '</member>';
                                        } else {
                                            $xml .= '<member>' . escape_html($username) . '</member>';
                                        }
                                        $pos += strlen($matches[1]) + 3;
                                        $differented = true;
                                    }
                                }
                                if (!$in_code_tag && trim($next) != '' && !$differented) {
                                    // Shortcut lookahead
                                    if (!$differented) {
                                        foreach ($shortcuts as $code => $replacement) {
                                            if ($next == $code[0] && substr($comcode, $pos - 1, strlen($code)) == $code) {
                                                $xml .= $continuation;
                                                $continuation = '';
                                                $pos += strlen($code) - 1;
                                                $differented = true;
                                                $xml .= $replacement;
                                                break;
                                            }
                                        }
                                    }
                                }
                                // Table syntax
                                if (!$differented) {
                                    if ($pos < $len && $comcode[$pos] == '|') {
                                        $end_tbl = strpos($comcode, chr(10) . '|}', $pos);
                                        if ($end_tbl !== false) {
                                            $end_fst_line_pos = strpos($comcode, chr(10), $pos);
                                            $caption = substr($comcode, $pos + 2, max($end_fst_line_pos - $pos - 2, 0));
                                            $pos += strlen($caption) + 1;
                                            $rows = preg_split('#(\\|-|\\|\\})#Um', substr($comcode, $pos, $end_tbl - $pos));
                                            if (count($rows) == 1 && $caption == 'floats') {
                                                $cells = preg_split('/(\\n\\! | \\!\\! |\\n\\| | \\|\\| )/', $rows[0], -1, PREG_SPLIT_DELIM_CAPTURE);
                                                array_shift($cells);
                                                // First one is non-existant empty
                                                $spec = true;
                                                // Find which to float
                                                $to_float = NULL;
                                                foreach ($cells as $i => $cell) {
                                                    if (!$spec) {
                                                        if (strpos($cell, '!') !== false || is_null($to_float)) {
                                                            $to_float = $i;
                                                        }
                                                    }
                                                    $spec = !$spec;
                                                }
                                                $xml .= '<float>';
                                                // Do floated one
                                                $xml .= '<fh>';
                                                $xml .= comcode_text__to__comcode_xml(rtrim($cells[$to_float]), true);
                                                $xml .= '</fh>';
                                                // Do non-floated ones
                                                foreach ($cells as $i => $cell) {
                                                    if ($i % 2 == 1 && $i != $to_float) {
                                                        $xml .= '<fd>';
                                                        $xml .= comcode_text__to__comcode_xml(rtrim($cells[$to_float]), true);
                                                        $xml .= '</fd>';
                                                    }
                                                }
                                                $xml .= '</float>';
                                            } else {
                                                $xml .= '<table summary="' . escape_html($caption) . '">';
                                                foreach ($rows as $table_row) {
                                                    $xml .= '<tr>';
                                                    $cells = preg_split('/(\\n\\! | \\!\\! |\\n\\| | \\|\\| )/', $table_row, -1, PREG_SPLIT_DELIM_CAPTURE);
                                                    array_shift($cells);
                                                    // First one is non-existant empty
                                                    $spec = true;
                                                    $c_type = '';
                                                    foreach ($cells as $cell) {
                                                        if ($spec) {
                                                            $c_type = strpos($cell, '!') !== false ? 'th' : 'td';
                                                        } else {
                                                            $xml .= '<' . $c_type . '>';
                                                            $xml .= comcode_text__to__comcode_xml(rtrim($cell), true);
                                                            $xml .= '</' . $c_type . '>';
                                                        }
                                                        $spec = !$spec;
                                                    }
                                                    $xml .= '</tr>';
                                                }
                                                $xml .= '</table>';
                                            }
                                            $pos = $end_tbl + 3;
                                            $differented = true;
                                        }
                                    }
                                }
                                // Link lookahead
                                if (!$differented) {
                                    if (!$in_semihtml && $next == 'h' && (substr($comcode, $pos - 1, strlen('http://')) == 'http://' || substr($comcode, $pos - 1, strlen('https://')) == 'https://' || substr($comcode, $pos - 1, strlen('ftp://')) == 'ftp://')) {
                                        list($link_end_pos, $auto_link) = detect_link($comcode, $pos);
                                        $xml .= $continuation;
                                        $continuation = '';
                                        $downloaded_at_link = http_download_file($auto_link, 3000, false);
                                        $link_captions_title = '';
                                        if (is_string($downloaded_at_link)) {
                                            $matches = array();
                                            if (preg_match('#<title>\\s*(.*)\\s*</title>#', $downloaded_at_link, $matches) != 0) {
                                                require_code('character_sets');
                                                $link_captions_title = @html_entity_decode(convert_to_internal_encoding($matches[1]), ENT_QUOTES, get_charset());
                                            }
                                        }
                                        $xml .= '<url param="' . escape_html($auto_link) . '">' . escape_html($link_captions_title) . '</url>';
                                        $pos += $link_end_pos - $pos;
                                        $differented = true;
                                        break;
                                    }
                                }
                            }
                            if (!$differented) {
                                if (!$in_separate_parse_section && (!$in_semihtml || !$comcode_dangerous && !$is_all_semihtml)) {
                                    if ($next == '&') {
                                        $ahead = substr($comcode, $pos, 20);
                                        $ahead_lower = strtolower($ahead);
                                        $matches = array();
                                        $entity = preg_match('#(\\#)?([\\w]*);#', $ahead_lower, $matches) != 0;
                                        // If it is a SAFE entity, use it
                                        if ($entity) {
                                            if ($matches[1] == '' && isset($ALLOWED_ENTITIES[$matches[2]])) {
                                                $pos += strlen($matches[2]) + 1;
                                                $continuation .= '&' . $matches[2] . ';';
                                            } elseif (is_numeric($matches[2]) && $matches[1] == '#') {
                                                $matched_entity = intval(base_convert($matches[1], 16, 10));
                                                if ($matched_entity < 127 && array_key_exists(chr($matched_entity), $POTENTIAL_JS_NAUGHTY_ARRAY)) {
                                                    $continuation .= escape_html($next);
                                                } else {
                                                    $pos += strlen($matches[2]) + 2;
                                                    $continuation .= '&#' . $matches[2] . ';';
                                                }
                                            } else {
                                                $continuation .= '&amp;';
                                            }
                                        } else {
                                            $continuation .= '&amp;';
                                        }
                                    } else {
                                        $continuation .= escape_html($next);
                                    }
                                } else {
                                    $continuation .= $next;
                                }
                            }
                        }
                    }
                }
                break;
            case CCP_IN_TAG_NAME:
                if ($next == '=') {
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTE_NAME_VALUE_RIGHT;
                    $current_attribute_name = 'param';
                } elseif (trim($next) == '') {
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTES;
                } elseif ($next == '[') {
                    warn_exit(do_lang_tempcode('CCP_TAG_OPEN_ANOMALY'));
                } elseif ($next == ']') {
                    if ($close) {
                        if ($formatting_allowed) {
                            list($close_list, $list_indent) = _convert_close_open_lists($list_indent);
                            $xml .= $close_list;
                        }
                        if (count($tag_stack) == 0) {
                            warn_exit(do_lang_tempcode('CCP_NO_CLOSE', escape_html($current_tag)));
                        }
                        $_last = array_pop($tag_stack);
                        if ($_last[0] != $current_tag) {
                            warn_exit(do_lang_tempcode('CCP_NO_CLOSE_MATCH', escape_html($current_tag), escape_html($_last)));
                        }
                        // Do the comcode for this tag
                        if ($in_semihtml) {
                            foreach ($_last[1] as $index => $conv) {
                                $_last[1][$index] = @html_entity_decode(str_replace('<br />', chr(10), $conv), ENT_QUOTES, get_charset());
                            }
                        }
                        $attributes = $_last[1];
                        if ($current_tag == 'html') {
                            $in_html = false;
                            $_last[0] = 'htmlWrap';
                        } elseif ($current_tag == 'semihtml') {
                            $in_semihtml = false;
                            $_last[0] = 'htmlWrap';
                        } elseif ($current_tag == 'external_table' || $current_tag == 'internal_table') {
                            $_last[0] = 'box';
                        } elseif ($current_tag == 'php') {
                            $_last[0] = 'code';
                            $attributes['param'] = 'php';
                        } elseif ($current_tag == 'codebox') {
                            $_last[0] = 'code';
                            $attributes['scroll'] = '1';
                        } elseif ($current_tag == 'sql') {
                            $_last[0] = 'code';
                            $attributes['param'] = 'sql';
                        } elseif ($current_tag == 'snapback') {
                            $_last[0] = 'post';
                        } elseif ($current_tag == 'thread') {
                            $_last[0] = 'topic';
                        } elseif ($current_tag == 'list') {
                            $sub_elements = explode('[*]', str_replace('[/*]', '', $xml));
                            $xml = '';
                            foreach ($sub_elements as $sub_element) {
                                $xml .= '<listElement>' . $sub_element . '</listElement>';
                            }
                        }
                        if ($_last[0] == 'box' && isset($attributes['breadth']) && !isset($attributes['dimensions'])) {
                            $attributes['dimensions'] = $attributes['breadth'];
                            unset($attributes['breadth']);
                        }
                        if ($_last[0] == 'page' && array_keys($attributes) != array('param')) {
                            $zone = isset($attributes['param']) ? $attributes['param'] : '_SEARCH';
                            $page = $xml;
                            $xml = $attributes['caption'];
                            unset($attributes['param']);
                            unset($attributes['caption']);
                            $pagelink = $zone . ':' . $page;
                            foreach ($attributes as $key => $val) {
                                $pagelink .= ':' . $key . '=' . $val;
                            }
                            $attributes = array('pageLink' => $pagelink);
                        }
                        if ($_last[0] == 'block') {
                            foreach ($attributes as $key => $val) {
                                $xml .= '<blockParam key="' . escape_html($key) . '" value="' . escape_html($val) . '" />';
                            }
                            $attributes = array();
                        }
                        if ($_last[0] == 'random') {
                            foreach ($attributes as $key => $val) {
                                $xml .= '<randomTarget pickIfAbove="' . escape_html($key) . '">' . comcode_text__to__comcode_xml($val, true) . '</randomTarget>';
                            }
                            $attributes = array();
                        }
                        if ($_last[0] == 'jumping') {
                            foreach ($attributes as $key => $val) {
                                $xml .= '<jumpingTarget>' . comcode_text__to__comcode_xml($val, true) . '</jumpingTarget>';
                            }
                            $attributes = array();
                        }
                        if ($_last[0] == 'concepts') {
                            foreach ($attributes as $_key => $_value) {
                                if (substr($_key, -4) == '_key') {
                                    $key = $_value;
                                    $cid = substr($_key, 0, strlen($_key) - 4);
                                    $value = $attributes[$cid . '_value'];
                                    $xml .= '<showConcept key="' . escape_html($key) . '" value="' . escape_html($value) . '" />';
                                }
                            }
                            $attributes = array();
                        }
                        if (($_last[0] == 'attachment' || $_last[0] == 'attachment_safe') && isset($attributes['description'])) {
                            $xml .= '<attachmentDescription>' . comcode_text__to__comcode_xml($attributes['description'], true) . '</attachmentDescription>';
                            unset($attributes['description']);
                        }
                        if ($_last[0] == 'hide' && isset($attributes['param'])) {
                            $xml .= '<hideTitle>' . comcode_text__to__comcode_xml($attributes['param'], true) . '</hideTitle>';
                            unset($attributes['param']);
                        }
                        if ($_last[0] == 'tooltip' && isset($attributes['param'])) {
                            $xml .= '<tooltipMessage>' . comcode_text__to__comcode_xml($attributes['param'], true) . '</tooltipMessage>';
                            unset($attributes['param']);
                        }
                        global $COMCODE_XML_PARAM_RENAMING, $COMCODE_XML_SWITCH_AROUND;
                        if (isset($attributes['param']) && isset($COMCODE_XML_PARAM_RENAMING[$_last[0]])) {
                            $attributes[$COMCODE_XML_PARAM_RENAMING[$_last[0]]] = $attributes['param'];
                            unset($attributes['param']);
                        }
                        $comcode_xml_switch_around = $COMCODE_XML_SWITCH_AROUND;
                        if ($_last[0] == 'email' && (!isset($attributes['param']) || !is_valid_email_address($attributes['param'])) && is_valid_email_address($xml)) {
                            $comcode_xml_switch_around[] = 'email';
                        }
                        if ($_last[0] == 'url' && (!isset($attributes['param']) || !looks_like_url($attributes['param'])) && looks_like_url($xml)) {
                            $comcode_xml_switch_around[] = 'url';
                        }
                        if (in_array($_last[0], $comcode_xml_switch_around)) {
                            $x = 'param';
                            if ($_last[0] == 'reference') {
                                $x = 'title';
                            }
                            if (isset($attributes[$x])) {
                                $temp = $attributes[$x];
                                $attributes[$x] = $xml;
                                $xml = comcode_text__to__comcode_xml($temp, true);
                            } else {
                                $attributes[$x] = $xml;
                            }
                        }
                        $in_code_tag = false;
                        $white_space_area = $_last[3];
                        $in_separate_parse_section = $_last[4];
                        $formatting_allowed = $_last[5];
                        $textual_area = $_last[6];
                        if ($_last[0] == 'htmlWrap') {
                            $embed_output = '<htmlWrap xmlns="http://www.w3.org/1999/xhtml">';
                        } else {
                            $embed_output = '<' . to_camelCase($_last[0]);
                            foreach ($attributes as $key => $val) {
                                $embed_output .= ' ' . to_camelCase($key) . '="' . escape_html($val) . '"';
                            }
                            $embed_output .= '>';
                        }
                        $embed_output .= $xml . '</' . to_camelCase($_last[0]) . '>';
                        $just_ended = isset($BLOCK_TAGS[$current_tag]);
                        $xml = $_last[2] . $embed_output;
                        if ($current_tag == 'title') {
                            if (strlen($comcode) > $pos + 1 && $comcode[$pos] == chr(10) && $comcode[$pos + 1] == chr(10)) {
                                $NUM_LINES += 2;
                                $pos += 2;
                                $just_new_line = true;
                                list($close_list, $list_indent) = _convert_close_open_lists($list_indent);
                                $xml .= $close_list;
                            }
                        }
                        $status = CCP_NO_MANS_LAND;
                    } else {
                        array_push($tag_stack, array($current_tag, $attribute_map, $xml, $white_space_area, $in_separate_parse_section, $formatting_allowed, $textual_area));
                        list(, , , $white_space_area, $formatting_allowed, $in_separate_parse_section, $textual_area, $attribute_map, $status, $in_html, $in_semihtml, $pos, $in_code_tag) = _opened_tag(false, false, get_member(), $attribute_map, $current_tag, $pos, $comcode_dangerous, $comcode_dangerous_html, $in_separate_parse_section, $in_html, $in_semihtml, $close, $len, $comcode);
                        $xml = '';
                    }
                } else {
                    $current_tag .= strtolower($next);
                }
                break;
            case CCP_STARTING_TAG:
                if ($next == '[') {
                    warn_exit(do_lang_tempcode('CCP_TAG_OPEN_ANOMALY'));
                } elseif ($next == ']') {
                    warn_exit(do_lang_tempcode('CCP_TAG_CLOSE_ANOMALY'));
                } elseif ($next == '/') {
                    $close = true;
                } else {
                    $current_tag .= strtolower($next);
                    $status = CCP_IN_TAG_NAME;
                }
                break;
            case CCP_IN_TAG_BETWEEN_ATTRIBUTES:
                if ($next == ']') {
                    array_push($tag_stack, array($current_tag, $attribute_map, $xml, $white_space_area, $in_separate_parse_section, $formatting_allowed, $textual_area));
                    list(, , , $white_space_area, $formatting_allowed, $in_separate_parse_section, $textual_area, $attribute_map, $status, $in_html, $in_semihtml, $pos, $in_code_tag) = _opened_tag(false, false, get_member(), $attribute_map, $current_tag, $pos, $comcode_dangerous, $comcode_dangerous_html, $in_separate_parse_section, $in_html, $in_semihtml, $close, $len, $comcode);
                    $xml = '';
                } elseif ($next == '[') {
                    warn_exit(do_lang_tempcode('CCP_TAG_OPEN_ANOMALY'));
                } elseif (trim($next) != '') {
                    $status = CCP_IN_TAG_ATTRIBUTE_NAME;
                    $current_attribute_name = $next;
                }
                break;
            case CCP_IN_TAG_ATTRIBUTE_NAME:
                if ($next == '[') {
                    warn_exit(do_lang_tempcode('CCP_TAG_OPEN_ANOMALY'));
                } elseif ($next == ']') {
                    $at_map_keys = array_keys($attribute_map);
                    $old_attribute_name = $at_map_keys[count($at_map_keys) - 1];
                    $attribute_map[$old_attribute_name] .= ' ' . $current_attribute_name;
                    array_push($tag_stack, array($current_tag, $attribute_map, $xml, $white_space_area, $in_separate_parse_section, $formatting_allowed, $textual_area));
                    list(, , , $white_space_area, $formatting_allowed, $in_separate_parse_section, $textual_area, $attribute_map, $status, $in_html, $in_semihtml, $pos, $in_code_tag) = _opened_tag(false, false, get_member(), $attribute_map, $current_tag, $pos, $comcode_dangerous, $comcode_dangerous_html, $in_separate_parse_section, $in_html, $in_semihtml, $close, $len, $comcode);
                    $xml = '';
                } elseif ($next == '=') {
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTE_NAME_VALUE_RIGHT;
                } elseif ($next != ' ') {
                    $current_attribute_name .= strtolower($next);
                } else {
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTE_NAME_VALUE_LEFT;
                }
                break;
            case CCP_IN_TAG_BETWEEN_ATTRIBUTE_NAME_VALUE_LEFT:
                if ($next == '=') {
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTE_NAME_VALUE_RIGHT;
                } elseif (trim($next) != '') {
                    warn_exit(do_lang_tempcode('CCP_ATTRIBUTE_ERROR', escape_html($current_attribute_name), escape_html($current_tag)));
                }
                break;
            case CCP_IN_TAG_BETWEEN_ATTRIBUTE_NAME_VALUE_RIGHT:
                if ($next == '[') {
                    warn_exit(do_lang_tempcode('CCP_TAG_OPEN_ANOMALY'));
                } elseif ($next == ']') {
                    warn_exit(do_lang_tempcode('CCP_TAG_CLOSE_ANOMALY'));
                } elseif ($next == '"' || $in_semihtml && substr($comcode, $pos - 1, 6) == '&quot;') {
                    if ($next != '"') {
                        $pos += 5;
                    }
                    $status = CCP_IN_TAG_ATTRIBUTE_VALUE;
                    $current_attribute_value = '';
                } elseif ($next != '') {
                    $status = CCP_IN_TAG_ATTRIBUTE_VALUE_NO_QUOTE;
                    $current_attribute_value = $next;
                }
                break;
            case CCP_IN_TAG_ATTRIBUTE_VALUE_NO_QUOTE:
                if ($next == ' ') {
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTES;
                    if (isset($attribute_map[$current_attribute_name])) {
                        warn_exit(do_lang_tempcode('CCP_DUPLICATE_ATTRIBUTES', escape_html($current_attribute_name), escape_html($current_tag)));
                    }
                    $attribute_map[$current_attribute_name] = $current_attribute_value;
                } elseif ($next == ']') {
                    if (isset($attribute_map[$current_attribute_name])) {
                        warn_exit(do_lang_tempcode('CCP_DUPLICATE_ATTRIBUTES', escape_html($current_attribute_name), escape_html($current_tag)));
                    }
                    $attribute_map[$current_attribute_name] = $current_attribute_value;
                    array_push($tag_stack, array($current_tag, $attribute_map, $xml, $white_space_area, $in_separate_parse_section, $formatting_allowed, $textual_area));
                    list(, , , $white_space_area, $formatting_allowed, $in_separate_parse_section, $textual_area, $attribute_map, $status, $in_html, $in_semihtml, $pos, $in_code_tag) = _opened_tag(false, false, get_member(), $attribute_map, $current_tag, $pos, $comcode_dangerous, $comcode_dangerous_html, $in_separate_parse_section, $in_html, $in_semihtml, $close, $len, $comcode);
                    $xml = '';
                } else {
                    $current_attribute_value .= $next;
                }
                break;
            case CCP_IN_TAG_ATTRIBUTE_VALUE:
                if ($next == '"' || $in_semihtml && substr($comcode, $pos - 1, 6) == '&quot;') {
                    if ($next != '"') {
                        $pos += 5;
                    }
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTES;
                    if (isset($attribute_map[$current_attribute_name])) {
                        warn_exit(do_lang_tempcode('CCP_DUPLICATE_ATTRIBUTES', escape_html($current_attribute_name), escape_html($current_tag)));
                    }
                    $attribute_map[$current_attribute_name] = $current_attribute_value;
                } else {
                    if ($next == '\\') {
                        if ($comcode[$pos] == '"') {
                            $current_attribute_value .= '"';
                            ++$pos;
                        } elseif ($comcode[$pos] == '\\') {
                            $current_attribute_value .= '\\';
                            ++$pos;
                        } else {
                            $current_attribute_value .= $next;
                        }
                    } else {
                        $current_attribute_value .= $next;
                    }
                }
                break;
        }
    }
    $xml .= $continuation;
    $continuation = '';
    list($close_list, $list_indent) = _convert_close_open_lists($list_indent);
    $xml .= $close_list;
    if ($status != CCP_NO_MANS_LAND || count($tag_stack) != 0) {
        $stack_top = array_pop($tag_stack);
        warn_exit(do_lang_tempcode('CCP_BROKEN_END', escape_html($stack_top[0])));
    }
    if (!$skip_wrapper) {
        $xml = '<comcode>' . $xml . '</comcode>';
    }
    return $xml;
}
コード例 #17
0
ファイル: images.php プロジェクト: erico-deh/ocPortal
/**
 * Find whether the image specified is actually an image, based on file extension
 *
 * @param  string			A URL or file path to the image
 * @param  boolean		Whether to check mime too
 * @return boolean		Whether the string pointed to a file appeared to be an image
 */
function is_image($name, $mime_too = false)
{
    if (substr(basename($name), 0, 1) == '.') {
        return false;
    }
    // Temporary file that some OS's make
    $ext = get_file_extension($name);
    $types = explode(',', get_option('valid_images'));
    foreach ($types as $val) {
        if (strtolower($val) == $ext) {
            return true;
        }
    }
    if ($mime_too && looks_like_url($name)) {
        http_download_file($name, 0, false);
        global $HTTP_DOWNLOAD_MIME_TYPE;
        if (preg_match('#^image/(png|gif|jpeg)$#', $HTTP_DOWNLOAD_MIME_TYPE) != 0) {
            return true;
        }
    }
    return false;
}
コード例 #18
0
ファイル: galleries3.php プロジェクト: erico-deh/ocPortal
/**
 * Script handler for downloading a gallery, as specified by GET parameters.
 */
function download_gallery_script()
{
    if (function_exists('set_time_limit')) {
        @set_time_limit(0);
    }
    require_code('galleries');
    // Closed site
    $site_closed = get_option('site_closed');
    if ($site_closed == '1' && !has_specific_permission(get_member(), 'access_closed_site') && !$GLOBALS['IS_ACTUALLY_ADMIN']) {
        header('Content-Type: text/plain');
        @exit(get_option('closed'));
    }
    require_lang('galleries');
    require_code('zip');
    $cat = get_param('cat');
    if (!has_category_access(get_member(), 'galleries', $cat)) {
        access_denied('CATEGORY_ACCESS');
    }
    check_specific_permission('may_download_gallery', array('galleries', $cat));
    if (strpos($cat, chr(10)) !== false || strpos($cat, chr(13)) !== false) {
        log_hack_attack_and_exit('HEADER_SPLIT_HACK');
    }
    $gallery_rows = $GLOBALS['SITE_DB']->query_select('galleries', array('*'), array('name' => $cat), '', 1);
    if (!array_key_exists(0, $gallery_rows)) {
        warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
    }
    $gallery_row = $gallery_rows[0];
    // Send header
    header('Content-Type: application/octet-stream' . '; authoritative=true;');
    if (strstr(ocp_srv('HTTP_USER_AGENT'), 'MSIE') !== false) {
        header('Content-Disposition: filename="gallery-' . $cat . '.zip"');
    } else {
        header('Content-Disposition: attachment; filename="gallery-' . $cat . '.zip"');
    }
    disable_php_memory_limit();
    $rows = array_merge($GLOBALS['SITE_DB']->query_select('videos', array('url', 'add_date'), array('cat' => $cat, 'validated' => 1)), $GLOBALS['SITE_DB']->query_select('images', array('url', 'add_date'), array('cat' => $cat, 'validated' => 1)));
    $array = array();
    foreach ($rows as $row) {
        $full_path = NULL;
        $data = NULL;
        if (url_is_local($row['url']) && file_exists(get_file_base() . '/' . urldecode($row['url']))) {
            $path = urldecode($row['url']);
            $full_path = get_file_base() . '/' . $path;
            if (file_exists($full_path)) {
                $time = filemtime($full_path);
                $name = $path;
            } else {
                continue;
            }
        } else {
            continue;
            // Actually we won't include them, if they are not local it implies it is not reasonable for them to lead to server load, and they may not even be native files
            $time = $row['add_date'];
            $name = basename(urldecode($row['url']));
            $data = http_download_file($row['url']);
        }
        $array[] = array('name' => preg_replace('#^uploads/galleries/#', '', $name), 'time' => $time, 'data' => $data, 'full_path' => $full_path);
    }
    if ($gallery_row['rep_image'] != '') {
        if (url_is_local($gallery_row['rep_image']) && file_exists(get_file_base() . '/' . urldecode($gallery_row['rep_image']))) {
            $path = urldecode($gallery_row['rep_image']);
            $full_path = get_file_base() . '/' . $path;
            if (file_exists($full_path)) {
                $time = filemtime($full_path);
                $name = $path;
                $data = file_get_contents($full_path);
            }
        } else {
            $time = $gallery_row['add_date'];
            $name = basename(urldecode($gallery_row['rep_image']));
            $data = http_download_file($gallery_row['rep_image']);
        }
        $array[] = array('name' => preg_replace('#^uploads/(galleries|grepimages)/#', '', $name), 'time' => $time, 'data' => $data);
    }
    @ini_set('zlib.output_compression', 'Off');
    //$zip_file=create_zip_file($array);
    //header('Content-Length: '.strval(strlen($zip_file)));
    //echo $zip_file;
    create_zip_file($array, true);
}
コード例 #19
0
ファイル: mail.php プロジェクト: erico-deh/ocPortal
/**
 * Attempt to send an e-mail to the specified recipient. The mail will be forwarding to the CC address specified in the options (if there is one, and if not specified not to cc).
 * The mail will be sent in dual HTML/text format, where the text is the unconverted comcode source: if a member does not read HTML mail, they may wish to fallback to reading that.
 *
 * @param  string			The subject of the mail in plain text
 * @param  LONG_TEXT		The message, as Comcode
 * @param  ?array			The destination (recipient) e-mail addresses [array of strings] (NULL: site staff address)
 * @param  ?mixed			The recipient name. Array or string. (NULL: site name)
 * @param  EMAIL			The from address (blank: site staff address)
 * @param  string			The from name (blank: site name)
 * @param  integer		The message priority (1=urgent, 3=normal, 5=low)
 * @range  1 5
 * @param  ?array			An list of attachments (each attachment being a map, path=>filename) (NULL: none)
 * @param  boolean		Whether to NOT CC to the CC address
 * @param  ?MEMBER		Convert comcode->tempcode as this member (a privilege thing: we don't want people being able to use admin rights by default!) (NULL: guest)
 * @param  boolean		Replace above with arbitrary admin
 * @param  boolean		HTML-only
 * @param  boolean		Whether to bypass queueing, because this code is running as a part of the queue management tools
 * @param  ID_TEXT		The template used to show the email
 * @param  boolean		Whether to bypass queueing
 * @return ?tempcode		A full page (not complete XHTML) piece of tempcode to output (NULL: it worked so no tempcode message)
 */
function mail_wrap($subject_tag, $message_raw, $to_email = NULL, $to_name = NULL, $from_email = '', $from_name = '', $priority = 3, $attachments = NULL, $no_cc = false, $as = NULL, $as_admin = false, $in_html = false, $coming_out_of_queue = false, $mail_template = 'MAIL', $bypass_queue = false)
{
    if (running_script('stress_test_loader')) {
        return NULL;
    }
    global $EMAIL_ATTACHMENTS;
    $EMAIL_ATTACHMENTS = array();
    require_code('site');
    require_code('mime_types');
    $bypass_queue = $bypass_queue || $priority < 3 || strpos(serialize($attachments), 'tmpfile') !== false;
    if (is_null($as)) {
        $as = $GLOBALS['FORUM_DRIVER']->get_guest_id();
    }
    if (!$coming_out_of_queue) {
        $GLOBALS['SITE_DB']->query('DELETE FROM ' . get_table_prefix() . 'logged_mail_messages WHERE m_date_and_time<' . strval(time() - 60 * 60 * 24 * 14) . ' AND m_queued=0');
        // Log it all for 2 weeks, then delete
        $through_queue = !$bypass_queue && (get_option('mail_queue_debug') === '1' || get_option('mail_queue') === '1' && cron_installed());
        $GLOBALS['SITE_DB']->query_insert('logged_mail_messages', array('m_subject' => substr($subject_tag, 0, 255), 'm_message' => $message_raw, 'm_to_email' => serialize($to_email), 'm_to_name' => serialize($to_name), 'm_from_email' => $from_email, 'm_from_name' => $from_name, 'm_priority' => $priority, 'm_attachments' => serialize($attachments), 'm_no_cc' => $no_cc ? 1 : 0, 'm_as' => $as, 'm_as_admin' => $as_admin ? 1 : 0, 'm_in_html' => $in_html ? 1 : 0, 'm_date_and_time' => time(), 'm_member_id' => get_member(), 'm_url' => get_self_url(true), 'm_queued' => $through_queue ? 1 : 0, 'm_template' => $mail_template), false, !$through_queue);
        // No errors if we don't NEED this to work
        if ($through_queue) {
            return NULL;
        }
    }
    if (count($attachments) == 0) {
        $attachments = NULL;
    }
    global $SENDING_MAIL;
    if ($SENDING_MAIL) {
        return NULL;
    }
    $SENDING_MAIL = true;
    // To and from, and language
    $staff_address = get_option('staff_address');
    if (is_null($to_email)) {
        $to_email = array($staff_address);
    }
    $to_email_new = array();
    foreach ($to_email as $test_address) {
        if ($test_address != '') {
            $to_email_new[] = $test_address;
        }
    }
    $to_email = $to_email_new;
    if ($to_email == array()) {
        $SENDING_MAIL = false;
        return NULL;
    }
    if ($to_email[0] == $staff_address) {
        $lang = get_site_default_lang();
    } else {
        $lang = user_lang();
        if (method_exists($GLOBALS['FORUM_DRIVER'], 'get_member_from_email_address')) {
            $member_id = $GLOBALS['FORUM_DRIVER']->get_member_from_email_address($to_email[0]);
            if (!is_null($member_id)) {
                $lang = get_lang($member_id);
            }
        }
    }
    if (is_null($to_name)) {
        if ($to_email[0] == $staff_address) {
            $to_name = get_site_name();
        } else {
            $to_name = '';
        }
    }
    if ($from_email == '') {
        $from_email = get_option('staff_address');
    }
    if ($from_name == '') {
        $from_name = get_site_name();
    }
    $from_email = str_replace("\r", '', $from_email);
    $from_email = str_replace("\n", '', $from_email);
    $from_name = str_replace("\r", '', $from_name);
    $from_name = str_replace("\n", '', $from_name);
    $theme = method_exists($GLOBALS['FORUM_DRIVER'], 'get_theme') ? $GLOBALS['FORUM_DRIVER']->get_theme() : 'default';
    if ($theme == 'default') {
        $theme = $GLOBALS['FORUM_DRIVER']->get_theme('');
        // ... So get theme of welcome zone
    }
    // Line termination is fiddly. It is safer to rely on sendmail supporting \n than undetectable-qmail/postfix-masquerading-as-sendmail not supporting the correct \r\n
    /*$sendmail_path=ini_get('sendmail_path');
    	if ((strpos($sendmail_path,'qmail')!==false) || (strpos($sendmail_path,'sendmail')!==false))
    		$line_term="\n";
    	else
    		$line_term="\r\n";
    	*/
    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || get_option('smtp_sockets_use') == '1') {
        $line_term = "\r\n";
        /*} elseif (strtoupper(substr(PHP_OS,0,3))=='MAC')
        	{
        		$line_term="\r";*/
    } else {
        $line_term = "\n";
    }
    // We use the boundary to seperate message parts
    $_boundary = uniqid('ocPortal', true);
    $boundary = $_boundary . '_1';
    $boundary2 = $_boundary . '_2';
    $boundary3 = $_boundary . '_3';
    // Our subject
    $subject = do_template('MAIL_SUBJECT', array('_GUID' => '44a57c666bb00f96723256e26aade9e5', 'SUBJECT_TAG' => $subject_tag), $lang, false, NULL, '.tpl', 'templates', $theme);
    $tightened_subject = $subject->evaluate($lang);
    // Note that this is slightly against spec, because characters aren't forced to be printable us-ascii. But it's better we allow this (which works in practice) than risk incompatibility via charset-base64 encoding.
    $tightened_subject = str_replace(chr(10), '', $tightened_subject);
    $tightened_subject = str_replace(chr(13), '', $tightened_subject);
    $regexp = '#^[\\x' . dechex(32) . '-\\x' . dechex(126) . ']*$#';
    if (preg_match($regexp, $tightened_subject) == 0) {
        $tightened_subject = '=?' . do_lang('charset', NULL, NULL, NULL, $lang) . '?B?' . base64_encode($tightened_subject) . "?=";
    }
    if (preg_match($regexp, $from_name) == 0) {
        $from_name = '=?' . do_lang('charset', NULL, NULL, NULL, $lang) . '?B?' . base64_encode($from_name) . "?=";
    }
    if (is_array($to_name)) {
        foreach ($to_name as $i => $_to_name) {
            if (preg_match($regexp, $_to_name) == 0) {
                $to_name[$i] = '=?' . do_lang('charset', NULL, NULL, NULL, $lang) . '?B?' . base64_encode($_to_name) . "?=";
            }
        }
    } else {
        if (preg_match($regexp, $to_name) == 0) {
            $to_name = '=?' . do_lang('charset', NULL, NULL, NULL, $lang) . '?B?' . base64_encode($to_name) . "?=";
        }
    }
    $simplify_when_can = true;
    // Used for testing. Not actually needed
    // Evaluate message. Needs doing early so we know if we have any headers
    $GLOBALS['NO_LINK_TITLES'] = true;
    global $LAX_COMCODE;
    $temp = $LAX_COMCODE;
    $LAX_COMCODE = true;
    $html_content = comcode_to_tempcode($message_raw, $as, $as_admin);
    $LAX_COMCODE = $temp;
    $GLOBALS['NO_LINK_TITLES'] = false;
    $attachments = array_merge(is_null($attachments) ? array() : $attachments, $EMAIL_ATTACHMENTS);
    // Headers
    $website_email = get_option('website_email');
    if ($website_email == '') {
        $website_email = $from_email;
    }
    if (get_value('use_true_from') !== '1') {
        $headers = 'From: "' . $from_name . '" <' . $website_email . '>' . $line_term;
    } else {
        $headers = 'From: <' . $from_email . '>' . $line_term;
    }
    $headers .= 'Reply-To: <' . $from_email . '>' . $line_term;
    $headers .= 'Return-Path: <' . $website_email . '>' . $line_term;
    $headers .= 'X-Sender: <' . $website_email . '>' . $line_term;
    $cc_address = $no_cc ? '' : get_option('cc_address');
    if ($cc_address != '' && !in_array($cc_address, $to_email)) {
        $headers .= (get_option('bcc') == '1' ? 'Bcc: <' : 'Cc: <') . $cc_address . '>' . $line_term;
    }
    $headers .= 'Message-ID: <' . $_boundary . '@' . get_domain() . '>' . $line_term;
    $headers .= 'X-Priority: ' . strval($priority) . $line_term;
    $brand_name = get_value('rebrand_name');
    if (is_null($brand_name)) {
        $brand_name = 'ocPortal';
    }
    $headers .= 'X-Mailer: ' . $brand_name . $line_term;
    $headers .= 'MIME-Version: 1.0' . $line_term;
    if (!is_null($attachments) || !$simplify_when_can) {
        $headers .= 'Content-Type: multipart/mixed;' . "\n\t" . 'boundary="' . $boundary . '"';
    } else {
        $headers .= 'Content-Type: multipart/alternative;' . "\n\t" . 'boundary="' . $boundary2 . '"';
    }
    $sending_message = '';
    $sending_message .= 'This is a multi-part message in MIME format.' . $line_term . $line_term;
    if (!is_null($attachments) || !$simplify_when_can) {
        $sending_message .= '--' . $boundary . $line_term;
        $sending_message .= 'Content-Type: multipart/alternative;' . "\n\t" . 'boundary="' . $boundary2 . '"' . $line_term . $line_term . $line_term;
    }
    global $CID_IMG_ATTACHMENT;
    $CID_IMG_ATTACHMENT = array();
    // Message starts (actually: it is kind of in header form also as it uses mime multi-part)
    if (!$in_html) {
        $_html_content = $html_content->evaluate($lang);
        $_html_content = preg_replace('#(keep|for)_session=[\\d\\w]*#', 'filtered=1', $_html_content);
        $message_html = strpos($_html_content, '<html') !== false ? make_string_tempcode($_html_content) : do_template($mail_template, array('_GUID' => 'b23069c20202aa59b7450ebf8d49cde1', 'CSS' => '{CSS}', 'LOGOURL' => get_logo_url(''), 'LANG' => $lang, 'TITLE' => $subject, 'CONTENT' => $_html_content), $lang, false, NULL, '.tpl', 'templates', $theme);
        $css = css_tempcode(true, true, $message_html->evaluate($lang), $theme);
        $_css = $css->evaluate($lang);
        if (get_option('allow_ext_images') != '1') {
            $_css = preg_replace_callback('#url\\(["\']?(http://[^"]*)["\']?\\)#U', '_mail_css_rep_callback', $_css);
        }
        $html_evaluated = $message_html->evaluate($lang);
        $html_evaluated = str_replace('{CSS}', $_css, $html_evaluated);
        // Cleanup the Comcode a bit
        $message_plain = comcode_to_clean_text($message_raw);
    } else {
        $html_evaluated = $message_raw;
    }
    $base64_encode = get_value('base64_emails') === '1';
    // More robust, but more likely to be spam-blocked, and some servers can scramble it.
    // Plain version
    if (!$in_html) {
        $sending_message .= '--' . $boundary2 . $line_term;
        $sending_message .= 'Content-Type: text/plain; charset=' . (preg_match($regexp, $message_plain) == 0 ? do_lang('charset', NULL, NULL, NULL, $lang) : 'us-ascii') . $line_term;
        // '; name="message.txt"'.	Outlook doesn't like: makes it think it's an attachment
        if ($base64_encode) {
            $sending_message .= 'Content-Transfer-Encoding: base64' . $line_term . $line_term;
            $sending_message .= chunk_split(base64_encode(unixify_line_format($message_plain)) . $line_term, 76, $line_term);
        } else {
            $sending_message .= 'Content-Transfer-Encoding: 8bit' . $line_term . $line_term;
            $sending_message .= wordwrap(str_replace(chr(10), $line_term, unixify_line_format($message_plain)) . $line_term, 998, $line_term);
        }
    }
    // HTML version
    $sending_message .= '--' . $boundary2 . $line_term;
    $sending_message .= 'Content-Type: multipart/related;' . "\n\t" . 'type="text/html";' . "\n\t" . 'boundary="' . $boundary3 . '"' . $line_term . $line_term . $line_term;
    $sending_message .= '--' . $boundary3 . $line_term;
    $sending_message .= 'Content-Type: text/html; charset=' . (preg_match($regexp, $html_evaluated) == 0 ? do_lang('charset', NULL, NULL, NULL, $lang) : 'us-ascii') . $line_term;
    // .'; name="message.html"'.	Outlook doesn't like: makes it think it's an attachment
    if (get_option('allow_ext_images') != '1') {
        $html_evaluated = preg_replace_callback('#<img\\s([^>]*)src="(http://[^"]*)"#U', '_mail_img_rep_callback', $html_evaluated);
        $matches = array();
        foreach (array('#<([^"<>]*\\s)style="([^"]*)"#', '#<style( [^<>]*)?' . '>(.*)</style>#Us') as $over) {
            $num_matches = preg_match_all($over, $html_evaluated, $matches);
            for ($i = 0; $i < $num_matches; $i++) {
                $altered_inner = preg_replace_callback('#url\\(["\']?(http://[^"]*)["\']?\\)#U', '_mail_css_rep_callback', $matches[2][$i]);
                if ($matches[2][$i] != $altered_inner) {
                    $altered_outer = str_replace($matches[2][$i], $altered_inner, $matches[0][$i]);
                    $html_evaluated = str_replace($matches[0][$i], $altered_outer, $html_evaluated);
                }
            }
        }
    }
    if ($base64_encode) {
        $sending_message .= 'Content-Transfer-Encoding: base64' . $line_term . $line_term;
        $sending_message .= chunk_split(base64_encode(unixify_line_format($html_evaluated)) . $line_term, 76, $line_term);
    } else {
        $sending_message .= 'Content-Transfer-Encoding: 8bit' . $line_term . $line_term;
        // Requires RFC 1652
        $sending_message .= wordwrap(str_replace(chr(10), $line_term, unixify_line_format($html_evaluated)) . $line_term, 998, $line_term);
    }
    $total_filesize = 0;
    foreach ($CID_IMG_ATTACHMENT as $id => $img) {
        $sending_message .= '--' . $boundary3 . $line_term;
        $file_path_stub = convert_url_to_path($img);
        $mime_type = get_mime_type(get_file_extension($img));
        $filename = basename($img);
        if (!is_null($file_path_stub)) {
            $total_filesize += @filesize($file_path_stub);
            if ($total_filesize > 1024 * 1024 * 5) {
                continue;
            }
            // Too large to process into an email
            $file_contents = @file_get_contents($file_path_stub);
        } else {
            $file_contents = http_download_file($img, NULL, false);
            $total_filesize += strlen($file_contents);
            if ($total_filesize >= 1024 * 1024 * 5) {
                continue;
            }
            // Too large to process into an email
            if (!is_null($GLOBALS['HTTP_DOWNLOAD_MIME_TYPE'])) {
                $mime_type = $GLOBALS['HTTP_DOWNLOAD_MIME_TYPE'];
            }
            if (!is_null($GLOBALS['HTTP_FILENAME'])) {
                $filename = $GLOBALS['HTTP_FILENAME'];
            }
        }
        $sending_message .= 'Content-Type: ' . str_replace("\r", '', str_replace("\n", '', $mime_type)) . $line_term;
        $sending_message .= 'Content-ID: <' . $id . '>' . $line_term;
        $sending_message .= 'Content-Disposition: inline; filename="' . str_replace("\r", '', str_replace("\n", '', $filename)) . '"' . $line_term;
        $sending_message .= 'Content-Transfer-Encoding: base64' . $line_term . $line_term;
        if (is_string($file_contents)) {
            $sending_message .= chunk_split(base64_encode($file_contents), 76, $line_term);
        }
    }
    $sending_message .= $line_term . '--' . $boundary3 . '--' . $line_term . $line_term;
    $sending_message .= $line_term . '--' . $boundary2 . '--' . $line_term . $line_term;
    // Attachments
    if (!is_null($attachments)) {
        foreach ($attachments as $path => $filename) {
            $sending_message .= '--' . $boundary . $line_term;
            $sending_message .= 'Content-Type: ' . get_mime_type(get_file_extension($filename)) . $line_term;
            // .'; name="'.str_replace("\r",'',str_replace("\n",'',$filename)).'"'   http://www.imc.org/ietf-822/old-archive2/msg02121.html
            $sending_message .= 'Content-Transfer-Encoding: base64' . $line_term;
            $sending_message .= 'Content-Disposition: attachment; filename="' . str_replace("\r", '', str_replace("\n", '', $filename)) . '"' . $line_term . $line_term;
            if (strpos($path, '://') === false) {
                $sending_message .= chunk_split(base64_encode(file_get_contents($path)), 76, $line_term);
            } else {
                require_code('files');
                $sending_message .= chunk_split(base64_encode(http_download_file($path)), 76, $line_term);
            }
        }
        $sending_message .= $line_term . '--' . $boundary . '--' . $line_term;
    }
    // Support for SMTP sockets rather than PHP mail()
    $error = NULL;
    if (get_option('smtp_sockets_use') == '1') {
        $worked = false;
        $host = get_option('smtp_sockets_host');
        $port = intval(get_option('smtp_sockets_port'));
        $errno = 0;
        $errstr = '';
        foreach ($to_email as $i => $to) {
            $socket = @fsockopen($host, $port, $errno, $errstr, 30.0);
            if ($socket !== false) {
                $rcv = fread($socket, 1024);
                $base_url = parse_url(get_base_url());
                $domain = $base_url['host'];
                // Login if necessary
                $username = get_option('smtp_sockets_username');
                $password = get_option('smtp_sockets_password');
                if ($username != '') {
                    fwrite($socket, 'EHLO ' . $domain . "\r\n");
                    $rcv = fread($socket, 1024);
                    fwrite($socket, "AUTH LOGIN\r\n");
                    $rcv = fread($socket, 1024);
                    if (strtolower(substr($rcv, 0, 3)) == '334') {
                        fwrite($socket, base64_encode($username) . "\r\n");
                        $rcv = fread($socket, 1024);
                        if (strtolower(substr($rcv, 0, 3)) == '235' || strtolower(substr($rcv, 0, 3)) == '334') {
                            fwrite($socket, base64_encode($password) . "\r\n");
                            $rcv = fread($socket, 1024);
                            if (strtolower(substr($rcv, 0, 3)) == '235') {
                            } else {
                                $error = do_lang('MAIL_ERROR_CONNECT_PASSWORD') . ' (' . str_replace($password, '*', $rcv) . ')';
                            }
                        } else {
                            $error = do_lang('MAIL_ERROR_CONNECT_USERNAME') . ' (' . $rcv . ')';
                        }
                    } else {
                        $error = do_lang('MAIL_ERROR_CONNECT_AUTH') . ' (' . $rcv . ')';
                    }
                } else {
                    fwrite($socket, 'HELO ' . $domain . "\r\n");
                    $rcv = fread($socket, 1024);
                }
                if (is_null($error)) {
                    $smtp_from_address = get_option('smtp_from_address');
                    if ($smtp_from_address == '') {
                        $smtp_from_address = $from_email;
                    }
                    fwrite($socket, 'MAIL FROM:<' . $website_email . ">\r\n");
                    $rcv = fread($socket, 1024);
                    if (strtolower(substr($rcv, 0, 3)) == '250' || strtolower(substr($rcv, 0, 3)) == '251') {
                        $sent_one = false;
                        fwrite($socket, "RCPT TO:<" . $to_email[$i] . ">\r\n");
                        $rcv = fread($socket, 1024);
                        if (strtolower(substr($rcv, 0, 3)) != '250' && strtolower(substr($rcv, 0, 3)) != '251') {
                            $error = do_lang('MAIL_ERROR_TO') . ' (' . $rcv . ')' . ' ' . $to_email[$i];
                        } else {
                            $sent_one = true;
                        }
                        if ($sent_one) {
                            fwrite($socket, "DATA\r\n");
                            $rcv = fread($socket, 1024);
                            if (strtolower(substr($rcv, 0, 3)) == '354') {
                                $attractive_date = strftime('%d %B %Y  %H:%M:%S', time());
                                $_to_name = preg_replace('#@.*$#', '', is_array($to_name) ? $to_name[$i] : $to_name);
                                // preg_replace is because some servers may reject sending names that look like e-mail addresses. ocP tries this from recommend module.
                                if (count($to_email) == 1) {
                                    if ($_to_name == '') {
                                        fwrite($socket, 'To: ' . $to_email[$i] . "\r\n");
                                    } else {
                                        fwrite($socket, 'To: ' . $_to_name . ' <' . $to_email[$i] . '>' . "\r\n");
                                    }
                                } else {
                                    fwrite($socket, 'To: ' . $_to_name . "\r\n");
                                }
                                fwrite($socket, 'Subject: ' . $tightened_subject . "\r\n");
                                fwrite($socket, 'Date: ' . $attractive_date . "\r\n");
                                $headers = preg_replace('#^\\.#m', '..', $headers);
                                $sending_message = preg_replace('#^\\.#m', '..', $sending_message);
                                fwrite($socket, $headers . "\r\n");
                                fwrite($socket, $sending_message);
                                fwrite($socket, "\r\n.\r\n");
                                $rcv = fread($socket, 1024);
                                fwrite($socket, "QUIT\r\n");
                                $rcv = fread($socket, 1024);
                            } else {
                                $error = do_lang('MAIL_ERROR_DATA') . ' (' . $rcv . ')';
                            }
                        }
                    } else {
                        $error = do_lang('MAIL_ERROR_FROM') . ' (' . $rcv . ')';
                    }
                    if (@fwrite($socket, "RSET\r\n") === false) {
                        @fclose($socket);
                        $socket = NULL;
                    } else {
                        $rcv = fread($socket, 1024);
                    }
                }
                if (!is_null($socket)) {
                    fclose($socket);
                }
                if (is_null($error)) {
                    $worked = true;
                }
            } else {
                $error = do_lang('MAIL_ERROR_CONNECT', $host, strval($port));
            }
        }
    } else {
        $worked = false;
        foreach ($to_email as $i => $to) {
            //exit($headers.chr(10).$sending_message);
            $GLOBALS['SUPPRESS_ERROR_DEATH'] = true;
            $additional = '';
            if (get_option('enveloper_override') == '1') {
                $additional = '-f ' . $website_email;
            }
            $_to_name = preg_replace('#@.*$#', '', is_array($to_name) ? $to_name[$i] : $to_name);
            // preg_replace is because some servers may reject sending names that look like e-mail addresses. ocP tries this from recommend module.
            if ($_to_name == '' || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
                $to_line = $to;
            } else {
                $to_line = '"' . $_to_name . '" <' . $to . '>';
            }
            //if (function_exists('mb_language')) mb_language('en');	Stop overridden mbstring mail function from messing and base64'ing stuff. Actually we don't need this as we make sure to pass through as headers with blank message, bypassing any filtering.
            if (str_replace(array('on', 'true', 'yes'), array('1', '1', '1'), strtolower(ini_get('safe_mode'))) == '1') {
                $worked = mail($to_line, $tightened_subject, $sending_message, $headers);
            } else {
                $worked = mail($to_line, $tightened_subject, $sending_message, $headers, $additional);
            }
            if (!$worked && isset($php_errormsg)) {
                $error = $php_errormsg;
            }
            $GLOBALS['SUPPRESS_ERROR_DEATH'] = false;
        }
    }
    if (!$worked) {
        $SENDING_MAIL = false;
        if (get_param_integer('keep_hide_mail_failure', 0) == 0) {
            require_code('site');
            attach_message(!is_null($error) ? make_string_tempcode($error) : do_lang_tempcode('MAIL_FAIL', escape_html(get_option('staff_address'))), 'warn');
        } else {
            return warn_screen(get_page_title('ERROR_OCCURRED'), do_lang_tempcode('MAIL_FAIL', escape_html(get_option('staff_address'))));
        }
    }
    $SENDING_MAIL = false;
    return NULL;
}
コード例 #20
0
ファイル: install.php プロジェクト: erico-deh/ocPortal
/**
 * Try and get a good .htaccess file built.
 * @param  resource		FTP connection to server
 */
function test_htaccess($conn)
{
    $clauses = array();
    $clauses[] = <<<END
# Disable inaccurate security scanning (ocPortal has it's own)
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
END;
    $php_value_ok = substr(ocp_srv('SERVER_SOFTWARE'), 0, 10) != 'LightSpeed';
    if ($php_value_ok) {
        $clauses[] = <<<END
# ocPortal needs uploads; many hosts leave these low
php_value post_max_size "16M"
php_value upload_max_filesize "16M"
END;
    }
    if ($php_value_ok) {
        $clauses[] = <<<END
# Turn insecure things off
php_flag allow_url_fopen off
END;
    }
    if ($php_value_ok) {
        $clauses[] = <<<END
php_flag register_globals off
END;
    }
    if ($php_value_ok) {
        $clauses[] = <<<END
php_value max_input_vars "2000"
php_value mbstring.func_overload "0"
# Suhosin can cause problems on configuration and Catalogue forms, which use a lot of fields
php_value suhosin.post.max_vars "2000"
php_value suhosin.request.max_vars "2000"
php_value suhosin.cookie.max_vars "400"
php_value suhosin.cookie.max_name_length "150"
php_value suhosin.post.max_value_length "100000000"
php_value suhosin.request.max_value_length "100000000"
php_value suhosin.post.max_totalname_length "10000"
php_value suhosin.request.max_totalname_length "10000"
php_flag suhosin.cookie.encrypt off
php_flag suhosin.sql.union off
END;
    }
    if ($php_value_ok) {
        $clauses[] = <<<END
# Put some limits up. ocPortal is stable enough not to cause problems- it'll only use higher limits when it really needs them
php_value memory_limit "128M"
END;
    }
    if ($php_value_ok) {
        $clauses[] = <<<END
php_value max_input_time "60"
END;
    }
    /*// NB: This'll only work in PHP6+   Bad idea, will miss temp directory
    $file_base=$GLOBALS['FILE_BASE'];
    $clauses[]=<<<END
    # Sandbox ocPortal to it's own directory
    php_value open_basedir "{$file_base}"
    END;
    */
    $clauses[] = <<<END
Options +FollowSymLinks
END;
    $clauses[] = <<<END
RewriteEngine on

# Redirect away from modules called directly by URL. Helpful as it allows you to "run" a module file in a debugger and still see it running.
RewriteRule ^([^=]*)webdav.php/([^=]*)pages/(modules|modules\\_custom)/([^/]*)\\.php\$ - [L]
RewriteRule ^([^=]*)pages/(modules|modules\\_custom)/([^/]*)\\.php\$ \$1index.php\\?page=\$3 [L,QSA,R]

# These have a specially reduced form (no need to make it too explicit that these are CEDI)
#  We shouldn't shorten them too much, or the actual zone or base url might conflict
RewriteRule ^([^=]*)pg/s/([^\\&\\?]*)/index\\.php\$ \$1index.php\\?page=cedi&id=\$2 [L,QSA]

# These have a specially reduce form (wide is implied)
RewriteRule ^([^=]*)pg/galleries/image/([^\\&\\?]*)/index\\.php(.*)\$ \$1index.php\\?page=galleries&type=image&id=\$2&wide=1\$3 [L,QSA]
RewriteRule ^([^=]*)pg/galleries/video/([^\\&\\?]*)/index\\.php(.*)\$ \$1index.php\\?page=galleries&type=video&id=\$2&wide=1\$3 [L,QSA]
RewriteRule ^([^=]*)pg/iotds/view/([^\\&\\?]*)/index\\.php(.*)\$ \$1index.php\\?page=iotds&type=view&id=\$2&wide=1\$3 [L,QSA]

# These are standard patterns
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)/([^/\\&\\?]*)/([^\\&\\?]*)/index\\.php(.*)\$ \$1index.php\\?page=\$2&type=\$3&id=\$4\$5 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)/([^/\\&\\?]*)/index\\.php(.*)\$ \$1index.php\\?page=\$2&type=\$3\$4 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)/index\\.php(.*)\$ \$1index.php\\?page=\$2\$3 [L,QSA]
# This one is weird... apache strips out // and turns to /, thus requiring an extra pattern...
RewriteRule ^([^=]*)pg/index\\.php(.*)\$ \$1index.php\\?page=\$3 [L,QSA]

# Now the same, but without any additional parameters (and thus no index.php)
RewriteRule ^([^=]*)pg/s/([^\\&\\?]*)\$ \$1index.php\\?page=cedi&id=\$2 [L,QSA]
RewriteRule ^([^=]*)pg/galleries/image/([^\\&\\?]*)\$ \$1index.php\\?page=galleries&type=image&id=\$2&wide=1\$3 [L,QSA]
RewriteRule ^([^=]*)pg/galleries/video/([^\\&\\?]*)\$ \$1index.php\\?page=galleries&type=video&id=\$2&wide=1\$3 [L,QSA]
RewriteRule ^([^=]*)pg/iotds/view/([^\\&\\?]*)\$ \$1index.php\\?page=iotds&type=view&id=\$2&wide=1 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)/([^/\\&\\?]*)/([^\\&\\?]*)/\$ \$1index.php\\?page=\$2&type=\$3&id=\$4 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)/([^/\\&\\?]*)/([^\\&\\?]*)\$ \$1index.php\\?page=\$2&type=\$3&id=\$4 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)/([^/\\&\\?]*)\$ \$1index.php\\?page=\$2&type=\$3 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?]*)\$ \$1index.php\\?page=\$2 [L,QSA]

# And these for those nasty situations where index.php was missing and we couldn't do anything about it (usually due to keep_session creeping into a semi-cached URL)
RewriteRule ^([^=]*)pg/s/([^\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$3&page=cedi&id=\$2 [L,QSA]
RewriteRule ^([^=]*)pg/galleries/image/([^/\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$5&page=galleries&type=image&id=\$2&wide=1&\$3 [L,QSA]
RewriteRule ^([^=]*)pg/galleries/video/([^/\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$5&page=galleries&type=video&id=\$2&wide=1&\$3 [L,QSA]
RewriteRule ^([^=]*)pg/iotds/view/([^/\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$3&page=iotds&type=view&id=\$2&wide=1 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?\\.]*)/([^/\\&\\?\\.]*)/([^/\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$5&page=\$2&type=\$3&id=\$4 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?\\.]*)/([^/\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$4&page=\$2&type=\$3 [L,QSA]
RewriteRule ^([^=]*)pg/([^/\\&\\?\\.]*)&(.*)\$ \$1index.php\\?\$3&page=\$2 [L,QSA]

# These have a specially reduced form (no need to make it too explicit that these are CEDI)
#  We shouldn't shorten them too much, or the actual zone or base url might conflict
RewriteRule ^(site|forum|adminzone|cms|collaboration)/s/([^\\&\\?]*)\\.htm\$ \$1/index.php\\?page=cedi&id=\$2 [L,QSA]
RewriteRule ^s/([^\\&\\?]*)\\.htm\$ index\\.php\\?page=cedi&id=\$1 [L,QSA]

# These have a specially reduce form (wide is implied)
RewriteRule ^(site|forum|adminzone|cms|collaboration)/galleries/image/([^\\&\\?]*)\\.htm\$ \$1/index.php\\?page=galleries&type=image&id=\$2&wide=1 [L,QSA]
RewriteRule ^(site|forum|adminzone|cms|collaboration)/galleries/video/([^\\&\\?]*)\\.htm\$ \$1/index.php\\?page=galleries&type=video&id=\$2&wide=1 [L,QSA]
RewriteRule ^(site|forum|adminzone|cms|collaboration)/iotds/view/([^\\&\\?]*)\\.htm\$ \$1/index.php\\?page=iotds&type=view&id=\$2&wide=1 [L,QSA]

# These are standard patterns
RewriteRule ^(site|forum|adminzone|cms|collaboration)/([^/\\&\\?]+)/([^/\\&\\?]*)/([^\\&\\?]*)\\.htm\$ \$1/index.php\\?page=\$2&type=\$3&id=\$4 [L,QSA]
RewriteRule ^(site|forum|adminzone|cms|collaboration)/([^/\\&\\?]+)/([^/\\&\\?]*)\\.htm\$ \$1/index.php\\?page=\$2&type=\$3 [L,QSA]
RewriteRule ^(site|forum|adminzone|cms|collaboration)/([^/\\&\\?]+)\\.htm\$ \$1/index.php\\?page=\$2 [L,QSA]
RewriteRule ^([^/\\&\\?]+)/([^/\\&\\?]*)/([^\\&\\?]*)\\.htm\$ index.php\\?page=\$1&type=\$2&id=\$3 [L,QSA]
RewriteRule ^([^/\\&\\?]+)/([^/\\&\\?]*)\\.htm\$ index.php\\?page=\$1&type=\$2 [L,QSA]
RewriteRule ^([^/\\&\\?]+)\\.htm\$ index.php\\?page=\$1 [L,QSA]
END;
    $clauses[] = <<<END
order allow,deny
# IP bans go here (leave this comment here! If this file is writeable, ocPortal will write in IP bans below, in sync with it's own DB-based banning - this makes DOS/hack attack prevention stronger)
# deny from xxx.xx.x.x (leave this comment here!)
allow from all
END;
    $base = dirname(ocp_srv('PHP_SELF'));
    $clauses[] = <<<END
<FilesMatch !"\\.(jpg|jpeg|gif|png|ico)\$">
ErrorDocument 404 {$base}/index.php?page=404
</FilesMatch>
END;
    if (is_writable_wrap(get_file_base() . '/exports/mods') && (!file_exists(get_file_base() . '/.htaccess') || trim(file_get_contents(get_file_base() . '/.htaccess')) == '')) {
        global $HTTP_MESSAGE;
        $domain = ocp_srv('HTTP_HOST');
        if (substr($domain, 0, 4) == 'www.') {
            $domain = substr($domain, 4);
        }
        $colon_pos = strpos($domain, ':');
        if ($colon_pos !== false) {
            $domain = substr($domain, 0, $colon_pos);
        }
        $pos = strpos(ocp_srv('PHP_SELF'), 'install.php');
        if ($pos === false) {
            $pos = strlen(ocp_srv('PHP_SELF'));
        } else {
            $pos--;
        }
        $port = ocp_srv('SERVER_PORT');
        if ($port == '' || $port == '80' || $port == '443') {
            $port = '';
        } else {
            $port = ':' . $port;
        }
        $base_url = post_param('base_url', 'http://' . $domain . $port . substr(ocp_srv('PHP_SELF'), 0, $pos));
        if (substr($base_url, -1) == '/') {
            $base_url = substr($base_url, 0, strlen($base_url) - 1);
        }
        foreach ($clauses as $i => $clause) {
            $myfile = fopen(get_file_base() . '/exports/mods/index.php', 'wt');
            fwrite($myfile, "<" . "?php\n\t\t\t@header('Expires: Mon, 20 Dec 1998 01:00:00 GMT');\n\t\t\t@header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');\n\t\t\t@header('Pragma: no-cache'); // for proxies, and also IE\n\t\t\t");
            fclose($myfile);
            $myfile = fopen(get_file_base() . '/exports/mods/.htaccess', 'wt');
            fwrite($myfile, $clause);
            fclose($myfile);
            $HTTP_MESSAGE = '';
            http_download_file($base_url . '/exports/mods/index.php', NULL, false);
            if ($HTTP_MESSAGE != '200') {
                $clauses[$i] = NULL;
            }
            unlink(get_file_base() . '/exports/mods/.htaccess');
        }
        $out = '';
        foreach ($clauses as $i => $clause) {
            if (!is_null($clause)) {
                $out .= $clause . chr(10) . chr(10);
            }
        }
        if (is_suexec_like()) {
            @unlink(get_file_base() . '/.htaccess');
            $tmp = fopen(get_file_base() . '/.htaccess', 'wb');
            fwrite($tmp, $out);
            fclose($tmp);
        } else {
            @ftp_delete($conn, '.htaccess');
            $tmp = fopen(get_file_base() . '/ocp_inst_tmp/tmp', 'wb');
            fwrite($tmp, $out);
            fclose($tmp);
            @ftp_put($conn, '.htaccess', get_file_base() . '/ocp_inst_tmp/tmp', FTP_TEXT);
            @ftp_site($conn, 'CHMOD 644 .htaccess');
        }
    }
}
コード例 #21
0
ファイル: mail.php プロジェクト: erico-deh/ocPortal
/**
 * Attempt to send an e-mail to the specified recipient. The mail will be forwarding to the CC address specified in the options (if there is one, and if not specified not to cc).
 * The mail will be sent in dual HTML/text format, where the text is the unconverted comcode source: if a member does not read HTML mail, they may wish to fallback to reading that.
 *
 * @param  string			The subject of the mail in plain text
 * @param  LONG_TEXT		The message, as Comcode
 * @param  ?array			The destination (recipient) e-mail addresses [array of strings] (NULL: site staff address)
 * @param  ?mixed			The recipient name. Array or string. (NULL: site name)
 * @param  EMAIL			The from address (blank: site staff address)
 * @param  string			The from name (blank: site name)
 * @param  integer		The message priority (1=urgent, 3=normal, 5=low)
 * @range  1 5
 * @param  ?array			An list of attachments (each attachment being a map, path=>filename) (NULL: none)
 * @param  boolean		Whether to NOT CC to the CC address
 * @param  ?MEMBER		Convert comcode->tempcode as this member (a privilege thing: we don't want people being able to use admin rights by default!) (NULL: guest)
 * @param  boolean		Replace above with arbitrary admin
 * @param  boolean		HTML-only
 * @param  boolean		Whether to bypass queueing, because this code is running as a part of the queue management tools
 * @param  ID_TEXT		The template used to show the email
 * @param  boolean		Whether to bypass queueing
 * @return ?tempcode		A full page (not complete XHTML) piece of tempcode to output (NULL: it worked so no tempcode message)
 */
function mail_wrap($subject_tag, $message_raw, $to_email = NULL, $to_name = NULL, $from_email = '', $from_name = '', $priority = 3, $attachments = NULL, $no_cc = false, $as = NULL, $as_admin = false, $in_html = false, $coming_out_of_queue = false, $mail_template = 'MAIL', $bypass_queue = false)
{
    if (get_option('smtp_sockets_use') == '0') {
        return non_overrided__mail_wrap($subject_tag, $message_raw, $to_email, $to_name, $from_email, $from_name, $priority, $attachments, $no_cc, $as, $as_admin, $in_html, $coming_out_of_queue);
    }
    if (running_script('stress_test_loader')) {
        return NULL;
    }
    if (is_null($bypass_queue)) {
        $bypass_queue = $priority < 3 || strpos(serialize($attachments), 'tmpfile') !== false;
    }
    global $EMAIL_ATTACHMENTS;
    $EMAIL_ATTACHMENTS = array();
    require_code('site');
    require_code('mime_types');
    if (is_null($as)) {
        $as = $GLOBALS['FORUM_DRIVER']->get_guest_id();
    }
    if (!$coming_out_of_queue) {
        $GLOBALS['SITE_DB']->query('DELETE FROM ' . get_table_prefix() . 'logged_mail_messages WHERE m_date_and_time<' . strval(time() - 60 * 60 * 24 * 14) . ' AND m_queued=0');
        // Log it all for 2 weeks, then delete
        $through_queue = !$bypass_queue && (get_option('mail_queue_debug') === '1' || get_option('mail_queue') === '1' && cron_installed());
        $GLOBALS['SITE_DB']->query_insert('logged_mail_messages', array('m_subject' => $subject_tag, 'm_message' => $message_raw, 'm_to_email' => serialize($to_email), 'm_to_name' => serialize($to_name), 'm_from_email' => $from_email, 'm_from_name' => $from_name, 'm_priority' => 3, 'm_attachments' => serialize($attachments), 'm_no_cc' => $no_cc ? 1 : 0, 'm_as' => $as, 'm_as_admin' => $as_admin ? 1 : 0, 'm_in_html' => $in_html ? 1 : 0, 'm_date_and_time' => time(), 'm_member_id' => get_member(), 'm_url' => get_self_url(true), 'm_queued' => $through_queue ? 1 : 0, 'm_template' => $mail_template));
        if ($through_queue) {
            return NULL;
        }
    }
    if (count($attachments) == 0) {
        $attachments = NULL;
    }
    global $SENDING_MAIL;
    if ($SENDING_MAIL) {
        return NULL;
    }
    $SENDING_MAIL = true;
    // To and from, and language
    $staff_address = get_option('staff_address');
    if (is_null($to_email)) {
        $to_email = array($staff_address);
    }
    $to_email_new = array();
    foreach ($to_email as $test_address) {
        if ($test_address != '') {
            $to_email_new[] = $test_address;
        }
    }
    $to_email = $to_email_new;
    if ($to_email == array()) {
        $SENDING_MAIL = false;
        return NULL;
    }
    if ($to_email[0] == $staff_address) {
        $lang = get_site_default_lang();
    } else {
        $lang = user_lang();
        if (method_exists($GLOBALS['FORUM_DRIVER'], 'get_member_from_email_address')) {
            $member_id = $GLOBALS['FORUM_DRIVER']->get_member_from_email_address($to_email[0]);
            if (!is_null($member_id)) {
                $lang = get_lang($member_id);
            }
        }
    }
    if (is_null($to_name)) {
        if ($to_email[0] == $staff_address) {
            $to_name = get_site_name();
        } else {
            $to_name = '';
        }
    }
    if ($from_email == '') {
        $from_email = get_option('staff_address');
    }
    if ($from_name == '') {
        $from_name = get_site_name();
    }
    $theme = method_exists($GLOBALS['FORUM_DRIVER'], 'get_theme') ? $GLOBALS['FORUM_DRIVER']->get_theme() : 'default';
    if ($theme == 'default') {
        $theme = $GLOBALS['FORUM_DRIVER']->get_theme('');
        // ... So get theme of welcome zone
    }
    // Our subject
    $_subject = do_template('MAIL_SUBJECT', array('_GUID' => '44a57c666bb00f96723256e26aade9e5', 'SUBJECT_TAG' => $subject_tag), $lang, false, NULL, '.tpl', 'templates', $theme);
    $subject = $_subject->evaluate($lang);
    // Note that this is slightly against spec, because characters aren't forced to be printable us-ascii. But it's better we allow this (which works in practice) than risk incompatibility via charset-base64 encoding.
    // Evaluate message. Needs doing early so we know if we have any headers
    // Misc settings
    $website_email = get_option('website_email');
    if ($website_email == '') {
        $website_email = $from_email;
    }
    $cc_address = $no_cc ? '' : get_option("cc_address");
    global $CID_IMG_ATTACHMENT;
    $CID_IMG_ATTACHMENT = array();
    // Decide message
    $GLOBALS['NO_LINK_TITLES'] = true;
    global $LAX_COMCODE;
    $temp = $LAX_COMCODE;
    $LAX_COMCODE = true;
    $html_content = comcode_to_tempcode($message_raw, $as, $as_admin);
    $LAX_COMCODE = $temp;
    $GLOBALS['NO_LINK_TITLES'] = false;
    if (!$in_html) {
        $_html_content = $html_content->evaluate($lang);
        $_html_content = preg_replace('#(keep|for)_session=[\\d\\w]*#', 'filtered=1', $_html_content);
        $message_html = strpos($_html_content, '<html') !== false ? make_string_tempcode($_html_content) : do_template($mail_template, array('_GUID' => 'b23069c20202aa59b7450ebf8d49cde1', 'CSS' => '{CSS}', 'LOGOURL' => get_logo_url(''), 'LANG' => $lang, 'TITLE' => $subject, 'CONTENT' => $_html_content), $lang, false, NULL, '.tpl', 'templates', $theme);
        $css = css_tempcode(true, true, $message_html->evaluate($lang), $theme);
        $_css = $css->evaluate($lang);
        if (get_option('allow_ext_images') != '1') {
            $_css = preg_replace_callback('#url\\(["\']?(http://[^"]*)["\']?\\)#U', '_mail_css_rep_callback', $_css);
        }
        $html_evaluated = $message_html->evaluate($lang);
        $html_evaluated = str_replace('{CSS}', $_css, $html_evaluated);
        // Cleanup the Comcode a bit
        $message_plain = comcode_to_clean_text($message_raw);
    } else {
        $html_evaluated = $message_raw;
    }
    // Character set
    $regexp = '#^[\\x' . dechex(32) . '-\\x' . dechex(126) . ']*$#';
    $charset = preg_match($regexp, $html_evaluated) == 0 ? do_lang('charset', NULL, NULL, NULL, $lang) : 'us-ascii';
    // CID attachments
    if (get_option('allow_ext_images') != '1') {
        $html_evaluated = preg_replace_callback('#<img\\s([^>]*)src="(http://[^"]*)"#U', '_mail_img_rep_callback', $html_evaluated);
        $matches = array();
        foreach (array('#<([^"<>]*\\s)style="([^"]*)"#', '#<style( [^<>]*)?' . '>(.*)</style>#Us') as $over) {
            $num_matches = preg_match_all($over, $html_evaluated, $matches);
            for ($i = 0; $i < $num_matches; $i++) {
                $altered_inner = preg_replace_callback('#url\\(["\']?(http://[^"]*)["\']?\\)#U', '_mail_css_rep_callback', $matches[2][$i]);
                if ($matches[2][$i] != $altered_inner) {
                    $altered_outer = str_replace($matches[2][$i], $altered_inner, $matches[0][$i]);
                    $html_evaluated = str_replace($matches[0][$i], $altered_outer, $html_evaluated);
                }
            }
        }
    }
    $cid_attachments = array();
    foreach ($CID_IMG_ATTACHMENT as $id => $img) {
        $file_path_stub = convert_url_to_path($img);
        $mime_type = get_mime_type(get_file_extension($img));
        $filename = basename($img);
        if (!is_null($file_path_stub)) {
            $cid_attachment = array('mime' => $mime_type, 'filename' => $filename, 'path' => $file_path_stub, 'temp' => false, 'cid' => $id);
        } else {
            $myfile = ocp_tempnam('email_attachment');
            http_download_file($img, NULL, false, false, 'ocPortal', NULL, NULL, NULL, NULL, NULL, $myfile);
            if (!is_null($GLOBALS['HTTP_DOWNLOAD_MIME_TYPE'])) {
                $mime_type = $GLOBALS['HTTP_DOWNLOAD_MIME_TYPE'];
            }
            if (!is_null($GLOBALS['HTTP_FILENAME'])) {
                $filename = $GLOBALS['HTTP_FILENAME'];
            }
            $cid_attachment = array('mime' => $mime_type, 'filename' => $filename, 'path' => $myfile, 'temp' => true, 'cid' => $id);
        }
        $cid_attachments[] = $cid_attachment;
    }
    // Attachments
    $real_attachments = array();
    $attachments = array_merge(is_null($attachments) ? array() : $attachments, $EMAIL_ATTACHMENTS);
    if (!is_null($attachments)) {
        foreach ($attachments as $path => $filename) {
            $mime_type = get_mime_type(get_file_extension($filename));
            if (strpos($path, '://') === false) {
                $real_attachment = array('mime' => $mime_type, 'filename' => $filename, 'path' => $path, 'temp' => false);
            } else {
                $myfile = ocp_tempnam('email_attachment');
                http_download_file($path, NULL, false, false, 'ocPortal', NULL, NULL, NULL, NULL, NULL, $myfile);
                if (!is_null($GLOBALS['HTTP_DOWNLOAD_MIME_TYPE'])) {
                    $mime_type = $GLOBALS['HTTP_DOWNLOAD_MIME_TYPE'];
                }
                if (!is_null($GLOBALS['HTTP_FILENAME'])) {
                    $filename = $GLOBALS['HTTP_FILENAME'];
                }
                $real_attachment = array('mime' => $mime_type, 'filename' => $filename, 'path' => $myfile, 'temp' => true);
            }
            $real_attachments[] = $real_attachment;
        }
    }
    // ==========================
    // Interface with SwiftMailer
    // ==========================
    require_code('Swift-4.1.1/lib/swift_required');
    // Read in SMTP settings
    $host = get_option('smtp_sockets_host');
    $port = intval(get_option('smtp_sockets_port'));
    $username = get_option('smtp_sockets_username');
    $password = get_option('smtp_sockets_password');
    $smtp_from_address = get_option('smtp_from_address');
    if ($smtp_from_address != '') {
        $from_email = $smtp_from_address;
    }
    // Create the Transport
    $transport = Swift_SmtpTransport::newInstance($host, $port)->setUsername($username)->setPassword($password);
    if ($port == 419 || $port == 465 || $port == 587) {
        $transport->setEncryption('tls');
    }
    // Create the Mailer using your created Transport
    $mailer = Swift_Mailer::newInstance($transport);
    // Create a message
    $to_array = array();
    if ($to_name === '') {
        foreach ($to_email as $_to_email) {
            $to_array[] = $_to_email;
        }
    } else {
        foreach ($to_email as $i => $_to_email) {
            $to_array[$_to_email] = is_array($to_name) ? $to_name[$i] : $to_name;
        }
    }
    $message = Swift_Message::newInstance($subject)->setFrom(array($website_email => $from_name))->setReplyTo(array($from_email => $from_name))->setTo($to_array)->setPriority($priority)->setCharset($charset)->setBody($html_evaluated, 'text/html', $charset)->addPart($message_plain, 'text/plain', $charset);
    if ($cc_address != '') {
        $message->setCc($cc_address);
    }
    // Attachments
    foreach ($real_attachments as $r) {
        $attachment = Swift_Attachment::fromPath($r['path'], $r['mime'])->setFilename($r['filename'])->setDisposition('attachment');
        $message->attach($attachment);
    }
    foreach ($cid_attachments as $r) {
        $attachment = Swift_Attachment::fromPath($r['path'], $r['mime'])->setFilename($r['filename'])->setDisposition('attachment')->setId($r['cid']);
        $message->attach($attachment);
    }
    // Send the message, and error collection
    $error = '';
    try {
        $result = $mailer->send($message);
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    if ($error == '' && !$result) {
        $error = 'Unknown error';
    }
    // Attachment cleanup
    foreach ($real_attachments as $r) {
        if ($r['temp']) {
            @unlink($r['path']);
        }
    }
    foreach ($cid_attachments as $r) {
        if ($r['temp']) {
            @unlink($r['path']);
        }
    }
    // Return / Error handling
    $SENDING_MAIL = false;
    if ($error != '') {
        if (get_param_integer('keep_hide_mail_failure', 0) == 0) {
            require_code('site');
            attach_message(!is_null($error) ? make_string_tempcode($error) : do_lang_tempcode('MAIL_FAIL', escape_html(get_option('staff_address'))), 'warn');
        } else {
            return warn_screen(get_page_title('ERROR_OCCURRED'), do_lang_tempcode('MAIL_FAIL', escape_html(get_option('staff_address'))));
        }
    }
    return NULL;
}
コード例 #22
0
ファイル: admin_lang.php プロジェクト: erico-deh/ocPortal
 /**
  * The UI to translate code.
  *
  * @return tempcode		The UI
  */
 function interface_code()
 {
     $lang = filter_naughty_harsh(get_param('lang', ''));
     $lang_new = get_param('lang_new', $lang);
     if ($lang_new != '') {
         require_code('type_validation');
         if (!is_alphanumeric($lang_new, true)) {
             warn_exit(do_lang_tempcode('BAD_CODENAME'));
         }
         if (strlen($lang_new) > 5) {
             warn_exit(do_lang_tempcode('INVALID_LANG_CODE'));
         }
         $lang = $lang_new;
     }
     if ($lang == '') {
         $title = get_page_title('TRANSLATE_CODE');
         $GLOBALS['HELPER_PANEL_TEXT'] = comcode_lang_string('DOC_FIND_LANG_STRING_TIP');
         return $this->choose_lang($title, true, true, do_lang_tempcode('CHOOSE_EDIT_LIST_LANG_FILE'));
     }
     breadcrumb_set_parents(array(array('_SELF:_SELF:misc', do_lang_tempcode('CHOOSE'))));
     breadcrumb_set_self(do_lang_tempcode('TRANSLATE_CODE'));
     $base_lang = fallback_lang();
     $map_a = get_file_base() . '/lang/langs.ini';
     $map_b = get_custom_file_base() . '/lang_custom/langs.ini';
     $search = get_param('search', '', true);
     if ($search != '') {
         $title = get_page_title('TRANSLATE_CODE');
         require_code('form_templates');
         $fields = new ocp_tempcode();
         global $LANGUAGE;
         foreach ($LANGUAGE[user_lang()] as $key => $value) {
             if (strpos(strtolower($value), strtolower($search)) !== false) {
                 $fields->attach(form_input_text($key, '', 'l_' . $key, str_replace('\\n', chr(10), $value), false));
             }
         }
         if ($fields->is_empty()) {
             inform_exit(do_lang_tempcode('NO_ENTRIES'));
         }
         $post_url = build_url(array('page' => '_SELF', 'type' => '_code2'), '_SELF');
         $hidden = new ocp_tempcode();
         $hidden->attach(form_input_hidden('redirect', get_self_url(true)));
         $hidden->attach(form_input_hidden('lang', $lang));
         return do_template('FORM_SCREEN', array('_GUID' => '2d7356fd2c4497ceb19450e65331c9c5', 'TITLE' => $title, 'HIDDEN' => $hidden, 'FIELDS' => $fields, 'URL' => $post_url, 'TEXT' => '', 'SUBMIT_NAME' => do_lang('TRANSLATE_CODE')));
     }
     $lang_file = get_param('lang_file');
     if (!file_exists($map_b)) {
         $map_b = $map_a;
     }
     $map = better_parse_ini_file($map_b);
     $title = get_page_title('_TRANSLATE_CODE', true, array(escape_html($lang_file), escape_html(array_key_exists($lang, $map) ? $map[$lang] : $lang)));
     // Upgrade to custom if not there yet (or maybe we are creating a new lang - same difference)
     $custom_dir = get_custom_file_base() . '/lang_custom/' . $lang;
     if (!file_exists($custom_dir)) {
         require_code('abstract_file_manager');
         force_have_afm_details();
         afm_make_directory('lang_custom/' . $lang, true);
         $cached_dir = get_custom_file_base() . '/lang_cached/' . $lang;
         if (!file_exists($cached_dir)) {
             afm_make_directory('lang_cached/' . $lang, true);
         }
         // Make comcode page dirs
         $zones = find_all_zones();
         foreach ($zones as $zone) {
             $_special_dir = get_custom_file_base() . '/' . $zone . '/pages/comcode_custom/' . $lang;
             if (!file_exists($_special_dir)) {
                 afm_make_directory($zone . ($zone == '' ? '' : '/') . 'pages/comcode_custom/' . $lang, true);
             }
             $_special_dir = get_custom_file_base() . '/' . $zone . '/pages/html_custom/' . $lang;
             if (!file_exists($_special_dir)) {
                 afm_make_directory($zone . ($zone == '' ? '' : '/') . 'pages/html_custom/' . $lang, true);
             }
         }
         // Make templates_cached dirs
         require_code('themes2');
         $themes = find_all_themes();
         foreach (array_keys($themes) as $theme) {
             $_special_dir = get_custom_file_base() . '/themes/' . $theme . '/templates_cached/' . $lang;
             if (!file_exists($_special_dir)) {
                 afm_make_directory('themes/' . $theme . '/templates_cached/' . $lang, true);
             }
         }
     }
     // Get some stuff
     $for_lang = get_lang_file_map($lang, $lang_file);
     $for_base_lang = get_lang_file_map($base_lang, $lang_file, true);
     $descriptions = get_lang_file_descriptions($base_lang, $lang_file);
     // Make our translation page
     $lines = '';
     $intertrans = $this->get_intertran_conv($lang);
     $actions = new ocp_tempcode();
     $next = 0;
     $trans_lot = '';
     $delimit = chr(10) . '=-=-=-=-=-=-=-=-' . chr(10);
     foreach ($for_base_lang as $name => $old) {
         if (array_key_exists($name, $for_lang)) {
             $current = $for_lang[$name];
         } else {
             $current = '';
             //$this->find_lang_matches($old,$lang); Too slow / useless for code translation
         }
         if ($current == '' && strtolower($name) != $name) {
             $trans_lot .= str_replace('\\n', chr(10), str_replace(array('{', '}'), array('(((', ')))'), $old)) . $delimit;
         }
     }
     $translated_stuff = array();
     if ($trans_lot != '' && $intertrans != '') {
         $result = http_download_file('http://translate.google.com/translate_t', NULL, false, false, 'ocPortal', array('text' => $trans_lot, 'langpair' => 'en|' . $intertrans));
         if (!is_null($result)) {
             require_code('character_sets');
             $result = convert_to_internal_encoding($result);
             $matches = array();
             if (preg_match('#<div id=result_box dir="ltr">(.*)</div>#Us', convert_to_internal_encoding($result), $matches) != 0) {
                 $result2 = $matches[1];
                 $result2 = @html_entity_decode($result2, ENT_QUOTES, get_charset());
                 $result2 = preg_replace('#\\s?<br>\\s?#', chr(10), $result2);
                 $result2 = str_replace('> ', '>', str_replace(' <', ' <', str_replace('</ ', '</', str_replace(array('(((', ')))'), array('{', '}'), $result2))));
                 $translated_stuff = explode(trim($delimit), $result2 . chr(10));
             }
         }
     }
     foreach ($for_base_lang + $for_lang as $name => $old) {
         if (array_key_exists($name, $for_lang)) {
             $current = $for_lang[$name];
         } else {
             $current = '';
             //$this->find_lang_matches($old,$lang); Too slow / useless for code translation
         }
         $description = array_key_exists($name, $descriptions) ? $descriptions[$name] : '';
         if ($current == '' && strtolower($name) != $name && array_key_exists($next, $translated_stuff)) {
             $_current = '';
             $translate_auto = trim($translated_stuff[$next]);
             $next++;
         } else {
             $_current = str_replace('\\n', chr(10), $current);
             $translate_auto = NULL;
         }
         if ($_current == '') {
             $_current = str_replace('\\n', chr(10), $old);
         }
         if ($intertrans != '' && get_value('google_translate_api_key') !== NULL) {
             $actions = do_template('TRANSLATE_ACTION', array('_GUID' => '9e9a68cb2c1a1e23a901b84c9af2280b', 'LANG_FROM' => get_site_default_lang(), 'LANG_TO' => $lang, 'NAME' => 'trans_' . $name, 'OLD' => $_current));
         }
         $temp = do_template('TRANSLATE_LINE', array('_GUID' => '9cb331f5852ee043e6ad30b45aedc43b', 'TRANSLATE_AUTO' => $translate_auto, 'DESCRIPTION' => $description, 'NAME' => $name, 'OLD' => str_replace('\\n', chr(10), $old), 'CURRENT' => $_current, 'ACTIONS' => $actions));
         $lines .= $temp->evaluate();
     }
     $url = build_url(array('page' => '_SELF', 'type' => '_code', 'lang_file' => $lang_file, 'lang' => $lang), '_SELF');
     return do_template('TRANSLATE_SCREEN', array('_GUID' => 'b3429f8bd0b4eb79c33709ca43e3207c', 'PAGE' => $lang_file, 'INTERTRANS' => get_value('google_translate_api_key') !== NULL ? $intertrans : '', 'LANG' => $lang, 'LINES' => $lines, 'TITLE' => $title, 'URL' => $url));
 }
コード例 #23
0
ファイル: attachments.php プロジェクト: erico-deh/ocPortal
/**
 * Get tempcode for a Comcode rich-media attachment.
 *
 * @param  ID_TEXT		The attachment tag
 * @set attachment attachment_safe attachment2
 * @param  array			A map of the attributes (name=>val) for the tag
 * @param  array			A map of the attachment properties (name=>val) for the attachment
 * @param  string			A special identifier to mark where the resultant tempcode is going to end up (e.g. the ID of a post)
 * @param  MEMBER			The member who is responsible for this Comcode
 * @param  boolean		Whether to check as arbitrary admin
 * @param  object			The database connection to use
 * @param  ?array			A list of words to highlight (NULL: none)
 * @param  ?MEMBER		The member we are running on behalf of, with respect to how attachments are handled; we may use this members attachments that are already within this post, and our new attachments will be handed to this member (NULL: member evaluating)
 * @param  boolean		Whether to parse so as to create something that would fit inside a semihtml tag. It means we generate HTML, with Comcode written into it where the tag could never be reverse-converted (e.g. a block).
 * @return tempcode		The tempcode for the attachment
 */
function render_attachment($tag, $attributes, $attachment, $pass_id, $source_member, $as_admin, $connection, $highlight_bits = NULL, $on_behalf_of_member = NULL, $semiparse_mode = false)
{
    require_code('comcode_renderer');
    $extension = get_file_extension($attachment['a_original_filename']);
    require_code('mime_types');
    $mime_type = get_mime_type($extension);
    $attachment['CLEAN_SIZE'] = clean_file_size($attachment['a_file_size']);
    $attachment['MIME_TYPE'] = $mime_type;
    $attachment['PASS_ID'] = intval($pass_id) < 0 ? strval(mt_rand(0, 10000)) : $pass_id;
    $attachment['SCRIPT'] = find_script('attachment');
    $attachment['RAND'] = strval(mt_rand(0, 32000));
    if ($connection->connection_write != $GLOBALS['SITE_DB']->connection_write) {
        $attachment['SUP_PARAMS'] = '&forum_db=1';
        $attachment['FORUM_DB_BIN'] = '1';
    } else {
        $attachment['SUP_PARAMS'] = '';
        $attachment['FORUM_DB_BIN'] = '';
    }
    $type = trim(array_key_exists('type', $attributes) ? $attributes['type'] : 'auto');
    $attachment['id'] = strval($attachment['id']);
    $attachment['a_member_id'] = strval($attachment['a_member_id']);
    $attachment['a_file_size'] = strval($attachment['a_file_size']);
    $attachment['a_last_downloaded_time'] = is_null($attachment['a_last_downloaded_time']) ? '' : strval($attachment['a_last_downloaded_time']);
    $attachment['a_add_time'] = strval($attachment['a_add_time']);
    $attachment['a_num_downloads'] = integer_format($attachment['a_num_downloads']);
    require_code('images');
    $attachment['a_width'] = array_key_exists('width', $attributes) ? strval(intval($attributes['width'])) : '';
    $attachment['a_height'] = array_key_exists('height', $attributes) ? strval(intval($attributes['height'])) : '';
    if ($attachment['a_width'] == '' || $attachment['a_height'] == '') {
        if (addon_installed('galleries') && is_video($attachment['a_original_filename']) && url_is_local($attachment['a_url'])) {
            require_code('galleries2');
            $vid_details = get_video_details(get_custom_file_base() . '/' . rawurldecode($attachment['a_url']), $attachment['a_original_filename'], true);
            if ($vid_details !== false) {
                list($_width, $_height, ) = $vid_details;
                if ($attachment['a_width'] == '') {
                    $attachment['a_width'] = strval($_width);
                }
                if ($attachment['a_height'] == '') {
                    $attachment['a_height'] = strval($_height);
                }
            }
        }
        if ($attachment['a_width'] == '' || $attachment['a_height'] == '') {
            if ($attachment['a_width'] == '') {
                $attachment['a_width'] = '240';
            }
            if ($attachment['a_height'] == '') {
                $attachment['a_height'] = '216';
            }
        }
    }
    $attachment['a_align'] = array_key_exists('align', $attributes) ? $attributes['align'] : 'left';
    if (!array_key_exists('a_description', $attachment)) {
        if (array_key_exists('description', $attributes)) {
            $attachment['description'] = $attributes['description'];
        }
        if (!array_key_exists('description', $attachment)) {
            $attachment['description'] = '';
        }
        $attachment['a_description'] = is_object($attachment['description']) ? $attachment['description'] : comcode_to_tempcode($attachment['description'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, NULL, $on_behalf_of_member);
    } else {
        $attachment['a_description'] = comcode_to_tempcode($attachment['a_description'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, NULL, $on_behalf_of_member);
    }
    $attachment['a_type'] = $type;
    $attachment['a_thumb'] = array_key_exists('thumb', $attributes) ? $attributes['thumb'] : '1';
    if ($attachment['a_thumb'] != '0') {
        $attachment['a_thumb'] = '1';
    }
    $attachment['a_thumb_url'] = array_key_exists('thumb_url', $attributes) ? $attributes['thumb_url'] : $attachment['a_thumb_url'];
    switch ($type) {
        case 'email':
            require_code('mail');
            global $EMAIL_ATTACHMENTS;
            if (url_is_local($attachment['a_url'])) {
                $attachment['a_url'] = get_custom_base_url() . '/' . $attachment['a_url'];
            }
            $EMAIL_ATTACHMENTS[$attachment['a_url']] = $attachment['a_original_filename'];
            $temp_tpl = new ocp_tempcode();
            break;
        case 'code':
            $url = $attachment['a_url'];
            if (url_is_local($url)) {
                $url = get_custom_base_url() . '/' . $url;
            }
            $file_contents = http_download_file($url, 1024 * 1024 * 20);
            list($_embed, $title) = do_code_box($extension, make_string_tempcode($file_contents));
            if ($attachment['a_original_filename'] != '') {
                $title = escape_html($attachment['a_original_filename']);
            }
            $temp_tpl = do_template('COMCODE_CODE', array('WYSIWYG_SAFE' => $tag == 'attachment' ? NULL : true, 'STYLE' => '', 'TYPE' => $extension, 'CONTENT' => $_embed, 'TITLE' => $title));
            break;
        case 'hyperlink':
            if ($tag == 'attachment') {
                $keep = symbol_tempcode('KEEP');
                $_url = new ocp_tempcode();
                $_url->attach(find_script('attachment') . '?id=' . urlencode($attachment['id']) . $keep->evaluate());
                if (get_option('anti_leech') == '1') {
                    $_url->attach('&for_session=');
                    $_url->attach(symbol_tempcode('SESSION_HASHED'));
                }
            } else {
                $url = $attachment['a_url'];
                if (url_is_local($url)) {
                    $url = get_custom_base_url() . '/' . $url;
                }
                $_url = make_string_tempcode($url);
            }
            $temp_tpl = hyperlink($_url, is_object($attachment['a_description']) ? $attachment['a_description']->evaluate() : $attachment['a_description'] != '' ? $attachment['a_description'] : $attachment['a_original_filename'], true);
            break;
        default:
            if (is_image($attachment['a_original_filename'])) {
                if ($type == 'inline' || $type == 'left_inline' || $type == 'right_inline') {
                    $attachment['mini'] = '1';
                }
                require_code('images');
                ensure_thumbnail($attachment['a_url'], $attachment['a_thumb_url'], 'attachments', 'attachments', intval($attachment['id']), 'a_thumb_url');
                $temp_tpl = do_template('ATTACHMENT_IMG' . (array_key_exists('mini', $attachment) && $attachment['mini'] == '1' ? '_MINI' : ''), map_keys_to_upper($attachment) + array('WYSIWYG_SAFE' => $tag == 'attachment' ? NULL : true));
                if ($type == 'left' || $type == 'left_inline') {
                    $temp_tpl = do_template('ATTACHMENT_LEFT', array('_GUID' => 'aee2a6842d369c8dae212c3478a3a3e9', 'WYSIWYG_SAFE' => $tag == 'attachment' ? NULL : true, 'CONTENT' => $temp_tpl));
                }
                if ($type == 'right' || $type == 'right_inline') {
                    $temp_tpl = do_template('ATTACHMENT_RIGHT', array('_GUID' => '1a7209d67d91db740c86e7a331720195', 'WYSIWYG_SAFE' => $tag == 'attachment' ? NULL : true, 'CONTENT' => $temp_tpl));
                }
                break;
            } elseif ($extension == 'swf') {
                $temp_tpl = do_template('ATTACHMENT_SWF', map_keys_to_upper($attachment) + array('WYSIWYG_SAFE' => $tag == 'attachment' ? NULL : true));
                break;
            } elseif (addon_installed('jwplayer') && ($mime_type == 'video/x-flv' || $mime_type == 'video/mp4' || $mime_type == 'video/webm')) {
                $temp_tpl = do_template('ATTACHMENT_FLV', map_keys_to_upper($attachment) + array('WYSIWYG_SAFE' => $tag == 'attachment' ? NULL : true));
                break;
            } elseif ($mime_type == 'video/quicktime') {
                $temp_tpl = do_template('ATTACHMENT_QT', map_keys_to_upper($attachment) + array('WYSIWYG_SAFE' => $tag == 'attachment' ? NULL : true));
                break;
            } elseif ($mime_type == 'audio/x-pn-realaudio') {
                $temp_tpl = do_template('ATTACHMENT_RM', map_keys_to_upper($attachment) + array('WYSIWYG_SAFE' => $tag == 'attachment' ? NULL : true));
                break;
            } elseif (substr($mime_type, 0, 5) == 'video' || substr($mime_type, 0, 5) == 'audio') {
                $temp_tpl = do_template('ATTACHMENT_MEDIA', map_keys_to_upper($attachment) + array('WYSIWYG_SAFE' => $tag == 'attachment' ? NULL : true));
                break;
            }
            // Continues on, as it's not a media type...
        // Continues on, as it's not a media type...
        case 'download':
            if (is_null($attachment['a_file_size'])) {
                $temp_tpl = do_template('ATTACHMENT_DOWNLOAD_REMOTE', map_keys_to_upper($attachment) + array('WYSIWYG_SAFE' => $tag == 'attachment' ? NULL : true));
            } else {
                $temp_tpl = do_template('ATTACHMENT_DOWNLOAD', map_keys_to_upper($attachment) + array('WYSIWYG_SAFE' => $tag == 'attachment' ? NULL : true));
            }
            break;
    }
    return $temp_tpl;
}
コード例 #24
0
ファイル: recommend.php プロジェクト: erico-deh/ocPortal
 /**
  * The UI for recommending the site.
  *
  * @return tempcode	The UI.
  */
 function gui()
 {
     require_code('form_templates');
     global $EXTRA_HEAD;
     $EXTRA_HEAD->attach('<meta name="robots" content="noindex" />');
     // XHTMLXHTML
     global $NON_CANONICAL_PARAMS;
     $NON_CANONICAL_PARAMS[] = 'page_title';
     $NON_CANONICAL_PARAMS[] = 'subject';
     $NON_CANONICAL_PARAMS[] = 's_message';
     $NON_CANONICAL_PARAMS[] = 'from';
     $NON_CANONICAL_PARAMS[] = 'title';
     $NON_CANONICAL_PARAMS[] = 'ocp';
     $page_title = get_param('page_title', NULL, true);
     $submit_name = !is_null($page_title) ? make_string_tempcode($page_title) : do_lang_tempcode('SEND');
     $post_url = build_url(array('page' => '_SELF', 'type' => 'actual'), '_SELF', NULL, true);
     $hidden = new ocp_tempcode();
     $name = post_param('name', is_guest() ? '' : $GLOBALS['FORUM_DRIVER']->get_username(get_member()));
     $recommender_email_address = post_param('recommender_email_address', $GLOBALS['FORUM_DRIVER']->get_member_email_address(get_member()));
     $fields = new ocp_tempcode();
     $fields->attach(form_input_line(do_lang_tempcode('YOUR_NAME'), '', 'name', $name, true));
     $fields->attach(form_input_email(do_lang_tempcode('YOUR_EMAIL_ADDRESS'), '', 'recommender_email_address', $recommender_email_address, true));
     $already = array();
     foreach ($_POST as $key => $email_address) {
         if (substr($key, 0, 14) != 'email_address_') {
             continue;
         }
         if (get_magic_quotes_gpc()) {
             $email_address = stripslashes($email_address);
         }
         $already[] = $email_address;
     }
     if (is_guest()) {
         $fields->attach(form_input_email(do_lang_tempcode('FRIEND_EMAIL_ADDRESS'), '', 'email_address_0', array_key_exists(0, $already) ? $already[0] : '', true));
     } else {
         $fields->attach(form_input_line_multi(do_lang_tempcode('FRIEND_EMAIL_ADDRESS'), do_lang_tempcode('THEIR_ADDRESS'), 'email_address_', $already, 1, NULL, 'email'));
     }
     if (may_use_invites() && get_forum_type() == 'ocf' && !is_guest()) {
         $invites = get_num_invites(get_member());
         if ($invites > 0) {
             require_lang('ocf');
             $invite = count($_POST) == 0 ? true : post_param_integer('invite', 0) == 1;
             $fields->attach(form_input_tick(do_lang_tempcode('USE_INVITE'), do_lang_tempcode('USE_INVITE_DESCRIPTION', $GLOBALS['FORUM_DRIVER']->is_super_admin(get_member()) ? do_lang('NA_EM') : integer_format($invites)), 'invite', $invite));
         }
     }
     $message = post_param('message', NULL);
     $subject = get_param('subject', do_lang('RECOMMEND_MEMBER_SUBJECT', get_site_name()), true);
     if (is_null($message)) {
         $message = get_param('s_message', '', true);
         if ($message == '') {
             $from = get_param('from', NULL, true);
             if (!is_null($from)) {
                 $resource_title = get_param('title', '', true);
                 if ($resource_title == '') {
                     $downloaded_at_link = http_download_file($from, 3000, false);
                     if (is_string($downloaded_at_link)) {
                         $matches = array();
                         if (preg_match('#\\s*<title[^>]*\\s*>\\s*(.*)\\s*\\s*<\\s*/title\\s*>#mi', $downloaded_at_link, $matches) != 0) {
                             $resource_title = trim(str_replace('&ndash;', '-', str_replace('&mdash;', '-', @html_entity_decode($matches[1], ENT_QUOTES, get_charset()))));
                             $resource_title = preg_replace('#^' . str_replace('#', '\\#', preg_quote(get_site_name())) . ' - #', '', $resource_title);
                             $resource_title = preg_replace('#\\s+[^\\d\\s][^\\d\\s]?[^\\d\\s]?\\s+' . str_replace('#', '\\#', preg_quote(get_site_name())) . '$#i', '', $resource_title);
                         }
                     }
                 }
                 if ($resource_title == '') {
                     $resource_title = do_lang('THIS');
                     // Could not find at all, so say 'this'
                 } else {
                     $subject = get_param('subject', do_lang('RECOMMEND_MEMBER_SUBJECT_SPECIFIC', get_site_name(), $resource_title), true);
                 }
                 $message = do_lang('FOUND_THIS_ON', get_site_name(), comcode_escape($from), comcode_escape($resource_title));
             }
         }
         if (get_param_integer('ocp', 0) == 1) {
             $message = do_lang('RECOMMEND_OCPORTAL');
         }
     }
     $text = is_null($page_title) ? do_lang_tempcode('RECOMMEND_SITE_TEXT') : new ocp_tempcode();
     if (!is_null(get_param('from', NULL, true))) {
         if (is_null($page_title)) {
             $title = get_page_title('RECOMMEND_LINK');
         } else {
             $title = get_page_title($page_title, false);
         }
         $submit_name = do_lang_tempcode('SEND');
         $text = do_lang_tempcode('RECOMMEND_AUTO_TEXT', get_site_name());
         $need_message = true;
     } else {
         if (is_null($page_title)) {
             $title = get_page_title('_RECOMMEND_SITE', true, array(escape_html(get_site_name())));
         } else {
             $title = get_page_title($page_title, false);
         }
         $hidden->attach(form_input_hidden('wrap_message', '1'));
         $need_message = false;
     }
     //add an upload CSV contacts file field
     $_help_url = build_url(array('page' => 'recommend_help'), get_page_zone('recommend_help'));
     $help_url = $_help_url->evaluate();
     if (get_value('disable_csv_recommend') !== '1' && !is_guest()) {
         $fields->attach(form_input_upload(do_lang_tempcode('ALT_FIELD', do_lang_tempcode('UPLOAD')), do_lang_tempcode('DESCRIPTION_UPLOAD_CSV_FILE', escape_html($help_url)), 'upload', false, NULL, NULL, false));
     }
     handle_max_file_size($hidden);
     $fields->attach(form_input_line(do_lang_tempcode('SUBJECT'), '', 'subject', $subject, true));
     $fields->attach(form_input_text_comcode(do_lang_tempcode('MESSAGE'), do_lang_tempcode('RECOMMEND_SUP_MESSAGE'), 'message', $message, $need_message));
     if (addon_installed('captcha')) {
         require_code('captcha');
         if (use_captcha()) {
             $fields->attach(form_input_captcha());
             $text->attach(' ');
             $text->attach(do_lang_tempcode('FORM_TIME_SECURITY'));
         }
     }
     $hidden->attach(form_input_hidden('comcode__message', '1'));
     if (get_value('disable_csv_recommend') !== '1' && !is_guest()) {
         $javascript = 'standardAlternateFields(\'upload\',\'email_address_0\');';
     } else {
         $javascript = '';
     }
     $javascript .= function_exists('captcha_ajax_check') ? captcha_ajax_check() : '';
     return do_template('FORM_SCREEN', array('_GUID' => '08a538ca8d78597b0417f464758a59fd', 'JAVASCRIPT' => $javascript, 'SKIP_VALIDATION' => true, 'TITLE' => $title, 'HIDDEN' => $hidden, 'FIELDS' => $fields, 'URL' => $post_url, 'SUBMIT_NAME' => $submit_name, 'TEXT' => $text));
 }
コード例 #25
0
ファイル: galleries2.php プロジェクト: erico-deh/ocPortal
/**
 * Create a video thumbnail.
 *
 * @param  URLPATH		Video to get thumbail from (must be local)
 * @param  ?PATH			Where to save to (NULL: decide for ourselves)
 * @return URLPATH		Thumbnail, only valid if expected_output_path was passed as NULL (blank: could not generate)
 */
function create_video_thumb($src_url, $expected_output_path = NULL)
{
    // Audio ones should have automatic thumbnails
    require_code('mime_types');
    $file_ext = get_file_extension($src_url);
    $input_mime_type = get_mime_type($file_ext);
    if (preg_match('#audio\\/#i', $input_mime_type) != 0) {
        $ret = find_theme_image('audio_thumb', true);
        if ($ret != '') {
            if (!is_null($expected_output_path)) {
                require_code('files');
                $_expected_output_path = fopen($expected_output_path, 'wb');
                http_download_file($ret, NULL, true, false, 'ocPortal', NULL, NULL, NULL, NULL, NULL, $_expected_output_path);
                fclose($_expected_output_path);
            }
        }
        return $ret;
    }
    // Try one of the hooks for video types
    $ve_hooks = find_all_hooks('systems', 'video_embed');
    foreach (array_keys($ve_hooks) as $ve_hook) {
        require_code('hooks/systems/video_embed/' . $ve_hook);
        $ve_ob = object_factory('Hook_video_embed_' . $ve_hook);
        $thumbnail = $ve_ob->get_video_thumbnail($src_url);
        if (!is_null($thumbnail)) {
            return $thumbnail;
        }
    }
    // Ok, gonna try hard using what FFMPEG techniques we can...
    if (substr($src_url, 0, strlen(get_custom_base_url() . '/')) == get_custom_base_url() . '/') {
        $src_url = substr($src_url, strlen(get_custom_base_url() . '/'));
    }
    if (!url_is_local($src_url)) {
        return '';
    }
    $src_file = get_custom_file_base() . '/' . rawurldecode($src_url);
    $src_file = preg_replace('#(\\\\|/)#', DIRECTORY_SEPARATOR, $src_file);
    if (class_exists('ffmpeg_movie')) {
        $filename = 'thumb_' . md5(uniqid('', true)) . '1.jpg';
        if (is_null($expected_output_path)) {
            $expected_output_path = get_custom_file_base() . '/uploads/galleries/' . $filename;
        }
        if (file_exists($expected_output_path)) {
            return 'uploads/galleries/' . rawurlencode(basename($expected_output_path));
        }
        $movie = @new ffmpeg_movie($src_file, false);
        if ($movie !== false) {
            if ($movie->getFrameCount() == 0) {
                return '';
            }
            $frame = $movie->getFrame(min($movie->getFrameCount(), 25));
            if (method_exists($frame, 'toGDImage')) {
                $gd_img = $frame->toGDImage();
                @imagejpeg($gd_img, $expected_output_path);
            } else {
                $frame->save($expected_output_path);
                // New-style
            }
            if (file_exists($expected_output_path)) {
                require_code('images');
                if (get_option('is_on_gd') == '1' && function_exists('imagecreatefromstring')) {
                    convert_image($expected_output_path, $expected_output_path, -1, -1, intval(get_option('thumb_width')), true, NULL, true);
                }
                return 'uploads/galleries/' . rawurlencode(basename($expected_output_path));
            }
        }
    }
    $ffmpeg_path = get_option('ffmpeg_path');
    if ($ffmpeg_path != '' && strpos(@ini_get('disable_functions'), 'shell_exec') === false) {
        $filename = 'thumb_' . md5(uniqid(strval(post_param_integer('thumbnail_auto_position', 1)), true)) . '%d.jpg';
        $dest_file = get_custom_file_base() . '/uploads/galleries/' . $filename;
        if (is_null($expected_output_path)) {
            $expected_output_path = str_replace('%d', '1', $dest_file);
        }
        if (file_exists($dest_file) && is_null(post_param_integer('thumbnail_auto_position', NULL))) {
            return 'uploads/galleries/' . rawurlencode(basename($expected_output_path));
        }
        @unlink($dest_file);
        // So "if (@filesize($expected_output_path)) break;" will definitely fail if error
        $dest_file = preg_replace('#(\\\\|/)#', DIRECTORY_SEPARATOR, $dest_file);
        $at = display_seconds_period(post_param_integer('thumbnail_auto_position', 1));
        if (strlen($at) == 5) {
            $at = '00:' . $at;
        }
        $shell_command = '"' . $ffmpeg_path . 'ffmpeg" -i ' . @escapeshellarg($src_file) . ' -an -ss ' . $at . ' -r 1 -vframes 1 -y ' . @escapeshellarg($dest_file);
        $shell_commands = array($shell_command, $shell_command . ' -map 0.0:0.0', $shell_command . ' -map 0.1:0.0');
        foreach ($shell_commands as $shell_command) {
            shell_exec($shell_command);
            if (@filesize($expected_output_path)) {
                break;
            }
        }
        if (file_exists(str_replace('%d', '1', $dest_file))) {
            require_code('images');
            if (get_option('is_on_gd') == '1' && function_exists('imagecreatefromstring')) {
                convert_image(str_replace('%d', '1', $dest_file), $expected_output_path, -1, -1, intval(get_option('thumb_width')), true, NULL, true);
            } else {
                copy(str_replace('%d', '1', $dest_file), $expected_output_path);
                fix_permissions($expected_output_path);
                sync_file($expected_output_path);
            }
            return 'uploads/galleries/' . rawurlencode(basename($expected_output_path));
        }
    }
    return '';
}
コード例 #26
0
ファイル: downloads2.php プロジェクト: erico-deh/ocPortal
/**
 * Create a data-mash from the file at a URL. This is data useful for the search engine.
 *
 * @param  URLPATH			The URL to make a data-mash of, or a filename if $data isn't blank
 * @param  ?string			Data (NULL: use URL)
 * @param  ?ID_TEXT			File extension (NULL: get from URL)
 * @param  boolean			Whether a direct file path was given instead of a URL
 * @return LONG_TEXT			The data-mash
 */
function create_data_mash($url, $data = NULL, $extension = NULL, $direct_path = false)
{
    if (function_exists('set_time_limit')) {
        @set_time_limit(300);
    }
    if (get_value('no_dload_search_index') === '1') {
        return '';
    }
    if (running_script('stress_test_loader')) {
        return '';
    }
    if (function_exists('memory_get_usage') && ini_get('memory_usage') == '8M') {
        return '';
    }
    // Some cowardice... don't want to tempt fate
    if (is_null($extension)) {
        $extension = get_file_extension($url);
    }
    $tmp_file = NULL;
    if (is_null($data)) {
        if ($direct_path || url_is_local($url)) {
            $actual_path = $direct_path ? $url : get_custom_file_base() . '/' . rawurldecode($url);
            if (file_exists($actual_path)) {
                switch ($extension) {
                    case 'zip':
                    case 'odt':
                    case 'odp':
                    case 'docx':
                    case 'tar':
                    case 'gz':
                        if (filesize($actual_path) > 1024 * 1024 * 3) {
                            return '';
                        }
                        break;
                }
                $tmp_file = $actual_path;
                if (filesize($actual_path) > 1024 * 1024 * 3) {
                    $myfile = fopen($actual_path, 'rb');
                    $data = '';
                    for ($i = 0; $i < 384; $i++) {
                        $data .= fread($myfile, 8192);
                    }
                    fclose($myfile);
                } else {
                    $data = file_get_contents($actual_path);
                }
            } else {
                $data = '';
            }
        } else {
            switch ($extension) {
                case 'txt':
                case '1st':
                case 'rtf':
                case 'pdf':
                case 'htm':
                case 'html':
                case 'xml':
                case 'doc':
                case 'xls':
                    break;
                    // Continue through to download good stuff
                // Continue through to download good stuff
                default:
                    return '';
                    // Don't download, it's not worth it
                    break;
            }
            $data = http_download_file($url, 3 * 1024 * 1024, false);
            // 3MB is enough
            if (is_null($data)) {
                return '';
            }
        }
    }
    $mash = '';
    switch ($extension) {
        case 'zip':
        case 'odt':
        case 'odp':
        case 'docx':
            require_code('m_zip');
            $tmp_file = ocp_tempnam('dcdm_');
            $myfile2 = fopen($tmp_file, 'wb');
            fwrite($myfile2, $data);
            fclose($myfile2);
            $myfile_zip = @zip_open($tmp_file);
            if (!is_integer($myfile_zip)) {
                while (($entry = @zip_read($myfile_zip)) !== false) {
                    $entry_name = @zip_entry_name($entry);
                    $mash .= ' ' . $entry_name;
                    if (substr($entry_name, -1) != '/') {
                        $_entry = @zip_entry_open($myfile_zip, $entry);
                        if ($_entry !== false) {
                            $file_data = '';
                            while (true) {
                                $it = @zip_entry_read($entry, 1024);
                                if ($it === false || $it == '') {
                                    break;
                                }
                                $file_data .= $it;
                                if (strlen($file_data) >= 3 * 1024 * 1024) {
                                    break;
                                }
                                // 3MB is enough
                            }
                            @zip_entry_close($entry);
                            $mash .= ' ' . create_data_mash($entry_name, $file_data);
                            if (strlen($mash) >= 3 * 1024 * 1024) {
                                break;
                            }
                            // 3MB is enough
                        }
                    }
                }
                @zip_close($myfile_zip);
            }
            @unlink($tmp_file);
            break;
        case 'tar':
            require_code('tar');
            $tmp_file = ocp_tempnam('dcdm_');
            $myfile = fopen($tmp_file, 'wb');
            fwrite($myfile, $data);
            fclose($myfile);
            $myfile_tar = tar_open($tmp_file, 'rb');
            if ($myfile_tar !== false) {
                $directory = tar_get_directory($myfile_tar);
                foreach ($directory as $entry) {
                    $entry_name = $entry['path'];
                    $mash .= ' ' . $entry_name;
                    if ($entry['size'] >= 3 * 1024 * 1024) {
                        continue;
                    }
                    // 3MB is enough
                    $_entrya = tar_get_file($myfile_tar, $entry['path']);
                    if (!is_null($_entrya)) {
                        $mash .= ' ' . create_data_mash($entry_name, $_entrya['data']);
                        if (strlen($mash) >= 3 * 1024 * 1024) {
                            break;
                        }
                        // 3MB is enough
                    }
                }
                tar_close($myfile_tar);
            }
            @unlink($tmp_file);
            break;
        case 'gz':
            if (function_exists('gzopen')) {
                if (function_exists('gzeof')) {
                    if (function_exists('gzread')) {
                        $tmp_file = ocp_tempnam('dcdm_');
                        $myfile = fopen($tmp_file, 'wb');
                        fwrite($myfile, $data);
                        fclose($myfile);
                        $myfile = gzopen($tmp_file, 'rb');
                        if ($myfile !== false) {
                            $file_data = '';
                            while (!gzeof($myfile)) {
                                $it = gzread($myfile, 1024);
                                $file_data .= $it;
                                if (strlen($file_data) >= 3 * 1024 * 1024) {
                                    break;
                                }
                                // 3MB is enough
                            }
                            $mash = ' ' . create_data_mash(preg_replace('#\\.gz#i', '', $url), $file_data);
                        }
                        @unlink($tmp_file);
                    }
                }
            }
            break;
        case 'txt':
        case '1st':
            $mash .= $data;
            break;
        case 'rtf':
            $len = strlen($data);
            $skipping_section_depth = 0;
            $escape = false;
            for ($i = 0; $i < $len; $i++) {
                $byte = $data[$i];
                if (!$escape && $byte == "\\") {
                    $escape = true;
                } elseif (!$escape && $byte == '{') {
                    if ($skipping_section_depth != 0) {
                        $skipping_section_depth++;
                    }
                } elseif (!$escape && $byte == '}') {
                    if ($skipping_section_depth != 0) {
                        $skipping_section_depth--;
                    }
                } elseif ($escape && $byte != '{' && $byte != "\\" && $byte != '}') {
                    $end_pos_1 = strpos($data, "\\", $i + 1);
                    if ($end_pos_1 === false) {
                        $end_pos_1 = $len;
                    }
                    $end_pos_2 = strpos($data, chr(10), $i + 1);
                    if ($end_pos_2 === false) {
                        $end_pos_2 = $len;
                    }
                    $end_pos_3 = strpos($data, ' ', $i + 1);
                    if ($end_pos_3 === false) {
                        $end_pos_3 = $len;
                    }
                    $end_pos_4 = strpos($data, "\t", $i + 1);
                    if ($end_pos_4 === false) {
                        $end_pos_4 = $len;
                    }
                    $end_pos_5 = strpos($data, '{', $i + 1);
                    if ($end_pos_5 === false) {
                        $end_pos_5 = $len;
                    }
                    $end_pos_6 = strpos($data, '}', $i + 1);
                    if ($end_pos_6 === false) {
                        $end_pos_6 = $len;
                    }
                    $end_pos = min($end_pos_1, $end_pos_2, $end_pos_3, $end_pos_4, $end_pos_5, $end_pos_6);
                    $tag = substr($data, $i, $end_pos - $i);
                    $tag = preg_replace('#[\\-0-9]*#', '', $tag);
                    if ($skipping_section_depth == 0 && ($tag == 'pgdsc' || $tag == 'comment' || $tag == 'object' || $tag == 'pict' || $tag == 'stylesheet' || $tag == 'fonttbl')) {
                        $skipping_section_depth = 1;
                    }
                    if ($tag == 'par') {
                        $mash .= chr(10);
                    }
                    $i = $end_pos - 1;
                    $escape = false;
                } elseif ($skipping_section_depth == 0) {
                    if ($byte != chr(13) && $byte != chr(10)) {
                        $mash .= $byte;
                    }
                    $escape = false;
                } else {
                    $escape = false;
                }
            }
            break;
        case 'pdf':
            if (str_replace(array('on', 'true', 'yes'), array('1', '1', '1'), strtolower(ini_get('safe_mode'))) != '1' && strpos(@ini_get('disable_functions'), 'shell_exec') === false && !is_null($tmp_file)) {
                $enc = get_charset() == 'utf-8' ? ' -enc UTF-8' : '';
                $path = 'pdftohtml -i -noframes -stdout -hidden' . $enc . ' -q -xml ' . @escapeshellarg($tmp_file);
                if (strpos(strtolower(PHP_OS), 'win') !== false) {
                    if (file_exists(get_file_base() . '/data_custom/pdftohtml.exe')) {
                        $path = '"' . get_file_base() . DIRECTORY_SEPARATOR . 'data_custom' . DIRECTORY_SEPARATOR . '"' . $path;
                    }
                }
                $tmp_file_2 = ocp_tempnam('pdfxml_');
                @shell_exec($path . ' > ' . $tmp_file_2);
                $mash = create_data_mash($tmp_file_2, NULL, 'xml', true);
                @unlink($tmp_file_2);
            }
            break;
        case 'htm':
        case 'html':
            $head_patterns = array('#<\\s*script.*<\\s*/\\s*script\\s*>#misU', '#<\\s*link[^<>]*>#misU', '#<\\s*style.*<\\s*/\\s*style\\s*>#misU');
            foreach ($head_patterns as $pattern) {
                $data = preg_replace($pattern, '', $data);
            }
        case 'xml':
            $mash = str_replace('&apos;', '\'', str_replace(' false ', ' ', str_replace(' true ', ' ', @html_entity_decode(preg_replace('#\\<[^\\<\\>]*\\>#', ' ', $data), ENT_QUOTES, get_charset()))));
            $mash = preg_replace('#Error : Bad \\w+#', '', $mash);
            break;
        case 'xls':
        case 'doc':
        case 'ppt':
        case 'hlp':
            //		default: // Binary formats are complex to parse, but whatsmore, as textual tagging isn't used, extraction can be done automatically as all identified text is good.
            $data = str_replace("", '', $data);
            // Strip out interleaved nulls because they are used in wide-chars, obscuring the data
            $mash = '';
            $needs_delimiter_next = false;
            $in_portion = false;
            $min_length = 10;
            if ($extension == 'xls') {
                $min_length = 4;
            }
            for ($i = 0; $i < strlen($data); $i++) {
                $ch = $data[$i];
                $chx = 1;
                $next_ok = _is_valid_data_mash_char($ch);
                if ($next_ok && !$in_portion) {
                    $x = $ch;
                    for ($j = $i + 1; $j < strlen($data); $j++) {
                        $_ch = $data[$j];
                        $_next_ok = _is_valid_data_mash_char($_ch);
                        if ($_next_ok) {
                            $x .= $_ch;
                            $chx++;
                        } else {
                            break;
                        }
                    }
                    if (strlen($x) < $min_length || $x == strtoupper($x) || $x == 'Microsoft Word Document' || $x == 'WordDocument' || $x == 'SummaryInformation' || $x == 'DocumentSummaryInformation') {
                        $i = $j;
                        continue;
                    }
                }
                if ($next_ok && $in_portion) {
                    $mash .= $ch;
                } elseif ($next_ok && $chx >= $min_length) {
                    if ($needs_delimiter_next) {
                        $mash .= ' ';
                        $needs_delimiter_next = false;
                    }
                    $mash .= $ch;
                    $in_portion = true;
                } else {
                    if ($in_portion) {
                        $needs_delimiter_next = true;
                        $in_portion = false;
                    }
                }
            }
            break;
    }
    if (strlen($mash) > 1024 * 1024 * 3) {
        $mash = substr($mash, 0, 1024 * 1024 * 3);
    }
    $mash = preg_replace('# +#', ' ', preg_replace('#[^\\w\\d-\\-\']#', ' ', $mash));
    if (strlen($mash) > intval(1024 * 1024 * 1 * 0.4)) {
        $mash = substr($mash, 0, intval(1024 * 1024 * 0.4));
    }
    return $mash;
}
コード例 #27
0
 /**
  * Standard aed_module edit actualiser.
  *
  * @param  ID_TEXT		The entry being edited
  * @return ?tempcode		Confirm message (NULL: continue)
  */
 function edit_actualisation($id)
 {
     $id = intval($id);
     $name = post_param('name', '');
     $cure = post_param('cure', '');
     $cure_price = post_param_integer('cure_price', 0);
     $immunization = post_param('immunization', '');
     $immunization_price = post_param_integer('immunization_price', 0);
     $spread_rate = post_param_integer('spread_rate', 12);
     $points_per_spread = post_param_integer('points_per_spread', 10);
     $enabled = post_param_integer('enabled', 0);
     require_code('uploads');
     $urls = get_url('url', 'image', 'uploads/diseases_addon', 0, OCP_UPLOAD_IMAGE, false, '', '');
     if ($urls[0] == '') {
         warn_exit(do_lang_tempcode('IMPROPERLY_FILLED_IN_UPLOAD'));
     }
     if (substr($urls[0], 0, 8) != 'uploads/' && is_null(http_download_file($urls[0], 0, false)) && !is_null($GLOBALS['HTTP_MESSAGE_B'])) {
         attach_message($GLOBALS['HTTP_MESSAGE_B'], 'warn');
     }
     $url = $urls[0];
     $GLOBALS['SITE_DB']->query_update('diseases', array('name' => $name, 'image' => $url, 'cure' => $cure, 'cure_price' => $cure_price, 'immunisation' => $immunization, 'immunisation_price' => $immunization_price, 'spread_rate' => $spread_rate, 'points_per_spread' => $points_per_spread, 'enabled' => $enabled), array('id' => $id), '', 1);
     return NULL;
 }
コード例 #28
0
ファイル: rss2.php プロジェクト: erico-deh/ocPortal
/**
 * Get enclosure details from a URL, as efficiently as possible.
 *
 * @param  URLPATH		The (possibly short) URL to get details for
 * @param  URLPATH		The full URL to get details for
 * @return array			A pair: the length of the data, the mime type
 */
function get_enclosure_details($url, $enclosure_url)
{
    $enclosure_length = '0';
    if (url_is_local($url) && file_exists(get_custom_file_base() . '/' . rawurldecode($url))) {
        $enclosure_length = strval(@filesize(get_custom_file_base() . '/' . rawurldecode($url)));
        require_code('mime_types');
        $enclosure_type = get_mime_type(get_file_extension($url));
    } else {
        http_download_file($enclosure_url, 0, false);
        $enclosure_length = strval($GLOBALS['HTTP_DOWNLOAD_SIZE']);
        if (is_null($enclosure_length)) {
            $enclosure_length = strval(strlen(http_download_file($enclosure_url)));
        }
        $enclosure_type = $GLOBALS['HTTP_DOWNLOAD_MIME_TYPE'];
    }
    return array($enclosure_length, $enclosure_type);
}
コード例 #29
0
ファイル: secpay.php プロジェクト: erico-deh/ocPortal
 /**
  * Handle IPN's. The function may produce output, which would be returned to the Payment Gateway. The function may do transaction verification.
  *
  * @return array	A long tuple of collected data.
  */
 function handle_transaction()
 {
     /*$myfile=fopen(get_file_base().'/data_custom/ecommerce.log','at');
     		fwrite($myfile,serialize($_POST));
     		fclose($myfile);*/
     $txn_id = post_param('trans_id');
     if (substr($txn_id, 0, 7) == 'subscr_') {
         $subscription = true;
         $txn_id = substr($txn_id, 7);
     } else {
         $subscription = false;
     }
     $transaction_rows = $GLOBALS['SITE_DB']->query_select('trans_expecting', array('*'), array('id' => $txn_id), '', 1);
     if (!array_key_exists(0, $transaction_rows)) {
         warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
     }
     $transaction_row = $transaction_rows[0];
     $member_id = $transaction_row['e_member_id'];
     $item_name = $subscription ? '' : $transaction_row['e_item_name'];
     $purchase_id = $transaction_row['e_purchase_id'];
     $code = post_param('code');
     $success = $code == 'A';
     $message = post_param('message');
     if ($message == '') {
         switch ($code) {
             case 'P:A':
                 $message = do_lang('PGE_A');
                 break;
             case 'P:X':
                 $message = do_lang('PGE_X');
                 break;
             case 'P:P':
                 $message = do_lang('PGE_P');
                 break;
             case 'P:S':
                 $message = do_lang('PGE_S');
                 break;
             case 'P:E':
                 $message = do_lang('PGE_E');
                 break;
             case 'P:I':
                 $message = do_lang('PGE_I');
                 break;
             case 'P:C':
                 $message = do_lang('PGE_C');
                 break;
             case 'P:T':
                 $message = do_lang('PGE_T');
                 break;
             case 'P:N':
                 $message = do_lang('PGE_N');
                 break;
             case 'P:M':
                 $message = do_lang('PGE_M');
                 break;
             case 'P:B':
                 $message = do_lang('PGE_B');
                 break;
             case 'P:D':
                 $message = do_lang('PGE_D');
                 break;
             case 'P:V':
                 $message = do_lang('PGE_V');
                 break;
             case 'P:R':
                 $message = do_lang('PGE_R');
                 break;
             case 'P:#':
                 $message = do_lang('PGE_HASH');
                 break;
             case 'C':
                 $message = do_lang('PGE_COMM');
                 break;
             default:
                 $message = do_lang('UNKNOWN');
         }
     }
     $payment_status = $success ? 'Completed' : 'Failed';
     $reason_code = '';
     $pending_reason = '';
     $memo = '';
     $mc_gross = post_param('amount');
     $mc_currency = post_param('currency', '');
     // May be blank for subscription
     $email = $GLOBALS['FORUM_DRIVER']->get_member_email_address($member_id);
     // Validate
     $hash = post_param('hash');
     if ($subscription) {
         $my_hash = md5('trans_id=' . $txn_id . '&' . 'req_cv2=true' . '&' . get_option('ipn_digest'));
     } else {
         $repeat = $this->_translate_subscription_details($transaction_row['e_length'], $transaction_row['e_length_units']);
         $my_hash = md5('trans_id=' . $txn_id . '&' . 'req_cv2=true' . '&' . 'repeat=' . $repeat . '&' . get_option('ipn_digest'));
     }
     if ($hash != $my_hash) {
         my_exit(do_lang('IPN_UNVERIFIED'));
     }
     if ($success) {
         require_code('notifications');
         dispatch_notification('payment_received', NULL, do_lang('PAYMENT_RECEIVED_SUBJECT', $txn_id, NULL, NULL, get_lang($member_id)), do_lang('PAYMENT_RECEIVED_BODY', float_format(floatval($mc_gross)), $mc_currency, get_site_name(), get_lang($member_id)), array($member_id), A_FROM_SYSTEM_PRIVILEGED);
     }
     // Subscription stuff
     if (get_param_integer('subc', 0) == 1) {
         if (!$success) {
             $payment_status = 'SCancelled';
         }
     }
     if ($success) {
         $_url = build_url(array('page' => 'purchase', 'type' => 'finish', 'product' => get_param('product', NULL)), get_module_zone('purchase'));
     } else {
         $_url = build_url(array('page' => 'purchase', 'type' => 'finish', 'cancel' => 1, 'message' => do_lang_tempcode('DECLINED_MESSAGE', $message)), get_module_zone('purchase'));
     }
     $url = $_url->evaluate();
     echo http_download_file($url);
     if (addon_installed('shopping')) {
         $this->store_shipping_address($purchase_id);
     }
     return array($purchase_id, $item_name, $payment_status, $reason_code, $pending_reason, $memo, $mc_gross, $mc_currency, $txn_id, '');
 }
コード例 #30
0
function transcode_remaining_locations()
{
    //if (file_exists(get_file_base().'/data_custom/locations/worldcitiespop.csv')) _worldcities_remaining_locations();
    $errored = 0;
    $type = 'yahoo';
    // Either google or yahoo or bing or mapquest
    $from = 0;
    do {
        $unknown = $GLOBALS['SITE_DB']->query('SELECT * FROM ' . get_table_prefix() . 'locations WHERE l_latitude IS NULL AND id>' . strval($from) . ' ORDER BY id', 100);
        if ($type == 'mapquest') {
            $url = 'http://www.mapquestapi.com/geocoding/v1/batch?key=Fmjtd%7Cluu22h0t2d%2C8l%3Do5-h0r2q&callback=renderBatch&outFormat=xml';
            foreach ($unknown as $i => $location) {
                $lstring = '{city="' . remove_accents($location['l_place']) . '", country="' . $location['l_country'] . '"}';
                $url .= '&location=' . urlencode($lstring);
                $unknown[$i]['l_string'] = $lstring;
                $from = $location['id'];
            }
            $result = http_download_file($url);
            $matches = array();
            if (strpos($result, '<lat>') !== false) {
                foreach ($unknown as $i => $location) {
                    $matches = array();
                    if (preg_match('#<location>' . str_replace('#', '\\#', preg_quote($location['l_string'])) . '</location>.*<geocodeQualityCode>(.*)</geocodeQualityCode>.*<lat>([\\-\\d\\.]+)</lat>\\s*<lng>([\\-\\d\\.]+)</lng>#sU', $result, $matches) != 0) {
                        if ($matches[1] == 'A5XAX' || $matches[1] == 'A5XBX') {
                            $GLOBALS['SITE_DB']->query_update('locations', array('l_latitude' => floatval($matches[2]), 'l_longitude' => floatval($matches[3])), array('id' => $location['id']), '', 1);
                        }
                    }
                }
                $errored = 0;
            } else {
                $errored++;
            }
            if ($errored == 10) {
                exit($result);
            }
        } else {
            foreach ($unknown as $location) {
                // Web service to get remaining latitude/longitude
                $lstring = $location['l_place'] . ', ' . $location['l_parent_3'] . ', ' . $location['l_parent_2'] . ', ' . $location['l_parent_1'] . ', ' . $location['l_country'];
                if ($type == 'bing') {
                    $url = 'http://dev.virtualearth.net/REST/v1/Locations?query=' . urlencode($lstring) . '&o=xml&key=AvmgsVWtIoJeCnZXdDnu3dQ7izV9oOowHCNDwbN4R1RPA9OXjfsQX1Cr9HSrsY4j';
                } elseif ($type == 'yahoo') {
                    $url = 'http://where.yahooapis.com/geocode?q=' . urlencode($lstring) . '&appid=dj0yJmk9N0x3TTdPaDNvdElCJmQ9WVdrOWFGWjVOa3hzTldFbWNHbzlNVFU0TXpBMU9EWTJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD1mNg--';
                } elseif ($type == 'google') {
                    $url = 'http://maps.googleapis.com/maps/api/geocode/xml?address=' . urlencode($lstring) . '&sensor=false';
                } else {
                    exit('unknown type');
                }
                $result = http_download_file($url);
                $matches = array();
                if ($type == 'bing' && preg_match('#<Latitude>([\\-\\d\\.]+)</Latitude>\\s*<Longitude>([\\-\\d\\.]+)</Longitude>#', $result, $matches) != 0 || $type == 'google' && preg_match('#<lat>([\\-\\d\\.]+)</lat>\\s*<lng>([\\-\\d\\.]+)</lng>#', $result, $matches) != 0 || $type == 'yahoo' && preg_match('#<latitude>([\\-\\d\\.]+)</latitude>\\s*<longitude>([\\-\\d\\.]+)</longitude>#', $result, $matches) != 0) {
                    $GLOBALS['SITE_DB']->query_update('locations', array('l_latitude' => floatval($matches[1]), 'l_longitude' => floatval($matches[2])), array('id' => $location['id']), '', 1);
                    $errored = 0;
                } elseif (preg_match('#(ZERO_RESULTS|<StatusCode>200</StatusCode>)#', $result) == 0) {
                    /*probably hit an API limit, or connection problem*/
                    $errored++;
                }
                if ($errored == 10) {
                    exit($result);
                }
                $from = $location['id'];
            }
        }
    } while (count($unknown) != 0);
}