function get_directory_contents($directory, $folders_only = false, $files_only = false)
{
    $dir = opendir($directory);
    // Get a list of all the folders and files in the directory
    while ($temp = readdir($dir)) {
        if ($temp != "." && $temp != "..") {
            if (is_dir($directory . "/" . $temp)) {
                if ($files_only == false) {
                    $children = get_directory_contents($directory . "/" . $temp, $folders_only);
                    $data[] = array('id' => str_replace(DIRECTORY, "", $directory . "/" . $temp), 'text' => $temp, 'url' => str_replace(DIRECTORY, "", $directory . "/" . $temp), 'children' => $children ? $children : array());
                }
            } else {
                if ($folders_only == false) {
                    // Exclude backup files from showing up in the list
                    if (stristr($temp, ".bak")) {
                        continue;
                    }
                    $data[] = array('id' => str_replace(DIRECTORY, "", $directory . "/" . $temp), 'text' => $temp, 'url' => str_replace(DIRECTORY, "", $directory . "/" . $temp));
                }
            }
        }
    }
    closedir($dir);
    return $data;
}
Example #2
0
 function testValidCode()
 {
     if (function_exists('set_time_limit')) {
         @set_time_limit(0);
     }
     require_code('files2');
     $php_path = find_php_path();
     $contents = get_directory_contents(get_file_base());
     foreach ($contents as $c) {
         if (substr($c, -4) == '.php' && basename($c) != 'errorlog.php' && basename($c) != 'phpstub.php' && basename($c) != 'permissioncheckslog.php') {
             $message = shell_exec($php_path . ' -l ' . $c);
             $this->assertTrue(strpos($message, 'No syntax errors detected') !== false, $message . ' (' . $c . ')');
         }
     }
 }
Example #3
0
function get_files()
{
    // get the dirs of all files
    $linkdocs = get_directory_contents("res/links/docs");
    $linkfiles = get_directory_contents("res/links/files");
    $links = array('files' => $linkfiles, 'docs' => $linkdocs);
    $tooldocs = get_directory_contents("res/tools/docs");
    $toolfiles = get_directory_contents("res/tools/files");
    $tools = array('files' => $toolfiles, 'docs' => $tooldocs);
    $articledocs = get_directory_contents("res/articles/docs");
    $articlefiles = get_directory_contents("res/articles/files");
    $articles = array('files' => $articlefiles, 'docs' => $articledocs);
    $dirs = array('links' => $links, 'tools' => $tools, 'articles' => $articles);
    $output = array('links' => array(), 'tools' => array(), 'articles' => array());
    //open and parse all files
    foreach ($dirs as $k => $v) {
        $resourcebundle = array();
        foreach ($v as $key => $value) {
            foreach ($value as $filename) {
                $filecontents = file_get_contents($filename);
                $arraykey = explode(".", array_pop(explode("/", $filename)))[0];
                if ($key == "docs") {
                    $split = explode("#?#", $filecontents);
                    $title = $split[0];
                    $description = $split[1];
                    $resourcebundle[$arraykey]["title"] = $title;
                    $resourcebundle[$arraykey]["description"] = $description;
                    $resourcebundle[$arraykey]["docspath"] = $filename;
                } elseif ($key == "files") {
                    $url = $filename;
                    $fl = explode(".", $filename);
                    $ext = array_pop($fl);
                    $id = array_pop(explode("/", implode($fl)));
                    if ($k == "links") {
                        $url = $filecontents;
                    }
                    $resourcebundle[$arraykey]["url"] = $url;
                    $resourcebundle[$arraykey]["ext"] = $ext;
                    $resourcebundle[$arraykey]["filespath"] = $filename;
                    $resourcebundle[$arraykey]["id"] = $id;
                }
            }
        }
        $output[$k] = $resourcebundle;
    }
    return $output;
}
Example #4
0
 /**
  * Standard modular run function for snippet hooks. Generates XHTML to insert into a page using AJAX.
  *
  * @return tempcode  The snippet
  */
 function run()
 {
     if (function_exists('set_time_limit')) {
         @set_time_limit(0);
     }
     require_code('files');
     require_code('files2');
     $size = 0;
     $max_size = get_param_integer('max_size') * 1024 * 1024;
     $files = get_directory_contents(get_custom_file_base());
     foreach ($files as $file) {
         $filesize = filesize(get_custom_file_base() . '/' . $file);
         if ($filesize < $max_size) {
             $size += $filesize;
         }
     }
     return make_string_tempcode(clean_file_size($size));
 }
Example #5
0
 /**
  * Standard function to create the standardised category tree
  *
  * @param  ID_TEXT		Notification code
  * @param  ?ID_TEXT		The ID of where we're looking under (NULL: N/A)
  * @return array 			Tree structure
  */
 function create_category_tree($notification_code, $id)
 {
     require_code('files2');
     $path = get_custom_file_base() . '/uploads/filedump';
     if (!is_null($id)) {
         $path .= '/' . $id;
     }
     $files = get_directory_contents($path, '', false, false);
     if (count($files) > 30) {
         return array();
     }
     // Too many, so don't show
     $pagelinks = array();
     foreach ($files as $file) {
         if (is_dir($path . '/' . $file)) {
             $pagelinks[] = array('id' => ($id == '' ? '' : $id . '/') . $file, 'title' => $file, 'child_count' => count($this->create_category_tree($notification_code, ($id == '' ? '' : $id . '/') . $file)));
         }
     }
     return $pagelinks;
 }
Example #6
0
 /**
  * Standard modular run function.
  *
  * @return tempcode	The result of execution.
  */
 function run()
 {
     if (!addon_installed('filedump')) {
         return new ocp_tempcode();
     }
     if (!file_exists(get_custom_file_base() . '/uploads/filedump')) {
         return new ocp_tempcode();
     }
     require_lang('filedump');
     require_code('files2');
     $bits = new ocp_tempcode();
     if (get_option('filedump_show_stats_count_total_files', true) == '1') {
         $bits->attach(do_template('BLOCK_SIDE_STATS_SUBLINE', array('KEY' => do_lang_tempcode('COUNT_FILES'), 'VALUE' => integer_format(count(get_directory_contents(get_custom_file_base() . '/uploads/filedump'))))));
     }
     if (get_option('filedump_show_stats_count_total_space', true) == '1') {
         $bits->attach(do_template('BLOCK_SIDE_STATS_SUBLINE', array('KEY' => do_lang_tempcode('DISK_USAGE'), 'VALUE' => clean_file_size(get_directory_size(get_custom_file_base() . '/uploads/filedump')))));
     }
     if ($bits->is_empty()) {
         return new ocp_tempcode();
     }
     $section = do_template('BLOCK_SIDE_STATS_SECTION', array('SECTION' => do_lang_tempcode('FILE_DUMP'), 'CONTENT' => $bits));
     return $section;
 }
Example #7
0
 /**
  * Standard modular run function for search results.
  *
  * @param  string			Search string
  * @param  boolean		Whether to only do a META (tags) search
  * @param  ID_TEXT		Order direction
  * @param  integer		Start position in total results
  * @param  integer		Maximum results to return in total
  * @param  boolean		Whether only to search titles (as opposed to both titles and content)
  * @param  string			Where clause that selects the content according to the main search string (SQL query fragment) (blank: full-text search)
  * @param  SHORT_TEXT	Username/Author to match for
  * @param  ?MEMBER		Member-ID to match for (NULL: unknown)
  * @param  TIME			Cutoff date
  * @param  string			The sort type (gets remapped to a field in this function)
  * @set    title add_date
  * @param  integer		Limit to this number of results
  * @param  string			What kind of boolean search to do
  * @set    or and
  * @param  string			Where constraints known by the main search code (SQL query fragment)
  * @param  string			Comma-separated list of categories to search under
  * @param  boolean		Whether it is a boolean search
  * @return array			List of maps (template, orderer)
  */
 function run($content, $only_search_meta, $direction, $max, $start, $only_titles, $content_where, $author, $author_id, $cutoff, $sort, $limit_to, $boolean_operator, $where_clause, $search_under, $boolean_search)
 {
     unset($author_id);
     unset($where_clause);
     require_lang('zones');
     // Calculate our where clause (search)
     if ($author != '') {
         return array();
     }
     require_code('files2');
     if ($search_under == '!') {
         $search_under = '';
     }
     $files = get_directory_contents(get_custom_file_base() . '/uploads/filedump/' . ($search_under == '' ? '' : $search_under . '/'));
     $_rows = $GLOBALS['SITE_DB']->query_select('filedump');
     $rows = array();
     foreach ($_rows as $row) {
         $rows[$row['path']] = $row;
     }
     $i = 0;
     $out = array();
     foreach ($files as $_path) {
         if ($search_under != '') {
             $_path = $search_under . '/' . $_path;
         }
         $path = get_custom_file_base() . '/uploads/filedump/' . $_path;
         if (filemtime($path) < $cutoff) {
             continue;
         }
         if (in_memory_search_match(array('content' => $content, 'conjunctive_operator' => $boolean_operator), $path)) {
             $caption = array_key_exists($_path, $rows) ? $rows[$_path] : $_path;
             $dirs = explode('/', dirname($_path));
             $pre = '';
             $file_breadcrumbs = new ocp_tempcode();
             $breadcrumbs_url = build_url(array('page' => 'filedump', 'place' => $pre . '/'), get_module_zone('filedump'));
             $file_breadcrumbs->attach(hyperlink($breadcrumbs_url, do_lang('ROOT')));
             foreach ($dirs as $dir) {
                 $file_breadcrumbs->attach(do_template('BREADCRUMB_SEPARATOR', array('_GUID' => '7ee62e230d53344a7d9667dc59be21c4')));
                 $breadcrumbs_url = build_url(array('page' => 'filedump', 'place' => $pre . $dir . '/'), get_module_zone('filedump'));
                 $file_breadcrumbs->attach(hyperlink($breadcrumbs_url, $dir));
                 $pre .= $dir . '/';
             }
             $url = get_custom_base_url() . '/uploads/filedump/' . $_path;
             require_code('images');
             if (!is_image($url)) {
                 $tpl = paragraph(hyperlink($url, escape_html($caption), true), 'dfdsfu09wl;f');
                 if (!$file_breadcrumbs->is_empty()) {
                     $tpl->attach(paragraph(do_lang_tempcode('LOCATED_IN', $file_breadcrumbs)));
                 }
                 $out[$i]['template'] = do_template('SIMPLE_PREVIEW_BOX', array('_GUID' => '51bc0cf751f4ccbd0b7f1a247b092368', 'TITLE' => basename($_path), 'SUMMARY' => $tpl));
             } else {
                 if (function_exists('set_time_limit')) {
                     @set_time_limit(5);
                 }
                 $tpl = do_image_thumb($url, $caption, true, true);
                 $out[$i]['template'] = do_template('SIMPLE_PREVIEW_BOX', array('_GUID' => '61bc0cf751f4ccbd0b7f1a247b092368', 'TITLE' => basename($_path), 'SUMMARY' => $tpl, 'BREADCRUMBS' => $file_breadcrumbs, 'URL' => $url));
             }
             if ($sort == 'title') {
                 $out[$i]['orderer'] = $path;
             } elseif ($sort == 'add_date') {
                 $out[$i]['orderer'] = filectime($path);
             } elseif ($sort == 'file_size') {
                 $out[$i]['orderer'] = filesize($path);
             }
             $i++;
         }
     }
     return $out;
 }
Example #8
0
/**
 * Copy a theme.
 *
 * @param  ID_TEXT		The original theme name
 * @param  ID_TEXT		The copy's theme name
 */
function actual_copy_theme($theme, $to)
{
    if ($theme == 'default') {
        fatal_exit(do_lang_tempcode('INTERNAL_ERROR'));
    }
    if (file_exists(get_custom_file_base() . '/themes/' . $to) || $to == 'default') {
        warn_exit(do_lang_tempcode('ALREADY_EXISTS', escape_html($to)));
    }
    require_code('abstract_file_manager');
    require_code('files2');
    force_have_afm_details();
    $contents = get_directory_contents(get_custom_file_base() . '/themes/' . $theme, '', true);
    foreach ($contents as $c) {
        afm_make_directory(dirname('themes/' . $to . '/' . $c), true, true);
        afm_copy('themes/' . $theme . '/' . $c, 'themes/' . $to . '/' . $c, true);
    }
    $needed = array('css', 'css_custom', 'images', 'images_custom', 'templates', 'templates_cached/' . get_site_default_lang(), 'templates_custom');
    foreach ($needed as $n) {
        afm_make_directory(dirname('themes/' . $to . '/' . $n), true, true);
    }
    $images = $GLOBALS['SITE_DB']->query_select('theme_images', array('*'), array('theme' => $theme));
    foreach ($images as $i) {
        $i['theme'] = $to;
        $i['path'] = str_replace('themes/' . $theme . '/', 'themes/' . $to . '/', $i['path']);
        $GLOBALS['SITE_DB']->query_insert('theme_images', $i);
    }
    log_it('COPY_THEME', $theme, $to);
}
Example #9
0
    /**
     * Standard import function.
     *
     * @param  object			The DB connection to import from
     * @param  string			The table prefix the target prefix is using
     * @param  PATH			The base directory we are importing from
     */
    function import_pages($db, $table_prefix, $file_base)
    {
        unset($db);
        unset($table_prefix);
        require_code('files2');
        $files = @get_directory_contents($file_base);
        $theme = either_param('theme');
        $convert_to_comcode = either_param_integer('convert_to_comcode', 0);
        $fix_html = either_param_integer('fix_html', 0);
        $base_url = either_param('base_url');
        if (substr($base_url, -1) == '/') {
            $base_url = substr($base_url, 0, strlen($base_url) - 1);
        }
        // Find all htm/html/php files
        $content_files = array();
        foreach ($files as $i => $file) {
            if (substr(strtolower($file), -4) == '.htm' || substr(strtolower($file), -5) == '.html' || substr(strtolower($file), -4) == '.php') {
                $content_files[] = $file;
                unset($files[$i]);
            }
        }
        if (count($content_files) == 0) {
            warn_exit(do_lang_tempcode('NO_PAGES_FOUND'));
        }
        // Discern new zones needed
        //  Note: files in directories in a deep path will be considered in a zone name changed so underscores replace slashes
        $new_zones = array();
        $current_zones = find_all_zones();
        foreach ($content_files as $file) {
            $zone = str_replace('/', '_', dirname($file));
            if ($zone == '.') {
                $zone = '';
            }
            if (!in_array($zone, $current_zones)) {
                $new_zones[] = $zone;
            }
        }
        $new_zones = array_unique($new_zones);
        // (Maybe AFM needed here - if zones have to be created, and possibly .htaccess changed to incorporate zone names in the redirects)
        if (count($new_zones) != 0) {
            require_code('abstract_file_manager');
            force_have_afm_details();
            $change_htaccess = get_option('htm_short_urls') == '1';
            $htaccess_path = get_file_base() . '/.htaccess';
            if ($change_htaccess && file_exists($htaccess_path) && is_writable_wrap($htaccess_path)) {
                $htaccess = file_get_contents($htaccess_path);
                $htaccess = preg_replace('#\\(site\\|forum\\|adminzone\\|cms\\|collaboration[^\\)]*#', '${0}|' . implode('|', $new_zones), $htaccess);
                $myfile = fopen($htaccess_path, 'wt');
                fwrite($myfile, $htaccess);
                fclose($myfile);
                fix_permissions($htaccess_path);
                sync_file($htaccess_path);
            }
            // Create new zones as needed (and set them to our chosen theme too)
            require_code('zones2');
            foreach ($new_zones as $zone) {
                actual_add_zone($zone, ucwords(str_replace('_', ' ', $zone)), 'start', '', $theme, 0, 0);
            }
        }
        // Discern cruft in htm/html via looking for best levenshtein to length ratio over a few pages; scan by tag, not by byte
        $compare_file_contents = array();
        shuffle($content_files);
        for ($i = 0; $i < min(2, count($content_files)); $i++) {
            $file_contents = file_get_contents($file_base . '/' . $content_files[$i]);
            $compare_file_contents[$content_files[$i]] = $this->_html_filter($file_contents, $fix_html, $base_url, $files, $file_base);
        }
        $cruft = array();
        if (count($compare_file_contents) > 1) {
            $to_find = array();
            if (file_exists($file_base . '/header.txt')) {
                $cruft['HEADER'] = $this->_html_filter(file_get_contents($file_base . '/header.txt'), $fix_html, $base_url, $files, $file_base);
            } else {
                $to_find[] = 'HEADER';
            }
            if (file_exists($file_base . '/footer.txt')) {
                $cruft['FOOTER'] = $this->_html_filter(file_get_contents($file_base . '/footer.txt'), $fix_html, $base_url, $files, $file_base);
            } else {
                $to_find[] = 'FOOTER';
            }
            foreach ($to_find as $template_wanted) {
                $best_ratios = array();
                foreach ($compare_file_contents as $i => $reference_file) {
                    if ($template_wanted == 'HEADER') {
                        $last_pos = strpos($reference_file, '<body');
                        if ($last_pos === false) {
                            $last_pos = 0;
                        } else {
                            $last_pos += 5;
                        }
                    } else {
                        $last_pos = strlen($reference_file) - 1;
                    }
                    $best_av_ratios = mixed();
                    $ratios = array();
                    while ($last_pos !== false) {
                        //@print('!'.(strlen($reference_file)-$last_pos).' '.$lv.' '.$ratio.'<br />'.chr(10));flush();if (@$dd++==180) @exit('fini'); // Useful for debugging
                        if ($template_wanted == 'HEADER') {
                            $next_pos = strpos($reference_file, '<', $last_pos);
                        } else {
                            $next_pos = strrpos(substr($reference_file, 0, $last_pos), '<');
                        }
                        if ($next_pos !== false) {
                            if ($template_wanted == 'HEADER') {
                                $up_to = substr($reference_file, 0, $next_pos);
                            } else {
                                $up_to = substr($reference_file, $next_pos);
                            }
                            $all_ratios_for_pos = array();
                            foreach ($compare_file_contents as $j => $other_file) {
                                if ($i != $j) {
                                    if ($template_wanted == 'HEADER') {
                                        $up_to_other_file = substr($other_file, 0, $next_pos);
                                    } else {
                                        $up_to_other_file = substr($other_file, $next_pos - (strlen($reference_file) - strlen($other_file)));
                                    }
                                    $lv = fake_levenshtein($up_to, $up_to_other_file);
                                    if ($template_wanted == 'HEADER') {
                                        $ratio = floatval($lv) * 3 - floatval($next_pos + 1);
                                        // We want this number to be as small as possible. We have multiplied the levenshtein distance because we care about that more than length (this number reached by experimentation); HTML has a low entropy which this number is fighting against.
                                    } else {
                                        $ratio = floatval($lv) * 3 - floatval(strlen($reference_file) - $next_pos);
                                        // We want this number to be as small as possible. We have multiplied the levenshtein distance because we care about that more than length (this number reached by experimentation); HTML has a low entropy which this number is fighting against.
                                    }
                                    $all_ratios_for_pos[] = $ratio;
                                }
                            }
                            $av_ratios = array_sum($all_ratios_for_pos) / floatval(count($all_ratios_for_pos));
                            if (is_null($best_av_ratios) || $av_ratios < $best_av_ratios) {
                                $best_av_ratios = $av_ratios;
                            } elseif ($av_ratios > $best_av_ratios + 300) {
                                break;
                            }
                            $ratios[$next_pos] = $av_ratios;
                            if ($template_wanted == 'HEADER') {
                                $next_pos++;
                            } else {
                                $next_pos--;
                            }
                        }
                        $last_pos = $next_pos;
                    }
                    asort($ratios);
                    $best_by_pos = array_keys($ratios);
                    $best_ratios[] = array($best_by_pos[0], $ratios[$best_by_pos[0]], $reference_file);
                }
                $best = mixed();
                $best_pos = NULL;
                $best_reference_file = NULL;
                foreach ($best_ratios as $bits) {
                    list($pos, $ratio, $reference_file) = $bits;
                    if (is_null($best) || $ratio < $best) {
                        $best = $ratio;
                        $best_pos = $pos;
                        $best_reference_file = $reference_file;
                    }
                }
                if ($template_wanted == 'HEADER') {
                    $cruft[$template_wanted] = substr($best_reference_file, 0, $best_pos);
                } else {
                    $cruft[$template_wanted] = substr($best_reference_file, $best_pos);
                }
            }
        } else {
            // We can't find any common consistency when we only have one, so we mark all cruft and then later we will actually assume GLOBAL.tpl does not change and the only header/footer bit is the logical one
            $cruft['HEADER'] = array_key_exists(0, $compare_file_contents) ? $compare_file_contents[0] : '';
            $cruft['FOOTER'] = array_key_exists(1, $compare_file_contents) ? $compare_file_contents[0] : '';
        }
        // Extract header from cruft (<body> and before); SAVE
        $header = $cruft['HEADER'];
        // special cases of something with ID or class of header/top going through too
        $header_cases = array('<div id="header"', '<div id="page_header"', '<div class="header"', '<div class="page_header"');
        foreach ($header_cases as $header_case) {
            $header_start_pos = strpos($header, $header_case);
            if ($header_start_pos !== false) {
                $header_start_pos = strpos($header, '>', $header_start_pos) + 1;
                break;
            }
        }
        if ($header_start_pos !== false) {
            $div_count = 1;
            do {
                $next_start = strpos($header, '<div ', $header_start_pos);
                $next_end = strpos($header, '</div>', $header_start_pos);
                $header_start_pos = $next_start !== false && $next_start < $next_end ? $next_start : $next_end;
                if ($header_start_pos !== false) {
                    $header_start_pos = strpos($header, '>', $header_start_pos) + 1;
                }
                $div_count += $next_start !== false && $next_start < $next_end ? 1 : -1;
            } while ($div_count > 0 && $header_start_pos !== false);
        }
        $body_start_pos = strpos($header, '<body');
        $head_end_pos = strpos($header, '<link');
        if ($head_end_pos === false) {
            $head_end_pos = strpos($header, '</head');
        }
        if ($header_start_pos === false) {
            $header_start_pos = strpos($header, '>', $body_start_pos) + 1;
        }
        if ($header_start_pos !== false) {
            $header = substr($header, 0, $header_start_pos);
        }
        $path = get_custom_file_base() . '/themes/' . filter_naughty($theme) . '/templates_custom/HEADER.tpl';
        $myfile = fopen($path, 'wt');
        $header_to_write = substr($header, 0, $head_end_pos) . '	<script type="text/javascript">// <![CDATA[
		{+START,IF,{$AND,{$EQ,,{$_GET,keep_has_js}},{$NOT,{$JS_ON}}}}
		if ((window.location.href.indexOf(\'upgrader.php\')==-1) && (window.location.search.indexOf(\'keep_has_js\')==-1)) {$,Redirect with JS on, and then hopefully we can remove keep_has_js after one click. This code only happens if JS is marked off, no infinite loops can happen.}
			window.location=window.location.href+((window.location.search==\'\')?(((window.location.href.indexOf(\'.htm\')==-1)&&(window.location.href.indexOf(\'.php\')==-1))?(((window.location.href.substr(window.location.href.length-1)!=\'/\')?\'/\':\'\')+\'index.php?\'):\'?\'):\'&\')+\'keep_has_js=1{+START,IF,{$DEV_MODE}}&keep_devtest=1{+END}\';
		{+END}
		{+START,IF,{$NOT,{$BROWSER_MATCHES,ie}}}{+START,IF,{$HAS_SPECIFIC_PERMISSION,sees_javascript_error_alerts}}window.take_errors=true;{+END}{+END}
		var {+START,IF,{$CONFIG_OPTION,is_on_timezone_detection}}server_timestamp={$FROM_TIMESTAMP%},{+END}ocp_lang=\'{$LANG;}\',ocp_theme=\'{$THEME;}\';
	//]]></script>

	<meta name="description" content="{+START,IF,{$NEQ,{DESCRIPTION},{!NA}}}{DESCRIPTION*}{+END}" />
	<meta name="keywords" content="{KEYWORDS*}" />

	{$CSS_TEMPCODE}

	{+START,IF_PASSED,EXTRA_HEAD}
		{EXTRA_HEAD}
	{+END}

	{$JS_TEMPCODE,header}

	{REFRESH}' . substr($header, $head_end_pos);
        $header_to_write = preg_replace('#<title>[^<>]*</title>#', '<title>{+START,IF_NON_EMPTY,{HEADER_TEXT}}{HEADER_TEXT*} - {+END}{$SITE_NAME*}</title>', $header_to_write);
        $header_to_write = preg_replace('#<meta name="keywords" content="([^"]*)"[^>]*>#', '', $header_to_write);
        $header_to_write = preg_replace('#<meta name="description" content="([^"]*)"[^>]*>#', '', $header_to_write);
        fwrite($myfile, $header_to_write);
        fclose($myfile);
        fix_permissions($path);
        sync_file($path);
        // Extract footer from cruft (</body> and below); SAVE
        $footer = $cruft['FOOTER'];
        // special cases of something with ID or class of footer/bottom going through too
        $footer_cases = array('<div id="footer"', '<div id="page_footer"', '<div class="footer"', '<div class="page_footer"');
        foreach ($footer_cases as $footer_case) {
            $footer_start_pos = strpos($footer, $footer_case);
            if ($footer_start_pos !== false) {
                break;
            }
        }
        if ($footer_start_pos === false) {
            $footer_start_pos = strpos($footer, '</body');
        }
        if ($footer_start_pos !== false) {
            $footer = substr($footer, $footer_start_pos);
        }
        $path = get_custom_file_base() . '/themes/' . filter_naughty($theme) . '/templates_custom/FOOTER.tpl';
        $myfile = fopen($path, 'wt');
        $footer_to_write = $footer;
        fwrite($myfile, $footer_to_write);
        fclose($myfile);
        fix_permissions($path);
        sync_file($path);
        // What remains is saved to GLOBAL (note that we don't try and be clever about panels - this is up to the user, and they don't really need them anyway)
        if (count($compare_file_contents) > 1) {
            $global_to_write = substr($cruft['HEADER'], strlen($header)) . "\n{MIDDLE}\n" . substr($cruft['FOOTER'], 0, strlen($cruft['FOOTER']) - strlen($footer));
        } else {
            $cruft['HEADER'] = $header_to_write;
            $cruft['FOOTER'] = $footer_to_write;
            $global_to_write = '{MIDDLE}';
        }
        $path = get_custom_file_base() . '/themes/' . filter_naughty($theme) . '/templates_custom/GLOBAL.tpl';
        $myfile = fopen($path, 'wt');
        fwrite($myfile, $global_to_write);
        fclose($myfile);
        fix_permissions($path);
        sync_file($path);
        // Extract site name from <title> tag, based on common consistency (largest common substring)
        $site_name = get_site_name();
        if (count($compare_file_contents) > 1) {
            $titles_in_reference_files = array();
            foreach ($compare_file_contents as $reference_file) {
                $matches = array();
                if (preg_match('#<title>(.*)</title>#', $reference_file, $matches) != 0) {
                    $titles_in_reference_files[] = $matches[1];
                }
            }
            // Find largest common substring
            $lcs = '';
            foreach ($titles_in_reference_files as $title_a) {
                for ($start = 0; $start < strlen($title_a); $start++) {
                    for ($end = $start + 1; $end < strlen($title_a); $end++) {
                        $current = substr($title_a, $start, $end - $start + 1);
                        foreach ($titles_in_reference_files as $title_b) {
                            if ($title_a != $title_b) {
                                if (strpos(strtolower($title_b), strtolower($current)) === false) {
                                    continue 2;
                                }
                            }
                        }
                        if (strpos(strtolower($title_b), strtolower($current)) !== false) {
                            if (strlen($current) > strlen($lcs)) {
                                $lcs = $current;
                            }
                        }
                    }
                }
            }
            // Strip bits
            $site_name = trim(preg_replace('#^[\\|\\-�,]#', '', preg_replace('#[\\|\\-�,]$#', '', trim($lcs))));
            // Save as site name
            set_option('site_name', $site_name);
        }
        // Go and save our pages
        disable_php_memory_limit();
        foreach ($content_files as $content_file) {
            $file_contents = file_get_contents($file_base . '/' . $content_file);
            // Find page-link for page
            $slash_count = substr_count($content_file, '/');
            if ($slash_count == 0) {
                $content_file = '/' . $content_file;
            } elseif ($slash_count > 1) {
                $last_slash_pos = strrpos($content_file, '/');
                $content_file = str_replace('/', '_', substr($content_file, 0, $last_slash_pos)) . substr($content_file, 0, $last_slash_pos);
            }
            list($zone, $page) = explode('/', preg_replace('#\\..*$#', '', $content_file), 2);
            if ($page == 'index') {
                $page = 'start';
            }
            if (substr($content_file, -4) == '.php') {
                $file_path = zone_black_magic_filterer(get_custom_file_base() . '/' . $zone . '/pages/minimodules_custom/' . $page . '.php');
                $myfile = fopen($file_path, 'wt');
                fwrite($myfile, $file_contents);
                fclose($myfile);
                fix_permissions($file_path);
                sync_file($file_path);
            } else {
                $filtered = $this->_html_filter($file_contents, $fix_html, $base_url, $files, $file_base);
                // Try and work out page title from <title> tag
                $matches = array();
                $page_title = NULL;
                if (preg_match('#<title>(.*)</title>#', $filtered, $matches) != 0) {
                    $page_title = preg_replace('#( [\\|\\-�] )?' . preg_quote($site_name) . '( [\\|\\-�] )?#', '', $matches[1]);
                }
                $page_keywords = NULL;
                if (preg_match('#<meta name="keywords" content="([^"]*)"#', $filtered, $matches) != 0) {
                    $page_keywords = $matches[1];
                }
                $page_description = NULL;
                if (preg_match('#<meta name="description" content="([^"]*)"#', $filtered, $matches) != 0) {
                    $page_description = $matches[1];
                }
                require_code('seo2');
                seo_meta_set_for_explicit('comcode_page', $zone . ':' . $page, $page_keywords, $page_description);
                // Strip cruft off for htm/html files
                $i = strpos($filtered, '</head>');
                if ($i === false) {
                    $i = 0;
                } else {
                    $i += 7;
                }
                $filtered = $this->levenshtein_strip_search($cruft['HEADER'], $filtered, false, $i);
                $filtered = $this->levenshtein_strip_search($cruft['FOOTER'], $filtered, true, 0);
                // Copy htm/html/php files to correct zone page directories (html_custom/<lang>, or minimodules_custom)
                if ($convert_to_comcode == 0) {
                    // Insert an <h1> if the h1 is not there
                    if (strpos($filtered, '<h1') === false && !is_null($page_title)) {
                        $filtered = "<h1>" . $page_title . "</h1>\n\n" . $filtered;
                    }
                    $file_path = zone_black_magic_filterer(get_custom_file_base() . '/' . $zone . '/pages/comcode_custom/' . get_site_default_lang() . '/' . $page . '.txt');
                    $myfile = fopen($file_path, 'wt');
                    fwrite($myfile, '[semihtml]' . $filtered . '[/semihtml]');
                    fclose($myfile);
                    fix_permissions($file_path);
                    sync_file($file_path);
                } else {
                    // Insert an <h1> if the h1 is not there
                    if (strpos($filtered, '[title') === false && !is_null($page_title)) {
                        $filtered = "[title]" . $page_title . "[/title]\n\n" . $filtered;
                    }
                    require_code('comcode_from_html');
                    $comcode = semihtml_to_comcode($filtered);
                    $file_path = zone_black_magic_filterer(get_custom_file_base() . '/' . $zone . '/pages/comcode_custom/' . get_site_default_lang() . '/' . $page . '.txt');
                    $myfile = fopen($file_path, 'wt');
                    fwrite($myfile, $comcode);
                    fclose($myfile);
                    fix_permissions($file_path);
                    sync_file($file_path);
                }
            }
        }
        // Copy all remaining files to under uploads/website_specific
        foreach ($files as $file) {
            if (!file_exists($file_base . '/' . $file)) {
                continue;
            }
            $path = get_custom_file_base() . '/uploads/website_specific/' . $file;
            $create_path = $path;
            do {
                @mkdir(dirname($create_path), 0777);
                $create_path = dirname($create_path);
            } while (strlen($create_path) > 1);
            copy($file_base . '/' . $file, $path);
            fix_permissions($path);
            sync_file($path);
        }
        // Set the panels to be blank
        foreach (array('site/', '') as $zone) {
            $panels = array('panel_left', 'panel_right');
            foreach ($panels as $panel) {
                $path = zone_black_magic_filterer(get_custom_file_base() . '/' . $zone . 'pages/comcode_custom/' . filter_naughty(fallback_lang()) . '/' . filter_naughty($panel) . '.txt');
                $myfile = fopen($path, 'wt');
                fclose($myfile);
                fix_permissions($path);
                sync_file($path);
            }
        }
    }
Example #10
0
/**
 * Get the contents of a directory, recursively. It is assumed that the directory exists.
 *
 * @param  PATH			The path to search
 * @param  PATH			The path we prepend to everything we find (intended to be used inside the recursion)
 * @param  boolean		Whether to also get special files
 * @param  boolean		Whether to recurse (if not, will return directories as files)
 * @return array			The contents of the directory
 */
function get_directory_contents($path, $rel_path = '', $special_too = false, $recurse = true)
{
    $out = array();
    $d = opendir($path);
    while (($file = readdir($d)) !== false) {
        if (!$special_too) {
            if (should_ignore_file($rel_path . ($rel_path == '' ? '' : '/') . $file, IGNORE_ACCESS_CONTROLLERS)) {
                continue;
            }
        } elseif ($file == '.' || $file == '..') {
            continue;
        }
        if (is_file($path . '/' . $file) || !$recurse) {
            $out[] = $rel_path . ($rel_path == '' ? '' : '/') . $file;
        } elseif (is_dir($path . '/' . $file)) {
            $out = array_merge($out, get_directory_contents($path . '/' . $file, $rel_path . ($rel_path == '' ? '' : '/') . $file, $special_too, $recurse));
        }
    }
    closedir($d);
    return $out;
}
 /**
  * Standard modular simple function for ajax-tree hooks. Returns a normal <select> style <option>-list, for fallback purposes
  *
  * @param  ?ID_TEXT		The ID to do under (NULL: root) - not always supported
  * @param  array			Options being passed through
  * @param  ?ID_TEXT		The ID to select by default (NULL: none)
  * @return tempcode		The nice list
  */
 function simple($id, $options, $it = NULL)
 {
     $out = '';
     if (has_actual_page_access(NULL, 'filedump')) {
         require_code('images');
         require_code('files2');
         $fullpath = get_custom_file_base() . '/uploads/filedump';
         if ($id != '') {
             $fullpath .= '/' . $id;
         }
         $tree = get_directory_contents($fullpath, '');
         foreach ($tree as $f) {
             if (!isset($options['only_images']) || !$options['only_images'] || is_image($f)) {
                 $rel = preg_replace('#^' . str_replace('#', '\\#', preg_quote($id)) . '/#', '', $f);
                 $out .= '<option value="' . escape_html('uploads/filedump/' . $f) . '"' . ($it === $f ? ' selected="selected"' : '') . '>' . escape_html($rel) . '</option>';
             }
         }
     }
     return make_string_tempcode($out);
 }
Example #12
0
 $ini_file = ($theme == 'default' ? get_file_base() : get_custom_file_base()) . '/themes/' . filter_naughty($theme) . '/theme.ini';
 if (file_exists($ini_file)) {
     $details = better_parse_ini_file($ini_file);
     if (array_key_exists('title', $details)) {
         $name = $details['title'];
     }
     if (array_key_exists('description', $details)) {
         $description = $details['description'];
     }
     if (array_key_exists('author', $details) && $details['author'] != 'admin') {
         $author = $details['author'];
     }
 }
 $file = 'theme-' . preg_replace('#^[\\_\\.\\-]#', 'x', preg_replace('#[^\\w\\.\\-]#', '_', $theme)) . $version_for_name . '.tar';
 $files2 = array();
 $theme_files = get_directory_contents(get_custom_file_base() . '/themes/' . $theme, 'themes/' . $theme);
 foreach ($theme_files as $file2) {
     if (substr($file2, -4) != '.tcp' && substr($file2, -4) != '.tcd' && substr($file2, -9) != '.editfrom') {
         $files2[] = $file2;
     }
 }
 foreach ($page_files as $file2) {
     $matches = array();
     $regexp = '#^((\\w+)/)?pages/comcode_custom/[^/]*/' . str_replace('#', '\\#', preg_quote($theme)) . '\\_\\_([\\w\\_]+)\\.txt$#';
     if (preg_match($regexp, $file2, $matches) != 0 && $matches[1] != 'docs' . strval(ocp_version())) {
         $files2[] = dirname($file2) . '/' . substr(basename($file2), strlen($theme) + 2);
     }
 }
 $_GET['keep_theme_test'] = '1';
 $_GET['theme'] = $theme;
 create_addon($file, $files2, $name, '', '', $author, 'ocProducts Ltd', '1.0', $description, 'exports/mods');
<?php

// Include main config file
include "includes/config.inc.php";
// Include common functions
include "includes/functions.inc.php";
$data = get_directory_contents(DIRECTORY, true);
print json_encode($data);
Example #14
0
<?php

require_code('files2');
$basedir = get_custom_file_base() . '/uploads/filedump/' . $GLOBALS['FORUM_DRIVER']->get_username(get_member());
$baseurl = get_custom_base_url() . '/uploads/filedump/' . rawurlencode($GLOBALS['FORUM_DRIVER']->get_username(get_member()));
$files = file_exists($basedir) ? get_directory_contents($basedir) : array();
if (count($files) == 0) {
    echo '<p class="nothing_here">No files have been uploaded for you yet.</p>';
} else {
    natsort($files);
    echo '<div class="wide_table_wrap"><table class="wide_table solidborder">';
    echo '<colgroup><col width="25%" /><col width="75%" /><col width="100px" /></colgroup>';
    echo '<thead><tr><th>Filename</th><th>Description</th><th>File size</th></tr></thead>';
    echo '<tbody>';
    foreach ($files as $file) {
        $dbrows = $GLOBALS['SITE_DB']->query_select('filedump', array('description', 'the_member'), array('name' => $file, 'path' => '/' . $GLOBALS['FORUM_DRIVER']->get_username(get_member()) . '/'));
        if (!array_key_exists(0, $dbrows)) {
            $description = do_lang_tempcode('NONE_EM');
        } else {
            $description = make_string_tempcode(get_translated_text($dbrows[0]['description']));
        }
        echo '
			<tr>
				<td><a target="_blank" href="' . escape_html($baseurl . '/' . $file) . '">' . escape_html($file) . '</a></td>
				<td>' . $description->evaluate() . '</td>
				<td>' . escape_html(clean_file_size(filesize($basedir . '/' . $file))) . '</td>
			</tr>
		';
    }
    echo '</tbody>';
    echo '</table></div>';
 $time = filemtime($probe_dir . '/' . $file);
 $latest_time = @filemtime(get_file_base() . '/' . $file);
 if ($latest_time !== false) {
     if ($time != $latest_time) {
         $old = file_get_contents($probe_dir . '/' . $file);
         $new = file_get_contents(get_file_base() . '/' . $file);
         if ($old != $new) {
             if ($time < $latest_time) {
                 $days_diff = intval(ceil(($latest_time - $time) / 60 / 60 / 24));
                 if ($days_diff > $cutoff_days) {
                     $cutoff_days = $days_diff;
                 }
             }
             if (preg_match('#^themes/default/(css/[^/]*\\.css|templates/[^/]*\\.tpl)$#', $file) != 0) {
                 // Looks for themes which may override
                 $themes = get_directory_contents($probe_dir . '/themes', '', false, false);
                 foreach ($themes as $theme) {
                     if ($theme == 'map.ini') {
                         continue;
                     }
                     if ($theme == 'index.html') {
                         continue;
                     }
                     $override_file = str_replace(array('themes/default/templates/', 'themes/default/css/'), array('themes/' . $theme . '/templates_custom/', 'themes/' . $theme . '/css_custom/'), $file) . '.editfrom';
                     if (file_exists($probe_dir . '/' . $override_file)) {
                         $theme_old = file_get_contents($probe_dir . '/' . $override_file);
                         $theme_new = $new;
                         $theme_old = preg_replace('#/\\*.*\\*/#sU', '', $theme_old);
                         $theme_new = preg_replace('#/\\*.*\\*/#sU', '', $theme_new);
                         if ($theme_new != $theme_old) {
                             $manual_changes['css_diff'][basename($override_file, 'editfrom')] = diff_simple_2($theme_old, $theme_new, true);
Example #16
0
 /**
  * Standard modular run function for RSS hooks.
  *
  * @param  string			A list of categories we accept from
  * @param  TIME			Cutoff time, before which we do not show results from
  * @param  string			Prefix that represents the template set we use
  * @set    RSS_ ATOM_
  * @param  string			The standard format of date to use for the syndication type represented in the prefix
  * @param  integer		The maximum number of entries to return, ordering by date
  * @return ?array			A pair: The main syndication section, and a title (NULL: error)
  */
 function run($_filters, $cutoff, $prefix, $date_string, $max)
 {
     if (!addon_installed('filedump')) {
         return NULL;
     }
     if (!has_actual_page_access(get_member(), 'filedump')) {
         return NULL;
     }
     if (!file_exists(get_custom_file_base() . '/uploads/filedump/')) {
         return array();
     }
     $filters = explode(',', $_filters);
     require_code('files2');
     $content = new ocp_tempcode();
     $files = get_directory_contents(get_custom_file_base() . '/uploads/filedump/');
     $_rows = $GLOBALS['SITE_DB']->query_select('filedump', NULL, NULL, '', NULL, NULL, true);
     if (is_null($_rows)) {
         return NULL;
     }
     $rows = array();
     foreach ($_rows as $row) {
         $rows[$row['path']] = $row;
     }
     foreach ($files as $i => $file) {
         if ($i == $max) {
             break;
         }
         if ($filters != array('')) {
             $ok = false;
             foreach ($filters as $filter) {
                 if (substr($file, 0, strlen($filter)) == $filter) {
                     $ok = true;
                 }
             }
             if (!$ok) {
                 continue;
             }
         }
         $id = $file;
         $news_date = date($date_string, filectime(get_custom_file_base() . '/uploads/filedump/' . $file));
         $edit_date = date($date_string, filemtime(get_custom_file_base() . '/uploads/filedump/' . $file));
         if ($news_date == $edit_date) {
             $edit_date = '';
         }
         $summary = '';
         $news = '';
         $author = '';
         if (array_key_exists($file, $rows)) {
             $summary = get_translated_text($rows[$file]['description']);
             $author = $GLOBALS['FORUM_DRIVER']->get_username($rows['the_member']);
         }
         $bits = explode('/', $file, 2);
         $news_title = xmlentities(escape_html($bits[0]));
         $category = array_key_exists(1, $bits) ? $bits[1] : '';
         $category_raw = $category;
         $view_url = get_custom_base_url() . '/uploads/filedump/' . $file;
         $if_comments = new ocp_tempcode();
         $content->attach(do_template($prefix . 'ENTRY', array('VIEW_URL' => $view_url, 'SUMMARY' => $summary, 'EDIT_DATE' => $edit_date, 'IF_COMMENTS' => $if_comments, 'TITLE' => $news_title, 'CATEGORY_RAW' => $category_raw, 'CATEGORY' => $category, 'AUTHOR' => $author, 'ID' => $id, 'NEWS' => $news, 'DATE' => $news_date)));
     }
     require_lang('filedump');
     return array($content, do_lang('FILE_DUMP'));
 }