Guest User

Untitled

a guest
Nov 29th, 2010
16,105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 94.86 KB | None | 0 0
  1. <?
  2. if(file_exists('/www/global/lockdown')) {
  3.     if($_COOKIE['4chan_auser'] && $_COOKIE['4chan_apass'] && ($_POST['mode']=='usrdel'||$_GET['mode']=='latest')) {
  4.         // ok
  5.     }
  6.     else {
  7.          die('Posting temporarily disabled. Come back later!<br/>&mdash;Team 4chan (uptime? what\'s that?)');
  8.     }
  9. }
  10. include_once "/www/global/yotsuba_config.php";
  11. include("/www/global/lib/postfilter.php");
  12. include("/www/global/lib/ads.php");
  13. define('SQLLOGBAN', 'banned_users');        //Table (NOT DATABASE) used for holding banned users
  14. define('SQLLOGMOD', 'mod_users');       //Table (NOT DATABASE) used for holding mod users
  15. define('SQLLOGDEL', 'del_log');     //Table (NOT DATABASE) used for holding deletion log
  16.  
  17. if(BOARD_DIR == 'test') {
  18.  ini_set('display_errors', 1);
  19. }
  20. extract($_POST);
  21. extract($_GET);
  22. extract($_COOKIE);
  23.  
  24. $id = intval($id);
  25.  
  26. if(array_key_exists('upfile',$_FILES)) {
  27. $upfile_name=$_FILES["upfile"]["name"];
  28. $upfile=$_FILES["upfile"]["tmp_name"];
  29. }
  30. else {
  31. $upfile_name=$upfile='';
  32. }
  33.  
  34. $path = realpath("./").'/'.IMG_DIR;
  35. ignore_user_abort(TRUE);
  36.  
  37. if(WORD_FILT&&file_exists("wf.php")){include_once("wf.php");}
  38. if(JANITOR_BOARD == 1)
  39.     include_once '/www/global/plugins/broomcloset.php';
  40.  
  41. mysql_board_connect();
  42.  
  43. // truncate $str to $max_lines lines and return $str and $abbr
  44. // where $abbr = whether or not $str was actually truncated
  45. function abbreviate($str,$max_lines) {
  46.     if(!defined('MAX_LINES_SHOWN')) {
  47.         if(defined('BR_CHECK')) {
  48.         define('MAX_LINES_SHOWN', BR_CHECK);
  49.         } else {
  50.         define('MAX_LINES_SHOWN', 20);
  51.         }
  52.         $max_lines = MAX_LINES_SHOWN;
  53.     }
  54.     $lines = explode("<br />", $str);
  55.     if(count($lines) > $max_lines) {
  56.         $abbr = 1;
  57.         $lines = array_slice($lines, 0, $max_lines);
  58.         $str = implode("<br />", $lines);
  59.     } else {
  60.         $abbr = 0;
  61.     }
  62.    
  63.     //close spans after abbreviating
  64.     //XXX will not work with more html - use abbreviate_html from shiichan
  65.     $str .= str_repeat("</span>", substr_count($str, "<span") - substr_count($str, "</span"));
  66.    
  67.     return array($str, $abbr);
  68. }
  69.  
  70.  
  71. // print $contents to $filename by using a temporary file and renaming it
  72. // (makes *.html and *.gz if USE_GZIP is on)
  73. function print_page($filename,$contents,$force_nogzip=0) {
  74.     $gzip = (USE_GZIP == 1 && !$force_nogzip);
  75.     $tempfile = tempnam(realpath(RES_DIR), "tmp"); //note: THIS actually creates the file
  76.     file_put_contents($tempfile, $contents, FILE_APPEND);
  77.     rename($tempfile, $filename);
  78.     chmod($filename, 0664); //it was created 0600
  79.  
  80.     if($gzip) {
  81.         $tempgz = tempnam(realpath(RES_DIR), "tmp"); //note: THIS actually creates the file
  82.         $gzfp = gzopen($tempgz, "w");
  83.         gzwrite($gzfp, $contents);
  84.         gzclose($gzfp);
  85.         rename($tempgz, $filename . '.gz');
  86.         chmod($filename . '.gz', 0664); //it was created 0600
  87.     }
  88. }
  89.  
  90. function file_get_contents_cached($filename) {
  91.     static $cache = array();
  92.     if(isset($cache[$filename]))
  93.         return $cache[$filename];
  94.     $cache[$filename] = file_get_contents($filename);
  95.     return $cache[$filename];
  96. }
  97.    
  98. function blotter_contents() {
  99.     static $cache;
  100.     if(isset($cache)) return $cache;
  101.     $ret = "";
  102.     $topN = 4; //how many lines to print
  103.     $bl_lines = file( BLOTTER_PATH );
  104.     $bl_top = array_slice($bl_lines, 0, $topN);
  105.     $date = "";
  106.     foreach($bl_top as $line) {
  107.             if(!$date) {
  108.                 $lineparts = explode(' - ', $line);
  109.                 if(strpos($lineparts[0],'<font')!==FALSE) {
  110.                     $dateparts = explode('>', $lineparts[0]);
  111.                     $date = $dateparts[1];
  112.                     $date = "<li><font color=\"red\">Blotter updated: $date</font>";
  113.                 }
  114.                 else {
  115.                     $date = $lineparts[0];
  116.                     $date = "<li>Blotter updated: $date";
  117.                 }
  118.             }
  119.             $line = trim($line);
  120.             $line = str_replace("\\", "\\\\", $line);
  121.             $line = str_replace("'", "\'", $line);
  122.             $ret .= "'<li>$line'+\n";
  123.     }
  124.     $ret .= "''";
  125.     $cache = array($date,$ret);
  126.     return array($date,$ret);
  127. }
  128.  
  129. // insert into the rapidsearch queue
  130. function rapidsearch_insert($board, $no, $body) {
  131.     $board = mysql_real_escape_string($board);
  132.     $no = (int)$no;
  133.     $body = mysql_real_escape_string($body);
  134.     mysql_global_do("INSERT INTO rs.rsqueue (`board`,`no`,`ts`,`com`) VALUES ('$board',$no,NOW(),'$body')");
  135. }
  136.  
  137. function find_match_and_prefix($regex, $str, $off, &$match)
  138. {
  139.     if (!preg_match($regex, $str, $m, PREG_OFFSET_CAPTURE, $off)) return FALSE;
  140.    
  141.     $moff = $m[0][1];
  142.     $match = array(substr($str, $off, $moff-$off), $m[0][0]);
  143.  
  144.     return TRUE;
  145. }
  146.  
  147. function spoiler_parse($com) {
  148.     if (!find_match_and_prefix("/\[spoiler\]/", $com, 0, $m)) return $com;
  149.    
  150.     $bl = strlen("[spoiler]"); $el = $bl+1;
  151.     $st = '<span class="spoiler" onmouseover="this.style.color=\'#FFF\';" onmouseout="this.style.color=this.style.backgroundColor=\'#000\'" style="color:#000;background:#000">';
  152.     $et = '</span>';
  153.     $ret = $m[0].$st; $lev = 1;
  154.     $off = strlen($m[0]) + $bl;
  155.    
  156.     while (1) {
  157.         if (!find_match_and_prefix("@\[/?spoiler\]@", $com, $off, $m)) break;
  158.         list($txt, $tag) = $m;
  159.        
  160.         $ret .= $txt;
  161.         $off += strlen($txt) + strlen($tag);
  162.        
  163.         if ($tag == "[spoiler]") {
  164.             $ret .= $st;
  165.             $lev++;
  166.         } else if ($lev) {
  167.             $ret .= $et;
  168.             $lev--;
  169.         }
  170.     }
  171.    
  172.     $ret .= substr($com, $off, strlen($com)-$off);
  173.     $ret .= str_repeat($et, $lev);
  174.  
  175.     return $ret;
  176. }
  177.  
  178. //rebuild the bans in array $boards
  179. function rebuild_bans($boards) {
  180.     $cmd = "nohup /usr/local/bin/suid_run_global bin/rebuildbans $boards >/dev/null 2>&1 &";
  181.     exec($cmd);
  182. }
  183.  
  184. function append_ban($board, $ip) {
  185.     $cmd = "nohup /usr/local/bin/suid_run_global bin/appendban $board $ip >/dev/null 2>&1 &";
  186.     exec($cmd);
  187. }
  188.  
  189. // check whether the current user can perform $action (on $no, for some actions)
  190. // board-level access is cached in $valid_cache.
  191. function valid($action='moderator', $no=0){
  192.     static $valid_cache; // the access level of the user
  193.     $access_level = array('none' => 0, 'janitor' => 1, 'janitor_this_board' => 2, 'moderator' => 5, 'manager' => 10, 'admin' => 20);
  194.     if(!isset($valid_cache)) {
  195.         $valid_cache = $access_level['none'];
  196.         if(isset($_COOKIE['4chan_auser'])&&isset($_COOKIE['4chan_apass'])){
  197.             $user = mysql_real_escape_string($_COOKIE['4chan_auser']);
  198.             $pass = mysql_real_escape_string($_COOKIE['4chan_apass']);
  199.         }
  200.         if($user&&$pass) {
  201.             $result=mysql_global_call("SELECT allow,deny FROM ".SQLLOGMOD." WHERE username='$user' and password='$pass'");
  202.             list($allow,$deny) = mysql_fetch_row($result);
  203.             mysql_free_result($result);
  204.             if($allow) {
  205.                 $allows = explode(',', $allow);
  206.                 $seen_janitor_token = false;
  207.                 // each token can increase the access level,
  208.                 // except that we only know that they're a moderator or a janitor for another board
  209.                 // AFTER we read all the tokens
  210.                 foreach($allows as $token) {
  211.                     if($token == 'janitor')
  212.                         $seen_janitor_token = true;
  213.                     else if($token == 'manager' && $valid_cache < $access_level['manager'])
  214.                         $valid_cache = $access_level['manager'];
  215.                     else if($token == 'admin' && $valid_cache < $access_level['admin'])
  216.                         $valid_cache = $access_level['admin'];
  217.                     else if(($token == BOARD_DIR || $token == 'all') && $valid_cache < $access_level['janitor_this_board'])
  218.                         $valid_cache = $access_level['janitor_this_board']; // or could be moderator, will be increased in next step
  219.                 }
  220.                 // now we can set moderator or janitor status
  221.                 if(!$seen_janitor_token) {
  222.                     if($valid_cache < $access_level['moderator'])
  223.                         $valid_cache = $access_level['moderator'];
  224.                 }
  225.                 else {
  226.                     if($valid_cache < $access_level['janitor'])
  227.                         $valid_cache = $access_level['janitor'];
  228.                 }
  229.                 if($deny) {
  230.                     $denies = explode(',', $deny);
  231.                     if(in_array(BOARD_DIR,$denies)) {
  232.                         $valid_cache = $access_level['none'];
  233.                     }
  234.                 }
  235.             }
  236.         }
  237.     }
  238.     switch($action) {
  239.         case 'moderator':
  240.             return $valid_cache >= $access_level['moderator'];
  241.         case 'textonly':
  242.             return $valid_cache >= $access_level['moderator'];
  243.         case 'janitor_board':
  244.             return $valid_cache >= $access_level['janitor'];
  245.         case 'delete':
  246.             if($valid_cache >= $access_level['janitor_this_board']) {
  247.                 return true;
  248.             }
  249.             // if they're a janitor on another board, check for illegal post unlock        
  250.             else if($valid_cache >= $access_level['janitor']) {
  251.                 $query=mysql_global_do("SELECT COUNT(*) from reports WHERE board='".BOARD_DIR."' AND no=$no AND cat=2");
  252.                 $illegal_count = mysql_result($query, 0, 0);
  253.                 mysql_free_result($query);
  254.                 return $illegal_count >= 3;
  255.             }
  256.         case 'reportflood':
  257.             return $valid_cache >= $access_level['janitor'];
  258.         case 'floodbypass':
  259.             return $valid_cache >= $access_level['moderator'];
  260.         default: // unsupported action
  261.             return false;
  262.     }
  263. }
  264.  
  265. function sticky_post($no, $position) {
  266.     global $log; log_cache();
  267.     $post_sticknum="202701010000".sprintf("%02d",$position);
  268.     $log[$no]['root'] = $post_sticknum;
  269.     $log[$no]['sticky'] = '1';
  270.     mysql_board_call('UPDATE '.SQLLOG." SET sticky='1'".
  271.                 ", root='".$post_sticknum."'".
  272.                 " WHERE no='".mysql_real_escape_string($no)."'");
  273. }
  274.  
  275. function permasage_post($no) {
  276.     global $log; log_cache();
  277.     $log[$no]['permasage'] = '1';
  278.     mysql_board_call('UPDATE '.SQLLOG." SET permasage='1'".
  279.                 " WHERE no='".mysql_real_escape_string($no)."'");
  280. }
  281.  
  282. function rebuildqueue_create_table() {
  283.     $sql = <<<EOSQL
  284. CREATE TABLE `rebuildqueue` (
  285.   `board` char(4) NOT NULL,
  286.   `no` int(11) NOT NULL,
  287.   `ownedby` int(11) NOT NULL default '0',
  288.   `ts` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  289.   PRIMARY KEY  (`board`,`no`,`ownedby`)
  290. )
  291. EOSQL;
  292.     mysql_board_call($sql);
  293. }
  294.  
  295. function rebuildqueue_add($no) {
  296.     $board = BOARD_DIR;
  297.     $no = (int)$no;
  298.     for($i=0;$i<2;$i++)
  299.         if(!mysql_board_call("INSERT IGNORE INTO rebuildqueue (board,no) VALUES ('$board','$no')"))
  300.             rebuildqueue_create_table();
  301.         else
  302.             break;
  303. }
  304.  
  305. function rebuildqueue_remove($no) {
  306.     $board = BOARD_DIR;
  307.     $no = (int)$no;
  308.     for($i=0;$i<2;$i++)
  309.         if(!mysql_board_call("DELETE FROM rebuildqueue WHERE board='$board' AND no='$no'"))
  310.             rebuildqueue_create_table();
  311.         else
  312.             break;
  313. }
  314.  
  315. function rebuildqueue_take_all() {
  316.     $board = BOARD_DIR;
  317.     $uid = mt_rand(1, mt_getrandmax());
  318.     for($i=0;$i<2;$i++)
  319.         if(!mysql_board_call("UPDATE rebuildqueue SET ownedby=$uid,ts=ts WHERE board='$board' AND ownedby=0"))
  320.             rebuildqueue_create_table();
  321.         else
  322.             break;
  323.     $q = mysql_board_call("SELECT no FROM rebuildqueue WHERE board='$board' AND ownedby=$uid");
  324.     $posts = array();
  325.     while($post=mysql_fetch_assoc($q))
  326.         $posts[] = $post['no'];
  327.     return $posts;
  328. }
  329.  
  330. function iplog_add($board, $no, $ip) {
  331.     $board = mysql_real_escape_string($board);
  332.     $no = (int)$no;
  333.     $ip = mysql_real_escape_string($ip);
  334.     mysql_board_call("INSERT INTO iplog (board,no,ip) VALUES ('$board',$no,'$ip')");
  335. }
  336. // build a structure out of all the posts in the database.
  337. // this lets us replace a LOT of queries with a simple array access.
  338. // it only builds the first time it was called.
  339. // rather than calling log_cache(1) to rebuild everything,
  340. // you should just manipulate the structure directly.
  341. function log_cache($invalidate=0) {
  342.     global $log, $ipcount, $mysql_unbuffered_reads, $lastno;
  343.     $ips = array();
  344.     $threads = array(); // no's
  345.     if($invalidate==0 && isset($log)) return;
  346.     $log = array(); // no -> [ data ]
  347.     mysql_board_call("SET read_buffer_size=1048576");
  348.     $mysql_unbuffered_reads = 1;
  349.     $query = mysql_board_call("SELECT * FROM ".SQLLOG);
  350.     $offset = 0;
  351.     $lastno = 0;
  352.     while($row = mysql_fetch_assoc($query)) {
  353.         if($row['no'] > $lastno) $lastno = $row['no'];
  354.         $ips[$row['host']] = 1;
  355.         // initialize log row if necessary
  356.         if( !isset($log[$row['no']]) ) {
  357.             $log[$row['no']] = $row;
  358.             $log[$row['no']]['children'] = array();
  359.         } else { // otherwise merge it with $row
  360.             foreach($row as $key=>$val)
  361.                 $log[$row['no']][$key] = $val;
  362.         }
  363.         // if this is a reply
  364.         if($row['resto']) {
  365.             // initialize whatever we need to
  366.             if( !isset($log[$row['resto']]) )
  367.                 $log[$row['resto']] = array();
  368.             if( !isset($log[$row['resto']]['children']) )
  369.                 $log[$row['resto']]['children'] = array();
  370.                
  371.             // add this post to list of children
  372.             $log[$row['resto']]['children'][$row['no']] = 1;
  373.             if($row['fsize']) {
  374.                 if(!isset($log[$row['resto']]['imgreplycount']))
  375.                     $log[$row['resto']]['imgreplycount'] = 0;
  376.                 else
  377.                     $log[$row['resto']]['imgreplycount']++;
  378.             }
  379.         } /*else {
  380.             $threads[] = $row['no'];
  381.         }*/
  382.     }
  383.    
  384.     $query = mysql_board_call("SELECT no FROM ".SQLLOG." WHERE root>0 order by root desc");
  385.     while($row = mysql_fetch_assoc($query)) {
  386.         if(isset($log[$row['no']]) && $log[$row['no']]['resto']==0)
  387.             $threads[] = $row['no'];
  388.     }
  389.     $log['THREADS'] = $threads;
  390.     $mysql_unbuffered_reads = 0;
  391.    
  392.     // calculate old-status for PAGE_MAX mode
  393.     if(EXPIRE_NEGLECTED != 1) {
  394.         rsort($threads, SORT_NUMERIC);
  395.    
  396.         $threadcount = count($threads);
  397.         if(PAGE_MAX > 0) // the lowest 5% of maximum threads get marked old
  398.             for($i = floor(0.95*PAGE_MAX*PAGE_DEF); $i < $threadcount; $i++) {
  399.                 if(!$log[$threads[$i]]['sticky'] && EXPIRE_NEGLECTED != 1)
  400.                     $log[$threads[$i]]['old'] = 1;
  401.             }
  402.         else { // threads w/numbers below 5% of LOG_MAX get marked old
  403.             foreach($threads as $thread) {
  404.                 if($lastno-LOG_MAX*0.95>$thread)
  405.                     if(!$log[$thread]['sticky'])
  406.                         $log[$thread]['old'] = 1;              
  407.             }
  408.         }
  409.     }
  410.    
  411.     $ipcount = count($ips);
  412. }
  413.  
  414.  
  415. // deletes a post from the database
  416. // imgonly: whether to just delete the file or to delete from the database as well
  417. // automatic: always delete regardless of password/admin (for self-pruning)
  418. // children: whether to delete just the parent post of a thread or also delete the children
  419. // die: whether to die on error
  420. // careful, setting children to 0 could leave orphaned posts.
  421. function delete_post($resno, $pwd, $imgonly=0, $automatic=0, $children=1, $die=1) {
  422.     global $log, $path;
  423.     log_cache();
  424.     $resno = intval($resno);
  425.  
  426.     // get post info
  427.     if(!isset($log[$resno])){if ($die) error("Can't find the post $resno.");}
  428.     $row=$log[$resno];
  429.    
  430.     // check password- if not ok, check admin status (and set $admindel if allowed)
  431.     $delete_ok = ( $automatic || (substr(md5($pwd),2,8) == $row['pwd']) || ($row['host'] == $_SERVER['REMOTE_ADDR']) );
  432.     if( ($pwd==ADMIN_PASS || $pwd==ADMIN_PASS2) ) { $delete_ok = $admindel = valid('delete', $resno); }
  433.     if(!$delete_ok) error(S_BADDELPASS);
  434.  
  435.     // check ghost bumping
  436.     if(!isset($admindel) || !$admindel) {
  437.         if(BOARD_DIR == 'a' && (int)$row['time'] > (time() - 25) && $row['email'] != 'sage') {
  438.             $ghostdump = var_export(array(
  439.                 'server'=>$_SERVER,
  440.                 'post'=>$_POST,
  441.                 'cookie'=>$_COOKIE,
  442.                 'row'=>$row),true);
  443.             //file_put_contents('ghostbump.'.time(),$ghostdump);
  444.         }
  445.     }
  446.  
  447.     if(isset($admindel) && $admindel) { // extra actions for admin user
  448.         $auser = mysql_escape_string($_COOKIE['4chan_auser']);
  449.         $adfsize=($row['fsize']>0)?1:0;
  450.         $adname=str_replace('</span> <span class="postertrip">!','#',$row['name']);
  451.         if($imgonly) { $imgonly=1; } else { $imgonly=0; }
  452.         $row['sub'] = mysql_escape_string($row['sub']);
  453.         $row['com'] = mysql_escape_string($row['com']);
  454.         $row['filename'] = mysql_escape_string($row['filename']);
  455.         mysql_global_do("INSERT INTO ".SQLLOGDEL." (imgonly,postno,board,name,sub,com,img,filename,admin) values('$imgonly','$resno','".SQLLOG."','$adname','{$row['sub']}','{$row['com']}','$adfsize','{$row['filename']}','$auser')");   
  456.     }
  457.    
  458.     if($row['resto']==0 && $children && !$imgonly) // select thread and children
  459.         $result=mysql_board_call("select no,resto,tim,ext from ".SQLLOG." where no=$resno or resto=$resno");
  460.     else // just select the post
  461.         $result=mysql_board_call("select no,resto,tim,ext from ".SQLLOG." where no=$resno");
  462.    
  463.     while($delrow=mysql_fetch_array($result)) {
  464.         // delete
  465.         $delfile = $path.$delrow['tim'].$delrow['ext']; //path to delete
  466.         $delthumb = THUMB_DIR.$delrow['tim'].'s.jpg';
  467.         if(is_file($delfile)) unlink($delfile); // delete image
  468.         if(is_file($delthumb)) unlink($delthumb); // delete thumb
  469.         if(OEKAKI_BOARD == 1 && is_file($path.$delrow['tim'].'.pch'))
  470.             unlink($path.$delrow['tim'].'.pch'); // delete oe animation
  471.         if(!$imgonly){ // delete thread page & log_cache row
  472.             if($delrow['resto'])
  473.                 unset( $log[$delrow['resto']]['children'][$delrow['no']] );
  474.             unset( $log[$delrow['no']] );
  475.             $log['THREADS'] = array_diff($log['THREADS'], array($delrow['no'])); // remove from THREADS
  476.             mysql_global_do("DELETE FROM reports WHERE no=".$delrow['no']); // clear reports
  477.             if(USE_GZIP == 1) {
  478.                 @unlink(RES_DIR.$delrow['no'].PHP_EXT);
  479.                 @unlink(RES_DIR.$delrow['no'].PHP_EXT.'.gz');
  480.             }
  481.             else {
  482.                 @unlink(RES_DIR.$delrow['no'].PHP_EXT);
  483.             }
  484.         }
  485.     }
  486.  
  487.     //delete from DB
  488.     if($row['resto']==0 && $children && !$imgonly) // delete thread and children
  489.         $result=mysql_board_call("delete from ".SQLLOG." where no=$resno or resto=$resno");
  490.     elseif(!$imgonly) // just delete the post
  491.         $result=mysql_board_call("delete from ".SQLLOG." where no=$resno");
  492.            
  493.     return $row['resto']; // so the caller can know what pages need to be rebuilt
  494. }
  495.  
  496. // purge old posts
  497. // should be called whenever a new post is added.
  498. function trim_db() {
  499.     if(JANITOR_BOARD == 1) return;
  500.    
  501.     log_cache();
  502.    
  503.     $maxposts = LOG_MAX;
  504.     // max threads = max pages times threads-per-page
  505.     $maxthreads = (PAGE_MAX > 0)?(PAGE_MAX * PAGE_DEF):0;
  506.    
  507.     // New max-page method
  508.     if($maxthreads) {
  509.         $exp_order = 'no';
  510.         if(EXPIRE_NEGLECTED == 1) $exp_order = 'root';
  511.         logtime('trim_db before select threads');
  512.         $result = mysql_board_call("SELECT no FROM ".SQLLOG." WHERE sticky=0 AND resto=0 ORDER BY $exp_order ASC");
  513.         logtime('trim_db after select threads');
  514.         $threadcount = mysql_num_rows($result);
  515.         while($row=mysql_fetch_array($result) and $threadcount >= $maxthreads) {
  516.             delete_post($row['no'], 'trim', 0, 1); // imgonly=0, automatic=1, children=1
  517.             $threadcount--;
  518.         }
  519.         mysql_free_result($result);
  520.     // Original max-posts method (note: cleans orphaned posts later than parent posts)
  521.     } else {
  522.         // make list of stickies
  523.         $stickies = array(); // keys are stickied thread numbers
  524.         $result = mysql_board_call("SELECT no from ".SQLLOG." where sticky=1 and resto=0");
  525.         while($row=mysql_fetch_array($result)) {
  526.             $stickies[ $row['no'] ] = 1;
  527.         }
  528.        
  529.         $result = mysql_board_call("SELECT no,resto,sticky FROM ".SQLLOG." ORDER BY no ASC");
  530.         $postcount = mysql_num_rows($result);
  531.         while($row=mysql_fetch_array($result) and $postcount >= $maxposts) {
  532.             // don't delete if this is a sticky thread
  533.             if($row['sticky'] == 1) continue;
  534.             // don't delete if this is a REPLY to a sticky
  535.             if($row['resto'] != 0 && $stickies[ $row['resto'] ] == 1) continue;
  536.             delete_post($row['no'], 'trim', 0, 1, 0); // imgonly=0, automatic=1, children=0
  537.             $postcount--;
  538.         }
  539.         mysql_free_result($result);
  540.     }
  541.  
  542. }
  543.  
  544. //resno - thread page to update (no of thread OP)
  545. //rebuild - don't rebuild page indexes
  546. function updatelog($resno=0,$rebuild=0){
  547.   global $log,$path;
  548.     set_time_limit(60);
  549. if($_SERVER['REQUEST_METHOD']=='GET' && !valid()) die(''); // anti ddos
  550.     log_cache();
  551.    
  552.       $imgdir = ((USE_SRC_CGI==1)?str_replace('src','src.cgi',IMG_DIR2):IMG_DIR2);
  553.     if(defined('INTERSTITIAL_LINK')) $imgdir .= INTERSTITIAL_LINK;
  554.       $thumbdir = THUMB_DIR2;
  555.         $imgurl = DATA_SERVER;
  556.  
  557.  
  558.   $resno=(int)$resno;
  559.   if($resno){
  560.     if(!isset($log[$resno])) {
  561.         updatelog(0,$rebuild); // the post didn't exist, just rebuild the indexes
  562.         return;
  563.     }
  564.     else if($log[$resno]['resto']) {
  565.             updatelog($log[$resno]['resto'],$rebuild); // $resno is a reply, try rebuilding the parent
  566.             return;
  567.         }
  568.   }
  569.  
  570.   if($resno){
  571.     $treeline = array($resno); logtime("Formatting thread page");
  572.     //if(!$treeline=mysql_board_call("select * from ".SQLLOG." where root>0 and no=".$resno." order by root desc")){echo S_SQLFAIL;}
  573.   }else{
  574.     $treeline = $log['THREADS']; logtime("Formatting index page");
  575.     //if(!$treeline=mysql_board_call("select * from ".SQLLOG." where root>0 order by root desc")){echo S_SQLFAIL;}
  576.   }
  577.  
  578.  
  579.     $counttree=count($treeline);
  580.   //$counttree=mysql_num_rows($treeline);
  581.   if(!$counttree){
  582.     $logfilename=PHP_SELF2;
  583.     $dat='';
  584.     head($dat,$resno);
  585.     form($dat,$resno);
  586.     print_page($logfilename, $dat);
  587.   }
  588.  
  589.     if(UPDATE_THROTTLING >= 1) {
  590.       $update_start = time();
  591.       touch("updatelog.stamp", $update_start);
  592.       $low_priority = false;
  593.       clearstatcache();
  594.       if(@filemtime(PHP_SELF) > $update_start-UPDATE_THROTTLING) {
  595.         $low_priority = true;
  596.         //touch($update_start . ".lowprio");
  597.       }
  598.       else {
  599.         touch(PHP_SELF,$update_start);
  600.       }
  601.      //     $mt = @filemtime(PHP_SELF);
  602.     //      touch($update_start . ".$mt.highprio");
  603.     }
  604.    
  605.     // if we're using CACHE_TTL method
  606.     if(CACHE_TTL >= 1) {
  607.         if($resno) {
  608.             $logfilename = RES_DIR.$resno.PHP_EXT;
  609.         }
  610.         else {
  611.             $logfilename = PHP_SELF2;
  612.         }
  613.         //if(USE_GZIP == 1) $logfilename .= '.html';
  614.         // if the file has been made and it's younger than CACHE_TTL seconds ago
  615.         clearstatcache();
  616.         if(file_exists($logfilename) && filemtime($logfilename) > (time() - CACHE_TTL)) {
  617.             // save the post to be rebuilt later
  618.             rebuildqueue_add($resno);
  619.             // if it's a thread, try again on the indexes
  620.             if($resno && !$rebuild) updatelog();
  621.             // and we don't do any more rebuilding on this request
  622.             return true;
  623.         }
  624.         else {
  625.             // we're gonna update it now, so take it out of the queue
  626.             rebuildqueue_remove($resno);
  627.             // and make sure nobody else starts trying to update it because it's too old
  628.             touch($logfilename);
  629.         }          
  630.     }
  631.  
  632.   for($page=0;$page<$counttree;$page+=PAGE_DEF){
  633.     $dat='';
  634.     head($dat,$resno);
  635.     form($dat,$resno);
  636.     if(!$resno){
  637.       $st = $page;
  638.     }
  639.     $dat.='<form name="delform" action="';
  640.     $dat.=PHP_SELF_ABS.'" method=POST>';
  641.  
  642.   for($i = $st; $i < $st+PAGE_DEF; $i++){
  643.     if(UPDATE_THROTTLING >= 1) {
  644.         clearstatcache();
  645.         if($low_priority && @filemtime("updatelog.stamp") > $update_start) {
  646.                 //touch($update_start . ".throttled");
  647.                 return;
  648.         }
  649.         if(rand(0,15)==0) return;
  650.      }
  651.    
  652.     list($_unused,$no) = each($treeline);
  653.     //list($no,$sticky,$permasage,$closed,$now,$name,$email,$sub,$com,$host,$pwd,$filename,$ext,$w,$h,$tn_w,$tn_h,$tim,$time,$md5,$fsize,$root,$resto)=mysql_fetch_row($treeline);
  654.     if(!$no){break;}
  655.     extract($log[$no]);
  656.     //if(!$resno&&!file_exists(RES_DIR.$no.PHP_EXT)) { updatelog($no); break; } // uhh
  657.  
  658.     //POST FILTERING
  659.     if(JANITOR_BOARD == 1) {
  660.         $name = broomcloset_capcode($name);
  661.     }
  662.         if($email) $name = "<a href=\"mailto:$email\" class=\"linkmail\">$name</a>";
  663.     if(strpos($sub,"SPOILER<>")===0) {
  664.         $sub = substr($sub,strlen("SPOILER<>")); //trim out SPOILER<>
  665.         $spoiler = 1;
  666.     } else $spoiler = 0;
  667.     $com = auto_link($com,$resno);
  668.     if(!$resno) list($com,$abbreviated) = abbreviate($com, MAX_LINES_SHOWN);
  669.  
  670.       if(isset($abbreviated) && $abbreviated) $com .= "<br /><span class=\"abbr\">Comment too long. Click <a href=\"".RES_DIR.($resto?$resto:$no).PHP_EXT."#$no\">here</a> to view the full text.</span>";
  671.     // Picture file name
  672.     $img = $path.$tim.$ext;
  673.     $displaysrc = $imgdir.$tim.$ext;
  674.     $linksrc = ((USE_SRC_CGI==1)?(str_replace(".cgi","",$imgdir).$tim.$ext):$displaysrc);
  675.     if(defined('INTERSTITIAL_LINK')) $linksrc = str_replace(INTERSTITIAL_LINK,"",$linksrc);
  676.     $src = IMG_DIR.$tim.$ext;
  677.     $longname = $filename.$ext;
  678.     if (strlen($filename)>40) {
  679.         $shortname = substr($filename, 0, 40)."(...)".$ext;
  680.     } else {
  681.         $shortname = $longname;
  682.     }
  683.     // img tag creation
  684.     $imgsrc = "";
  685.     if($ext){
  686.         // turn the 32-byte ascii md5 into a 24-byte base64 md5
  687.         $shortmd5 = base64_encode(pack("H*", $md5));
  688.       if ($fsize >= 1048576) { $size = round(($fsize/1048576),2)." M";
  689.       } else if ($fsize >= 1024) { $size = round($fsize/1024)." K";
  690.       } else { $size = $fsize." "; }
  691.       if(!$tn_w && !$tn_h && $ext==".gif"){
  692.         $tn_w=$w;
  693.         $tn_h=$h;
  694.       }
  695.                   if($spoiler) {
  696.               $size= "Spoiler Image, $size";
  697.                   $imgsrc = "<br><a href=\"".$displaysrc."\" target=_blank><img src=\"".SPOILER_THUMB."\" border=0 align=left hspace=20 alt=\"".$size."B\" md5=\"$shortmd5\"></a>";          
  698.               } elseif($tn_w && $tn_h){//when there is size...
  699.         if(@is_file(THUMB_DIR.$tim.'s.jpg')){
  700.           $imgsrc = "<br><a href=\"".$displaysrc."\" target=_blank><img src=".$thumbdir.$tim.'s.jpg'." border=0 align=left width=$tn_w height=$tn_h hspace=20 alt=\"".$size."B\" md5=\"$shortmd5\"></a>";
  701.         }else{
  702.           $imgsrc = "<a href=\"".$displaysrc."\" target=_blank><span class=\"tn_thread\" title=\"".$size."B\">Thumbnail unavailable</span></a>";
  703.         }
  704.       }else{
  705.         if(@is_file(THUMB_DIR.$tim.'s.jpg')){
  706.           $imgsrc = "<br><a href=\"".$displaysrc."\" target=_blank><img src=".$thumbdir.$tim.'s.jpg'." border=0 align=left hspace=20 alt=\"".$size."B\" md5=\"$shortmd5\"></a>";
  707.         }else{
  708.           $imgsrc = "<a href=\"".$displaysrc."\" target=_blank><span class=\"tn_thread\" title=\"".$size."B\">Thumbnail unavailable</span></a>";
  709.         }
  710.       }
  711.       if (!is_file($src)) {
  712.           $dat.='<img src="'.$imgurl.'filedeleted.gif" alt="File deleted.">';
  713.       } else {
  714.         $dimensions=($ext=='.pdf')?'PDF':"{$w}x{$h}";
  715.         if ($resno) {
  716.           $dat.="<span class=\"filesize\">".S_PICNAME."<a href=\"$linksrc\" target=\"_blank\">$time$ext</a>-(".$size."B, ".$dimensions.", <span title=\"".$longname."\">".$shortname."</span>)</span>".$imgsrc;
  717.                 } else {
  718.               $dat.="<span class=\"filesize\">".S_PICNAME."<a href=\"$linksrc\" target=\"_blank\">$time$ext</a>-(".$size."B, ".$dimensions.")</span>".$imgsrc;
  719.         }
  720.       }
  721.     }
  722.     //  Main creation
  723.     $dat.="<a name=\"$resno\"></a>\n<input type=checkbox name=\"$no\" value=delete><span class=\"filetitle\">$sub</span> \n";
  724.     $dat.="<span class=\"postername\">$name</span> $now <span id=\"nothread$no\">";
  725.  
  726.     if($sticky==1) {
  727.         $stickyicon=' <img src="'.$imgurl.'sticky.gif" alt="sticky"> ';
  728.     } else { $stickyicon=""; }
  729.     if($closed==1) {
  730.         $stickyicon .= ' <img src="'.$imgurl.'closed.gif" alt="closed"> ';
  731.     }
  732.    
  733.     if(PARTY==1) {
  734.         $dat .= "<img src='http://img.4chan.org/xmashat.gif' style='position:absolute;margin-top:-100px;left:0px;'>";
  735.     }
  736.        
  737.     if($resno) {
  738.         $dat.="<a href=\"#$no\" class=\"quotejs\">No.</a><a href=\"javascript:quote('$no')\" class=\"quotejs\">$no</a> $stickyicon &nbsp; ";
  739.     } else {
  740.         $dat.="<a href=\"".RES_DIR.$no.PHP_EXT."#".$no."\" class=\"quotejs\">No.</a><a href=\"".RES_DIR.$no.PHP_EXT."#q".$no."\" class=\"quotejs\">$no</a> $stickyicon &nbsp; [<a href=\"".RES_DIR.$no.PHP_EXT."\">".S_REPLY."</a>]";
  741.     }
  742.     $dat.="</span>\n<blockquote>$com</blockquote>";
  743.  
  744.      // Deletion pending
  745.       if(isset($log[$no]['old'])) $dat.="<span class=\"oldpost\">".S_OLD."</span><br>\n";
  746.  
  747.     $resline = $log[$no]['children'];
  748.     ksort($resline);
  749.     $countres=count($log[$no]['children']);
  750.     $t=0;
  751.     if($sticky==1) {
  752.         $disam=1;
  753.     } elseif(defined('REPLIES_SHOWN')) {
  754.         $disam=REPLIES_SHOWN;
  755.     } else {
  756.         $disam=5;
  757.     }
  758.     $s=$countres - $disam;
  759.       $cur=1;
  760.       while ($s >= $cur) {
  761.         list($row) = each($resline);
  762.       if($log[$row]["fsize"]!=0) { $t++; }
  763.         $cur++;
  764.         }
  765.     if ($countres!=0) reset($resline);
  766.  
  767.     if(!$resno){
  768.     if ($s<2) { $posts=" post"; } else { $posts=" posts"; }
  769.     if ($t<2) { $replies="reply"; } else { $replies="replies"; }
  770.      if(($s>0)&&($t==0)){
  771.       $dat.="<span class=\"omittedposts\">".$s.$posts." omitted. Click Reply to view.</span>\n";
  772.      } elseif (($s>0)&&($t>0)) {
  773.       $dat.="<span class=\"omittedposts\">".$s.$posts." and ".$t." image ".$replies." omitted. Click Reply to view.</span>\n";
  774.      }
  775.     }else{$s=0;}
  776.    
  777.     while(list($resrow)=each($resline)){
  778.       if($s>0){$s--;continue;}
  779.       //list($no,$sticky,$permasage,$closed,$now,$name,$email,$sub,$com,$host,$pwd,$filename,$ext,$w,$h,$tn_w,$tn_h,$tim,$time,$md5,$fsize,$root,$resto)=$resrow;
  780.       extract($log[$resrow]);
  781.       if(!$no){break;}
  782.  
  783.     //POST FILTERING
  784.     if(JANITOR_BOARD == 1) {
  785.         $name = broomcloset_capcode($name);
  786.     }
  787.         if($email) $name = "<a href=\"mailto:$email\" class=\"linkmail\">$name</a>";
  788.     if(strpos($sub,"SPOILER<>")===0) {
  789.         $sub = substr($sub,strlen("SPOILER<>")); //trim out SPOILER<>
  790.         $spoiler = 1;
  791.     } else $spoiler = 0;
  792.     $com = auto_link($com,$resno);
  793.     if(!$resno) list($com,$abbreviated) = abbreviate($com, MAX_LINES_SHOWN);
  794.  
  795.       if(isset($abbreviated)&&$abbreviated) $com .= "<br /><span class=\"abbr\">Comment too long. Click <a href=\"".RES_DIR.($resto?$resto:$no).PHP_EXT."#$no\">here</a> to view the full text.</span>";
  796.      
  797.             // Picture file name
  798.             $r_img = $path.$tim.$ext;
  799.             $r_displaysrc = $imgdir.$tim.$ext;
  800.             $r_linksrc = ((USE_SRC_CGI==1)?(str_replace(".cgi","",$imgdir).$tim.$ext):$r_displaysrc);
  801.     if(defined('INTERSTITIAL_LINK')) $r_linksrc = str_replace(INTERSTITIAL_LINK,"",$r_linksrc);
  802.             $r_src = IMG_DIR.$tim.$ext;
  803.             $longname = $filename.$ext;
  804.             if (strlen($filename)>30) {
  805.               $shortname = substr($filename, 0, 30)."(...)".$ext;
  806.             } else {
  807.               $shortname = $longname;
  808.             }
  809.             // img tag creation
  810.             $r_imgsrc = "";
  811.             if($ext){
  812.                     // turn the 32-byte ascii md5 into a 24-byte base64 md5
  813.             $shortmd5 = base64_encode(pack("H*", $md5));
  814.           if ($fsize >= 1048576) { $size = round(($fsize/1048576),2)." M";
  815.           } else if ($fsize >= 1024) { $size = round($fsize/1024)." K";
  816.           } else { $size = $fsize." "; }
  817.               if(!$tn_w && !$tn_h && $ext==".gif"){
  818.                 $tn_w=$w;
  819.                 $tn_h=$h;
  820.               }
  821.               if($spoiler) {
  822.               $size= "Spoiler Image, $size";
  823.                   $r_imgsrc = "<br><a href=\"".$r_displaysrc."\" target=_blank><img src=\"".SPOILER_THUMB."\" border=0 align=left hspace=20 alt=\"".$size."B\" md5=\"$shortmd5\"></a>";          
  824.               }
  825.               elseif($tn_w && $tn_h){//when there is size...
  826.                 if(@is_file(THUMB_DIR.$tim.'s.jpg')){
  827.                   $r_imgsrc = "<br><a href=\"".$r_displaysrc."\" target=_blank><img src=".$thumbdir.$tim.'s.jpg'." border=0 align=left width=$tn_w height=$tn_h hspace=20 alt=\"".$size."B\" md5=\"$shortmd5\"></a>";
  828.                 }else{
  829.                   $r_imgsrc = "<a href=\"".$r_displaysrc."\" target=_blank><span class=\"tn_reply\" title=\"".$size."B\">Thumbnail unavailable</span></a>";
  830.                 }
  831.               }else{
  832.                 if(@is_file(THUMB_DIR.$tim.'s.jpg')){
  833.                   $r_imgsrc = "<br><a href=\"".$r_displaysrc."\" target=_blank><img src=".$thumbdir.$tim.'s.jpg'." border=0 align=left hspace=20 alt=\"".$size."B\" md5=\"$shortmd5\"></a>";
  834.                 }else{
  835.                   $r_imgsrc = "<a href=\"".$r_displaysrc."\" target=_blank><span class=\"tn_reply\" title=\"".$size."B\">Thumbnail unavailable</span></a>";
  836.                 }
  837.               }
  838.               if (!is_file($r_src)) {
  839.                 $r_imgreply='<br><img src="'.$imgurl.'filedeleted-res.gif" alt="File deleted.">';
  840.               } else {
  841.                 $dimensions=($ext=='.pdf')?'PDF':"{$w}x{$h}";
  842.                 if ($resno) {
  843.                     $r_imgreply="<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"filesize\">".S_PICNAME."<a href=\"$r_linksrc\" target=\"_blank\">$time$ext</a>-(".$size."B, ".$dimensions.", <span title=\"".$longname."\">".$shortname."</span>)</span>".$r_imgsrc;
  844.                             } else {
  845.                     $r_imgreply="<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"filesize\">".S_PICNAME."<a href=\"$r_linksrc\" target=\"_blank\">$time$ext</a>-(".$size."B, ".$dimensions.")</span>".$r_imgsrc;
  846.               }
  847.               }
  848.             }
  849.            
  850.       // Main Reply creation
  851.       $dat.="<a name=\"$no\"></a>\n";
  852.             $dat.="<table><tr><td nowrap class=\"doubledash\">&gt;&gt;</td><td id=\"$no\" class=\"reply\">\n";
  853. //      if (($t>3)&&($fsize!=0)) {
  854. //      $dat.="&nbsp;&nbsp;&nbsp;<b>Image hidden</b>&nbsp;&nbsp; $now No.$no \n";
  855. //          } else {
  856.       $dat.="<input type=checkbox name=\"$no\" value=delete><span class=\"replytitle\">$sub</span> \n";
  857.       $dat.="<span class=\"commentpostername\">$name</span> $now <span id=\"norep$no\">";
  858.       if($resno) {
  859.         $dat.="<a href=\"#$no\" class=\"quotejs\">No.</a><a href=\"javascript:quote('$no')\" class=\"quotejs\">$no</a></span>";
  860.       } else {
  861.         $dat.="<a href=\"".RES_DIR.$resto.PHP_EXT."#$no\" class=\"quotejs\">No.</a><a href=\"".RES_DIR.$resto.PHP_EXT."#q$no\" class=\"quotejs\">$no</a></span>";
  862.       }
  863.       if(isset($r_imgreply)) $dat.=$r_imgreply;
  864.       $dat.="<blockquote>$com</blockquote>";
  865. //      }
  866.       $dat.="</td></tr></table>\n";
  867.         unset($r_imgreply);
  868.     }
  869.     $dat.="<br clear=left><hr>\n";
  870.     clearstatcache();//clear stat cache of a file
  871.     //mysql_free_result($resline);
  872.     $p++;
  873.     if($resno){break;} //only one tree line at time of res
  874.   }
  875.     // bottom of a page
  876.     if(BOTTOM_AD == 1) {
  877.         $bottomad = "";
  878.        
  879.         if (defined("BOTTOM_TXT") && BOTTOM_TXT) {
  880.             $bottomad .= ad_text_for(BOTTOM_TXT);
  881.         }
  882.        
  883.         if (defined("BOTTOM_TABLE") && BOTTOM_TABLE) {
  884.             list($bottomimg,$bottomlink) = rid(BOTTOM_TABLE,1);
  885.             $bottomad .= "<center><a href=\"$bottomlink\" target=\"_blank\"><img style=\"border:1px solid black;\" src=\"$bottomimg\" width=728 height=90 border=0 /></a></center>";
  886.         }
  887.        
  888.         if($bottomad)
  889.             $dat .= "$bottomad<hr>";
  890.     }
  891.        
  892. $dat.='<table align=right><tr><td nowrap align=center class=deletebuttons>
  893. <input type=hidden name=mode value=usrdel>'.S_REPDEL.' [<input class=checkbox type=checkbox name=onlyimgdel value=on>'.S_DELPICONLY.']<br>
  894. '.S_DELKEY.' <input class=inputtext type=password name="pwd" size=8 maxlength=8 value="">
  895. <input type=submit value="'.S_DELETE.'"><input type="button" value="Report" onclick="var o=document.getElementsByTagName(\'INPUT\');for(var i=0;i<o.length;i++)if(o[i].type==\'checkbox\' && o[i].checked && o[i].value==\'delete\') return reppop(\''.PHP_SELF_ABS.'?mode=report&no=\'+o[i].name+\'\');"></form><script>document.delform.pwd.value=get_pass("4chan_pass");</script></td></tr>';
  896. if (strpos($_SERVER['SERVER_NAME'],".4chan.org")) {
  897.     $dat.='<tr><td align="right">Style [';
  898.     $dat.='<a href="#" onclick="setActiveStyleSheet(\'Yotsuba\'); return false;">Yotsuba</a> | ';
  899.     $dat.='<a href="#" onclick="setActiveStyleSheet(\'Yotsuba B\'); return false;">Yotsuba B</a> | ';
  900.     $dat.='<a href="#" onclick="setActiveStyleSheet(\'Futaba\'); return false;">Futaba</a> | ';
  901.     $dat.='<a href="#" onclick="setActiveStyleSheet(\'Burichan\'); return false;">Burichan</a>]</td></tr>';
  902. }
  903. $dat.='</table>';
  904.  
  905.     if(!$resno){ // if not in res display mode
  906.       $prev = $st - PAGE_DEF;
  907.       $next = $st + PAGE_DEF;
  908.     // Page navigation
  909.       $dat.="<table class=pages align=left border=1><tr>";
  910.       if($prev >= 0){ //ok to make prev button
  911.         if($prev==0){
  912.           $dat.="<form action=\"".PHP_SELF2."\" onsubmit='location=this.action;return false;' method=get><td>";
  913.         }else{
  914.           $dat.="<form action=\"".$prev/PAGE_DEF.PHP_EXT."\" onsubmit='location=this.action;return false;' method=get><td>";
  915.         }
  916.         $dat.="<input type=submit value=\"".S_PREV."\" accesskey=\"z\">";
  917.         $dat.="</td></form>";
  918.       }else{$dat.="<td>".S_FIRSTPG."</td>";}
  919.         // page listing
  920.       $dat.="<td>";
  921.       for($i = 0; $i < $counttree ; $i+=PAGE_DEF){
  922.         if( !(PAGE_MAX > 0) )
  923.             if($i&&!($i%(PAGE_DEF*10))){$dat.="<br>";} // linebreak every 10 pages
  924.         if($st==$i){$dat.="[<b>".($i/PAGE_DEF)."</b>] ";} // don't link current page
  925.         else{
  926.           if($i==0){$dat.="[<a href=\"".PHP_SELF2."\">0</a>] ";}
  927.           else{$dat.="[<a href=\"".($i/PAGE_DEF).PHP_EXT."\">".($i/PAGE_DEF)."</a>] ";}
  928.         }
  929.       }
  930.       // continue printing up to PAGE_MAX if we're using that mode... this should rarely happen
  931.       for(; (PAGE_MAX > 0) && $i < PAGE_MAX*PAGE_DEF; $i+=PAGE_DEF) {
  932.         $dat.="[".($i/PAGE_DEF)."] ";
  933.       }
  934.      
  935.       $dat.="</td>";
  936.  
  937.       if($p >= PAGE_DEF && $counttree > $next){ // ok to make next button
  938.         $dat.="<form action=\"".$next/PAGE_DEF.PHP_EXT."\" onsubmit='location=this.action;return false' method=get><td>";
  939.         $dat.="<input type=submit value=\"".S_NEXT."\" accesskey=\"x\">";
  940.         $dat.="</td></form>";
  941.       }else{$dat.="<td>".S_LASTPG."</td>";}
  942.         $dat.="</tr></table><br clear=all>\n";
  943.     }
  944.     foot($dat);
  945.     //if($resno){echo $dat;break;}
  946.     if($resno) {
  947.         logtime("Printing thread $resno page");
  948.         $logfilename=RES_DIR.$resno.PHP_EXT;
  949.         print_page($logfilename, $dat);
  950.         $dat='';
  951.       if(!$rebuild) $deferred = updatelog(0);
  952.       break;
  953.     }
  954.     logtime("Printing index page");
  955.     if($page==0){$logfilename=PHP_SELF2;}
  956.     else{$logfilename=$page/PAGE_DEF.PHP_EXT;}
  957.     print_page($logfilename, $dat);
  958.     if(!$resno && $page==0 && USE_RSS==1) {
  959.         include_once '/www/global/rss.php';
  960.         rss_dump();
  961.     }
  962.     if(UPDATE_THROTTLING >= 1) {
  963.         clearstatcache();
  964.         if(@filemtime("updatelog.stamp") == $update_start)
  965.             unlink("updatelog.stamp");
  966.     }
  967.     //chmod($logfilename,0666);
  968.   }
  969.   //mysql_free_result($treeline);
  970.   if(isset($deferred)) return $deferred;
  971.   return false;
  972. }
  973.  
  974. /* head */
  975. function head(&$dat,$res,$error=0){
  976.     $titlepart = '';
  977.     if(JANITOR_BOARD == 1) {
  978.         $dat .= broomcloset_head($dat);
  979.     }
  980.  
  981.   if (SHOWTITLEIMG == 1) {
  982.         //$titleimg = rid('title_banners');
  983.       $titleimg = rid_in_directory("/dontblockthis/title/");
  984.       $titlepart.= '<img width=300 height=100 src="'.$titleimg.'">';
  985.     } else if (SHOWTITLEIMG == 2) {
  986.       $titlepart.= '<img width=300 height=100 src="'.TITLEIMG.'" onclick="this.src=this.src;">';
  987.     }
  988.   $include1=file_get_contents_cached(NAV_TXT);
  989.   $cookiejs="function get_cookie(name){with(document.cookie){var index=indexOf(name+\"=\");if(index==-1) return '';index=indexOf(\"=\",index)+1;var endstr=indexOf(\";\",index);if(endstr==-1) endstr=length;return decodeURIComponent(substring(index,endstr));}};\nfunction get_pass(name){var pass=get_cookie(name);if(pass) return pass;var chars=\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";var pass='';for(var i=0;i<8;i++){var rnd=Math.floor(Math.random()*chars.length);pass+=chars.substring(rnd,rnd+1);}return(pass);}\n";
  990.   $cookiejs .= 'function toggle(name){var a=document.getElementById(name); a.style.display = ((a.style.display!="block")?"block":"none");}';
  991.   $scriptjs = '';
  992.   // set styleswitcher script configuration variables
  993.   if(DEFAULT_BURICHAN==1) {
  994.     $scriptjs .= '<script type="text/javascript">var style_group="ws_style";</script>';
  995.   } else {
  996.     $scriptjs .= '<script type="text/javascript">var style_group="nws_style";</script>';
  997.   }
  998.     $scriptjs .='<script type="text/javascript" src="'.DATA_SERVER.'script.js"></script>';
  999.   $dat.='<html><head>
  1000. <META HTTP-EQUIV="content-type" CONTENT="text/html; charset=UTF-8">
  1001. <meta name="robots" content="'.META_ROBOTS.'"/>
  1002. <meta name="description" content="'.META_DESCRIPTION.'"/>
  1003. <meta name="keywords" content="'.META_KEYWORDS.'"/>';
  1004.     if (RTA==1) {
  1005.         $dat .= "\n<meta name=\"RATING\" content=\"RTA-5042-1996-1400-1577-RTA\" />";
  1006.     }
  1007. $styles = array(
  1008.     'Yotsuba' => 'yotsuba.8.css',
  1009.     'Yotsuba B' => 'yotsublue.8.css',
  1010.     'Futaba' => 'futaba.8.css',
  1011.     'Burichan' => 'burichan.8.css',
  1012. );
  1013.     if (DEFAULT_BURICHAN==1) {
  1014.         foreach($styles as $style=>$stylecss) {
  1015.             $rel = ( ($style == 'Yotsuba B') ? 'stylesheet' : 'alternate stylesheet' );
  1016.             $dat .= "<link rel=\"$rel\" type=\"text/css\" href=\"".DATA_SERVER."$stylecss\" title=\"$style\">";
  1017.         }
  1018.     } else {
  1019.         if(defined('CSS_FORCE')) {
  1020.             foreach($styles as $style=>$stylecss) {
  1021.                 $rel = ( ($style == 'Yotsuba') ? 'stylesheet' : 'alternate stylesheet' );
  1022.                 $dat .= "<link rel=\"$rel\" type=\"text/css\" href=\"".CSS_FORCE."\" title=\"$style\">";
  1023.             }
  1024.         }
  1025.         else {
  1026.             foreach($styles as $style=>$stylecss) {
  1027.                 $rel = ( ($style == 'Yotsuba') ? 'stylesheet' : 'alternate stylesheet' );
  1028.                 $dat .= "<link rel=\"$rel\" type=\"text/css\" href=\"".DATA_SERVER."$stylecss\" title=\"$style\">";
  1029.             }
  1030.         }
  1031.     }
  1032.  
  1033. if(USE_RSS==1)
  1034.     $dat .= '<link rel="alternate" title="RSS feed" href="/'.BOARD_DIR.'/index.rss" type="application/rss+xml" />';
  1035. $dat.='<title>'.strip_tags(TITLE).'</title>
  1036. <script type="text/javascript"><!--
  1037. '.$cookiejs.'
  1038. //--></script>
  1039. '.$scriptjs;
  1040.  
  1041. if (FIXED_TEXT_AD == 1 && file_exists(FIXED_TEXT_PATH)) {
  1042.     $dat.="<style>.postarea { padding-left:400px; }</style>";
  1043. }
  1044.  
  1045. $dat .= '</head>
  1046. <body bgcolor="#FFFFEE" text="#800000" link="#0000EE" vlink="#0000EE">'.$include1;
  1047.  
  1048. $dat.='<div class="logo">
  1049. '.$titlepart.'<br>
  1050. <font size=5>
  1051. <b><SPAN>'.TITLE.'</SPAN></b></font>';
  1052. if(defined('SUBTITLE'))
  1053.     $dat .= '<br><font size=1>'.SUBTITLE.'</font>';
  1054. $dat.='</div>
  1055. <hr width="90%" size=1>
  1056. ';
  1057. if(LEADERBOARD_AD == 1) {
  1058.         if(defined('LEADERBOARD_TXT') && LEADERBOARD_TXT) {
  1059.             $dat.='<div style="text-align: center">' .
  1060.                 ad_text_for(LEADERBOARD_TXT) .
  1061.             '</div><hr>';
  1062.         }
  1063.         else if(defined('LEADERBOARD_TABLE')) {
  1064.             list($ldimg,$ldhref) = rid(LEADERBOARD_TABLE,1);
  1065.             $dat.='<div style="text-align: center"><a href="'.$ldhref.'" target="_blank"><img src="'.$ldimg.'" border="0"></a></div><hr>';
  1066.         }
  1067.         else
  1068.             $dat.='<div style="text-align: center"><a href="'.LEADERBOARD_LINK.'" target="_blank"><img src="http://content.4chan.org/dontblockthis/'.LEADERBOARD_IMG.'" border="0"></a></div><hr>';
  1069. }
  1070. }
  1071.  
  1072. /* Contribution form */
  1073. function form(&$dat,$resno,$admin=""){
  1074.   global $log; log_cache();
  1075.   $maxbyte = MAX_KB * 1024;
  1076.   $no=$resno;
  1077.   $closed=0;
  1078.   $msg='';
  1079.   $hidden='';
  1080.   if($resno){
  1081.     $closed = $log[$resno]['closed'];
  1082.  
  1083.     $msg.="[<a href=\"../".PHP_SELF2."\" accesskey=\"a\">".S_RETURN."</a>]\n";
  1084.     $msg.="<table width='100%'><tr><th bgcolor=#e04000>\n";
  1085.     $msg.="<font color=#FFFFFF>".S_POSTING."</font>\n";
  1086.     $msg.="</th></tr></table>\n";
  1087.   }
  1088.   if($admin){
  1089.     $hidden = "<input type=hidden name=admin value=\"".ADMIN_PASS."\">";
  1090.     $msg = "<h4>".S_NOTAGS."</h4>";
  1091.   }
  1092. if($closed!=1) {
  1093.   $dat.=$msg;
  1094.   form_ads($dat);
  1095. if(OEKAKI_BOARD == 1) {
  1096.     require_once 'oekaki.php';
  1097.     if($_GET['mode'] != 'oe_finish')
  1098.         oe_form($dat,$resno);
  1099.     else
  1100.         oe_preview($dat);      
  1101. }
  1102.   $dat.='<div align="center" class="postarea"><form name="post" action="';
  1103.     $dat.=PHP_SELF_ABS.'" method="POST" enctype="multipart/form-data">
  1104. '.$hidden.'<input type=hidden name="MAX_FILE_SIZE" value="'.$maxbyte.'">
  1105. ';
  1106. if($no){$dat.='<input type=hidden name=resto value="'.$no.'">
  1107. ';}
  1108.     if((FIXED_TEXT_AD == 1) && $fixedad = ad_text_for(FIXED_TEXT_PATH)) {
  1109.     $dat.='<div id="ad">'.$fixedad.'</div>';
  1110.     }
  1111. if(FORCED_ANON == 1) {
  1112.     $dat.='<table cellpadding=1 cellspacing=1><tr colspan=2><td><input type=hidden name=name><input type=hidden name=sub>&nbsp;</td></tr>'
  1113.     .'<tr><td></td><td class="postblock" align="left"><b>'.S_EMAIL.'</b></td><td><input class=inputtext type=text name=email size="28"><span id="tdname"></span><span id="tdemail"></span>';
  1114. } else {
  1115. $dat.='<table cellpadding=1 cellspacing=1>
  1116. <tr><td></td><td class="postblock" align="left"><b>'.S_NAME.'</b></td><td><input class=inputtext type=text name=name size="28"><span id="tdname"></span></td></tr>
  1117. <tr><td></td><td class="postblock" align="left"><b>'.S_EMAIL.'</b></td><td><input class=inputtext type=text name=email size="28"><span id="tdemail"></span></td></tr>
  1118. <tr><td></td><td class="postblock" align="left"><b>'.S_SUBJECT.'</b></td><td><input class=inputtext type=text name=sub size="35">';
  1119. }
  1120. if($admin){
  1121. $dat.='<tr><td></td><td class="postblock" align="left"><b>Reply ID</b></td><td><input class=inputtext type=text name=resto size="10"> [<label><input type=checkbox name=age value=1>Age</label>] ';
  1122. }
  1123. $dat.='<input type=submit value="'.S_SUBMIT.'" accesskey="s">';
  1124. if (SPOILERS==1) {
  1125.   $dat.=' [<label><input type=checkbox name=spoiler value=on>'.S_SPOILERS.'</label>]';
  1126. };
  1127. $dat.='</td></tr>
  1128. <tr><td valign=bottom></td><td class="postblock" align="left"><b>'.S_COMMENT.'</b></td><td><textarea class=inputtext name=com cols="48" rows="4" wrap=soft></textarea></td></tr>
  1129. ';
  1130. if(OEKAKI_BOARD == 1 && $_GET['mode'] == 'oe_finish') { require_once 'oekaki.php'; oe_finish_form($dat); }
  1131. elseif (MAX_IMGRES!=0) {
  1132.     $dat.='<tr><td></td><td class="postblock" align="left"><b>'.S_UPLOADFILE.'</b></td>
  1133.     <td><input type=file name=upfile size="35">';
  1134.     if (!$resno&&NO_TEXTONLY!=1) {
  1135.     $dat.='[<label><input type=checkbox name=textonly value=on>'.S_NOFILE.'</label>]';
  1136.     }
  1137.     $dat.='</td></tr>';
  1138. }
  1139. $dat.='<tr><td></td><td class="postblock" align="left"><b>'.S_DELPASS.'</b></td><td><input class=inputtext type=password name="pwd" size=8 maxlength=8 value=""><small>'.S_DELEXPL.'</small><input type=hidden name=mode value="regist"></td></tr>
  1140. <tr><td></td><td colspan=2>
  1141. <table border=0 cellpadding=0 cellspacing=0 width="100%"><tr><td class="rules">'.S_RULES;
  1142. if(!$resno && SHOW_UNIQUES == 1) {
  1143.   $dat.='<LI>Currently <b>'.$GLOBALS['ipcount'].'</b> unique user posts.';
  1144. }
  1145. $dat.='</td><td align="right" valign="center">'.DONATE.'</td></tr>';
  1146. if(FORCED_ANON==1) { // extra spacer to make up for the 2 missing table rows
  1147.     $dat .='<tr><td>&nbsp;</td></tr>';
  1148. }
  1149. if(SHOW_BLOTTER == 1) {
  1150. list($blotdate,$blotcontents) = blotter_contents();
  1151. $dat.='<tr><td class="rules">
  1152. <script type="text/javascript"><!--
  1153. function updateBlotterVisible() {
  1154.     if(get_cookie("blotter_hide") == "show") {
  1155.         document.getElementById("blotter").style.display = \'inline\';
  1156.     } else {
  1157.         document.getElementById("blotter").style.display = \'none\';
  1158.     }
  1159. }
  1160.  
  1161. function toggleBlotter() {
  1162.     if(get_cookie("blotter_hide") == "show") {
  1163.         document.cookie = "blotter_hide=hide; expires=Thu, 4 Feb 2044 04:04:04 UTC; domain=4chan.org; path=/";
  1164.     } else {
  1165.         document.cookie = "blotter_hide=show; expires=Thu, 4 Feb 2044 04:04:04 UTC; domain=4chan.org; path=/";
  1166.     }
  1167.     updateBlotterVisible();
  1168. }
  1169. document.write(\'<div style="position:relative;"><div style="top:0px;left:0px;position:absolute;" class="rules">'.$blotdate.'</div><div style="top:0px;right:0px;position:absolute;"><a href="javascript:void(0)" onclick="toggleBlotter()">Show/Hide</a> <a href="'.BLOTTER_URL.'?all">Show All</a></div><div id="blotter" style="display:none" class="rules"><br/>\');
  1170.     document.write(' . $blotcontents . ');
  1171. document.write(\'</div></div>\');
  1172. updateBlotterVisible();
  1173. -->
  1174. </script>
  1175. </td></tr>';
  1176. }
  1177. $dat.='</table></td></tr></table></form></div><hr>
  1178. <script>with(document.post) {name.value=get_cookie("4chan_name"); email.value=get_cookie("4chan_email"); pwd.value=get_pass("4chan_pass"); }</script>
  1179. ';
  1180. } else { // closed thread
  1181.     $dat.="[<a href=\"../".PHP_SELF2."\" accesskey=\"a\">".S_RETURN."</a>]<hr>\n";
  1182.     form_ads($dat);
  1183.     $dat.='<table style="text-align:center;width:100%;height:300px;"><tr valign="middle"><td align="center"><font color=red size=5 style=""><b>Thread closed.<br/>You may not reply at this time.</b></font></tr></td></table>';
  1184. }
  1185.     if (BANROT_AD==1) {
  1186.         /*if(!$banadquery=mysql_global_call("select url,img from ".BANROTLOG." order by rand() limit 1")){echo S_SQLFAIL;}
  1187.         $banadrow=mysql_fetch_row($banadquery);
  1188.         list($ba_url,$ba_img)=$banadrow;*/
  1189.         $dat.='<center>';
  1190.         if(defined('TOPAD_TABLE')) {
  1191.             list($topad, $toplink) = rid(TOPAD_TABLE, 1);
  1192.             $dat .= "<a href=\"$toplink\" target=\"_blank\"><img style=\"border:1px solid black;\" src=\"$topad\" width=468 height=60 border=0 /></a>";
  1193.         }
  1194.         else {
  1195.             $dat .= rotating_ad_banner();
  1196.         }
  1197.         /*
  1198.         $dat.='<a href="http://webhosting.cologuys.com" target="_blank"><img src="http://content.4chan.org/dontblockthis/CG_100x60_2.gif" border="0"></a>';
  1199.         if ($ba_url != "") {
  1200.             $dat.='<a href="'.BANROT_PHP.'?url='.$ba_url.'" target="_blank"><img src="'.$ba_img.'" border="0"></a>';
  1201.         } else {
  1202.             $dat.='<img src="'.$ba_img.'" border="0">';
  1203.         }*/
  1204.  
  1205.     }
  1206.    
  1207.     if(BANROT2_AD==1) {
  1208.     /*  $dat .= @file_get_contents('/www/global/topad.txt');
  1209.         $dat.='<a href="http://webhosting.cologuys.com" target="_blank"><img src="http://content.4chan.org/dontblockthis/CG_100x60_2.gif" border="0"></a>';
  1210.         $dat.="</center><hr>\n";*/
  1211.     }
  1212.     elseif (BANROT_B==1) {
  1213.         /*if(!$banadquery=mysql_global_call("select url,img from ".BANROT_B_LOG." where DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= installed) ORDER BY RAND() limit 1")){echo S_SQLFAIL;}
  1214.         $banadrow=mysql_fetch_row($banadquery);
  1215.         list($ba_url,$ba_img)=$banadrow;
  1216.         $dat.='<br/>';
  1217.         if ($ba_url != "") {
  1218.             $dat.='<a href="'.$ba_url.'" target="_blank"><img src="'.$ba_img.'" border="0"></a>';
  1219.         } else {
  1220.             $dat.='<img src="'.$ba_img.'" border="0">';
  1221.         }
  1222.       $dat.="<br><a href=\"http://www.4chan.org/advertise/\" target=\"_blank\"><small>Buy a banner for this board!</small></a></center><hr>\n";*/
  1223.     }
  1224.     elseif(NOT4CHAN!=1 && BANROT_AD==1 || BANROT2_AD==1) {
  1225.     //$dat.="<br><a href=\"http://www.4chan.org/advertise/\" target=\"_blank\"><small>Advertise with 4chan!</small></a></center><hr>\n";
  1226.     $dat.="</center><hr>\n";
  1227.   }
  1228.  
  1229.   if (defined('GLOBAL_MSG') && GLOBAL_MSG!='') {
  1230.       $dat.=GLOBAL_MSG."\n<hr>\n";
  1231.   }
  1232.  
  1233.   if(JANITOR_BOARD == 1) {
  1234.     $dat = broomcloset_form($dat);
  1235.   }
  1236. }
  1237.  
  1238. function delete_uploaded_files()
  1239. {
  1240.     global $upfile_name,$path,$upfile,$dest;
  1241.     if($dest||$upfile) {
  1242.       @unlink($dest);
  1243.       @unlink($upfile);
  1244.       if(OEKAKI_BOARD == 1) { @unlink("$dest.pch"); }
  1245.     }
  1246. }
  1247.  
  1248. /* Footer */
  1249. function foot(&$dat){
  1250.  global $update_avg_secs;
  1251.  $include2=file_get_contents_cached(NAV2_TXT);
  1252. /* $dat.='<div class="footer">'.S_FOOT.'</div>
  1253. '.$include2.'
  1254. </body></html>';*/
  1255.   $dat .="$include2";
  1256.   if ($update_avg_secs) $dat .= "<!-- $update_avg_secs s -->";
  1257.   $dat .= "</body></html>";
  1258. }
  1259. function error($mes,$unused=''){
  1260.   delete_uploaded_files();
  1261.   head($dat,0,1);
  1262.   form_ads($dat);
  1263.  
  1264.   //echo "<br><br><hr size=1><br><br>\n<center><font color=red size=5><b>$mes<br><br><a href=";
  1265.   $dat .= '<table style="text-align:center;width:100%;height:300px;"><tr valign="middle"><td align="center"><font color=red size=5 style=""><b>' . $mes . '<br><br><a href=';
  1266.   if(strpos($_SERVER['REQUEST_URI'],RES_DIR)) $dat .= "../";
  1267.   //echo PHP_SELF2.">".S_RELOAD."</a></b></font></center><br><br><hr size=1>";
  1268.   $dat .=  PHP_SELF2.">".S_RELOAD."</a></b></font></tr></td></table><br><br><hr size=1>";
  1269.   if(BANROT_AD == 1 && !defined('TOPAD_TABLE')) {
  1270.         $dat.='<center>';
  1271.         $dat .= rotating_ad_banner();
  1272.         if(BOTTOM_AD == 1) {
  1273.             $dat .= "<hr size=1>";
  1274.         }
  1275.   }
  1276.  if(BOTTOM_AD == 1) {
  1277.     $bottomad = ad_text_for(BOTTOMAD);
  1278.     if($bottomad)
  1279.         $dat .= "$bottomad<hr>";
  1280.   }
  1281.   $dat .= "</center>";
  1282.   foot($dat);
  1283.   die($dat);
  1284. }
  1285.  
  1286. /* Auto Linker */
  1287. function normalize_link_cb($m) {
  1288.     $subdomain = $m[1];
  1289.     $original = $m[0];
  1290.     $board = strtolower($m[2]);
  1291.     $m[0] = $m[1] = $m[2] = '';
  1292.     for($i=count($m)-1;$i>2;$i--) {
  1293.         if($m[$i]) { $no = $m[$i]; break; }
  1294.     }
  1295.     if($subdomain == 'www' || $subdomain == 'static' || $subdomain == 'content')
  1296.         return $original;
  1297.     if($board == BOARD_DIR)
  1298.         return "&gt;&gt;$no";
  1299.     else
  1300.         return "&gt;&gt;&gt;/$board/$no";
  1301. }
  1302. function normalize_links($proto) {
  1303.     // change http://xxx.4chan.org/board/res/no links into plaintext >># or >>>/board/#
  1304.     if(strpos($proto,"4chan.org")===FALSE) return $proto;
  1305.    
  1306.     $proto = preg_replace_callback('@http://([A-za-z]*)[.]4chan[.]org/(\w+)/(?:res/(\d+)[.]html(?:#q?(\d+))?|\w+.php[?]res=(\d+)(?:#(\d+))?|)(?=[\s.<!?,]|$)@i','normalize_link_cb',$proto);
  1307.     // rs.4chan.org to >>>rs/query+string
  1308.     $proto = preg_replace('@http://rs[.]4chan[.]org/\?s=([a-zA-Z0-9$_.+-]+)@i','&gt;&gt;&gt;/rs/$1',$proto);
  1309.     return $proto;
  1310. }
  1311.  
  1312. function intraboard_link_cb($m) {
  1313.     global $intraboard_cb_resno, $log;
  1314.     $no = $m[1];
  1315.     $resno = $intraboard_cb_resno;
  1316.     if(isset($log[$no])) {
  1317.         $resto = $log[$no]['resto'];
  1318.         $resdir = ($resno ? '' : RES_DIR);
  1319.         $ext = PHP_EXT;
  1320.         if($resno && $resno==$resto) // linking to a reply in the same thread
  1321.             return "<a href=\"#$no\" class=\"quotelink\" onClick=\"replyhl('$no');\">&gt;&gt;$no</a>";
  1322.         elseif($resto==0) // linking to a thread
  1323.             return "<a href=\"$resdir$no$ext#$no\" class=\"quotelink\">&gt;&gt;$no</a>";
  1324.         else // linking to a reply in another thread
  1325.             return "<a href=\"$resdir$resto$ext#$no\" class=\"quotelink\">&gt;&gt;$no</a>";
  1326.     }
  1327.     return $m[0];
  1328. }
  1329. function intraboard_links($proto, $resno) {
  1330.     global $intraboard_cb_resno;
  1331.  
  1332.     $intraboard_cb_resno = $resno;
  1333.  
  1334.     $proto = preg_replace_callback('/&gt;&gt;([0-9]+)/', 'intraboard_link_cb', $proto);
  1335.     return $proto;
  1336. }
  1337.  
  1338. function interboard_link_cb($m) {
  1339.     // on one hand, we can link to imgboard.php, using any old subdomain,
  1340.     // and let apache & imgboard.php handle it when they click on the link
  1341.     // on the other hand, we can use the database to fetch the proper subdomain
  1342.     // and even the resto to construct a proper link to the html file (and whether it exists or not)
  1343.    
  1344.     // for now, we'll assume there's more interboard links posted than interboard links visited.
  1345.     $url = DATA_SERVER . $m[1] . '/' . PHP_SELF . ($m[2] ? ('?res=' . $m[2]) : "");
  1346.     return "<a href=\"$url\" class=\"quotelink\">{$m[0]}</a>"; 
  1347. }
  1348. function interboard_rs_link_cb($m) {
  1349.     // $m[1] might be a url-encoded query string, or might be manual-typed text
  1350.     // so we'll normalize it to raw text first and then re-encode it
  1351.     $lsearchquery = urlencode( urldecode($m[1]) );
  1352.     return "<a href=\"http://rs.4chan.org/?s=$lsearchquery\" class=\"quotelink\">{$m[0]}</a>";
  1353. }
  1354.  
  1355. function interboard_dis_link_cb($m) {
  1356.     $durl = $m[1]; //i don't think this is useful but just in case
  1357.     return "<a href=\"http://dis.4chan.org/read/$durl\" class=\"quotelink\">{$m[0]}</a>";
  1358. }
  1359.  
  1360. function dis_matching_re() {
  1361.     global $dis_matching_re;
  1362.    
  1363.     if (!$dis_matching_re) {
  1364.         $boards = file('/www/global/disboards.txt');
  1365.         foreach ($boards as $board) {
  1366.             list($bn,) = explode("<>", $board);
  1367.             $dis_matching_re .= $bn;
  1368.             $dis_matching_re .= '|';
  1369.         }
  1370.        
  1371.         $dis_matching_re = substr($dis_matching_re, 0, -1); //lose last |
  1372.     }
  1373.    
  1374.     return $dis_matching_re;
  1375. }
  1376.  
  1377. function interboard_links($proto) {
  1378.     $boards = "an?|cm?|fa|fit|gif|h[cr]?|[bdefgkmnoprstuvxy]|wg?|ic?|y|cgl|c[ko]|mu|po|t[gv]|toy|trv|jp|r9k|sp";
  1379.     $disboards = dis_matching_re();
  1380.     $proto = preg_replace_callback('@&gt;&gt;&gt;/('.$boards.')/([0-9]*)@i', 'interboard_link_cb', $proto);
  1381.     $proto = preg_replace_callback('@&gt;&gt;&gt;/rs/([^\s<>]+)@', 'interboard_rs_link_cb', $proto);
  1382.     $proto = preg_replace_callback('@&gt;&gt;&gt;/(('.$disboards.')/[^\s<>]*)@i', 'interboard_dis_link_cb', $proto);
  1383.     return $proto;
  1384. }
  1385.  
  1386. function auto_link($proto,$resno){
  1387.     $proto = normalize_links($proto);
  1388.        
  1389.     // auto-link remaining 4chan.org URLs if they're not part of HTML
  1390.     if(strpos($proto,"4chan.org")!==FALSE) {
  1391.         $proto = preg_replace('/(http:\/\/(?:[A-Za-z]*\.)?)(4chan)(\.org)(\/)([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?/i',"<a href=\"\\0\" target=\"_blank\">\\0</a>",$proto);
  1392.         $proto = preg_replace('/([<][^>]*?)<a href="((http:\/\/(?:[A-Za-z]*\.)?)(4chan)(\.org)(\/)([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?)" target="_blank">\\2<\/a>([^<]*?[>])/i', '\\1\\3\\4\\5\\6\\7\\8', $proto);
  1393.     }
  1394.    
  1395.     $proto = intraboard_links($proto,$resno);
  1396.     $proto = interboard_links($proto);
  1397.     return $proto;
  1398. }
  1399.  
  1400. function auto_ban_poster($nametrip, $banlength, $global, $reason, $pubreason='') {
  1401.     if(!$nametrip) $nametrip = S_ANONAME;
  1402.     if(strpos($nametrip, '</span> <span class="postertrip">!') !== FALSE) {
  1403.         $nameparts=explode('</span> <span class="postertrip">!',$name);
  1404.         $nametrip = "{$nameparts[0]} #{$nameparts[1]}";
  1405.     }
  1406.     $host = $_SERVER['REMOTE_ADDR'];
  1407.     $reverse = mysql_real_escape_string(gethostbyaddr($host));
  1408.     $xff = mysql_real_escape_string(getenv("HTTP_X_FORWARDED_FOR"));
  1409.    
  1410.     $nametrip = mysql_real_escape_string($nametrip);
  1411.     $global = ($global?1:0);
  1412.     $board = BOARD_DIR;
  1413.     $reason = mysql_real_escape_string($reason);
  1414.     $pubreason = mysql_real_escape_string($pubreason);
  1415.     if($pubreason) {
  1416.         $pubreason .= "<>";
  1417.     }
  1418.  
  1419.     //if they're already banned on this board, don't insert again
  1420.     //since this is just a spam post
  1421.     //i don't think it matters if the active ban is global=0 and this one is global=1
  1422.     {
  1423.         $existingq = mysql_global_do("select count(*)>0 from ".SQLLOGBAN." where host='$host' and active=1 and (board='$board' or global=1)");
  1424.         $existingban = mysql_result($existingq, 0, 0);
  1425.         if ($existingban > 0) {
  1426.             delete_uploaded_files();
  1427.             die();
  1428.         }
  1429.     }
  1430.  
  1431.     if($banlength == 0) { // warning
  1432.         // check for recent warnings to punish spammers
  1433.         $autowarnq=mysql_global_call("SELECT COUNT(*) FROM ".SQLLOGBAN." WHERE host='$host' AND admin='Auto-ban' AND now > DATE_SUB(NOW(),INTERVAL 3 DAY) AND reason like '%$reason'");
  1434.         $autowarncount=mysql_result($autowarnq,0,0);
  1435.         if($autowarncount > 3) {
  1436.             $banlength = 14;
  1437.         }
  1438.     }
  1439.    
  1440.    
  1441.     if($banlength == -1) // permanent
  1442.         $length = '0000' . '00' .'00'; // YYYY/MM/DD
  1443.     else {
  1444.         $banlength = (int)$banlength;
  1445.         if($banlength < 0) $banlength = 0;
  1446.         $length = date("Ymd",time()+$banlength*(24*60*60));
  1447.     }
  1448.     $length .= "00"."00"."00"; // H:M:S
  1449.    
  1450.     if(!$result=mysql_global_do("INSERT INTO ".SQLLOGBAN." (board,global,name,host,reason,length,admin,reverse,xff) VALUES('$board','$global','$nametrip','$host','$pubreason<b>Auto-ban</b>: $reason','$length','Auto-ban','$reverse','$xff')")){echo S_SQLFAIL;}
  1451.     @mysql_free_result($result);
  1452.     append_ban($global ? "global" : $global, $host);
  1453. }
  1454.  
  1455. function check_blacklist($post, $dest) {
  1456.     $board = BOARD_DIR;
  1457.     $querystr = "SELECT SQL_NO_CACHE * FROM blacklist WHERE active=1 AND (boardrestrict='' or boardrestrict='$board') AND (0 ";
  1458.     foreach($post as $field=>$contents) {
  1459.         if($contents) {
  1460.             $contents = mysql_real_escape_string(html_entity_decode($contents));
  1461.             $querystr .= "OR (field='$field' AND contents='$contents') ";
  1462.         }
  1463.     }
  1464.     $querystr .= ") LIMIT 1";
  1465.     $query = mysql_global_call($querystr);
  1466.     if(mysql_num_rows($query) == 0) return false;
  1467.     $row = mysql_fetch_assoc($query);
  1468.     if($row['ban']) {
  1469.         $prvreason = "Blacklisted ${row['field']} - " . htmlspecialchars($row['contents']);
  1470.         auto_ban_poster($post['trip']?$post['nametrip']:$post['name'], $row['banlength'], 1, $prvreason, $row['banreason']);
  1471.     }
  1472.     error(S_UPFAIL, $dest);
  1473. }
  1474.  
  1475.  
  1476. // word-wrap without touching things inside of tags
  1477. function wordwrap2($str,$cols,$cut) {
  1478.     // if there's no runs of $cols non-space characters, wordwrap is a no-op
  1479.         if(strlen($str)<$cols || !preg_match('/[^ <>]{'.$cols.'}/', $str)) {
  1480.                 return $str;
  1481.         }
  1482.     $sections = preg_split('/[<>]/', $str);
  1483.     $str='';
  1484.     for($i=0;$i<count($sections);$i++) {
  1485.         if($i%2) { // inside a tag
  1486.             $str .= '<' . $sections[$i] . '>';
  1487.         }
  1488.         else { // outside a tag
  1489.             $words = explode(' ',$sections[$i]);
  1490.             foreach($words as &$word) {
  1491.                 $word = wordwrap($word, $cols, $cut, 1);
  1492.                 // fix utf-8 sequences (XXX: is this slower than mbstring?)
  1493.                 $lines = explode($cut, $word);
  1494.                 for($j=1;$j<count($lines);$j++) { // all lines except the first
  1495.                     while(1) {
  1496.                         $chr = substr($lines[$j], 0, 1);
  1497.                         if((ord($chr) & 0xC0) == 0x80) { // if chr is a UTF-8 continuation...
  1498.                             $lines[$j-1] .= $chr; // put it on the end of the previous line
  1499.                             $lines[$j] = substr($lines[$j], 1); // take it off the current line
  1500.                             continue;
  1501.                         }
  1502.                             break; // chr was a beginning utf-8 character
  1503.                     }
  1504.                 }
  1505.                 $word = implode($cut, $lines); 
  1506.                
  1507.             }
  1508.             $str .= implode(' ', $words);
  1509.         }
  1510.     }
  1511.     return $str;
  1512. }
  1513.  
  1514. function cidrtest ($longip, $CIDR) {
  1515.     list ($net, $mask) = split ("/", $CIDR);
  1516.    
  1517.     $ip_net = ip2long ($net);
  1518.     $ip_mask = ~((1 << (32 - $mask)) - 1);
  1519.    
  1520.     $ip_ip = $longip;
  1521.    
  1522.     $ip_ip_net = $ip_ip & $ip_mask;
  1523.    
  1524.     return ($ip_ip_net == $ip_net);
  1525. }
  1526.  
  1527. function  proxy_connect($port) {
  1528.   $fp = @fsockopen ($_SERVER["REMOTE_ADDR"], $port,$a,$b,2);
  1529.   if(!$fp){return 0;}else{return 1;}
  1530. }
  1531.  
  1532. function processlist_cleanup($id) {
  1533.     logtime('Done');
  1534.     //mysql_board_call("DELETE FROM proclist WHERE id='$id'");
  1535. }
  1536.  
  1537. function logtime($desc) {
  1538.     static $run = -1;
  1539.     if(!defined('PROFILING') && !defined('PROCESSLIST')) return;
  1540.     if($run==-1) {
  1541.         $run = getmypid(); // rand(0,16777215);
  1542.         if(PROCESSLIST == 1) {
  1543.             register_shutdown_function('processlist_cleanup', $run);
  1544.             $dump = mysql_real_escape_string(serialize(array('GET'=>$_GET,'POST'=>$_POST,'SERVER'=>$_SERVER)));
  1545.             mysql_board_call("INSERT INTO proclist VALUES ('$run','$dump','')");
  1546.         }
  1547.     }
  1548.     if(PROCESSLIST == 1) {
  1549.         mysql_board_call("UPDATE proclist SET descr='$desc' WHERE id='$run'");
  1550.     }
  1551.     else {
  1552.         $board = BOARD_DIR;
  1553.         $time = microtime(true);
  1554.         mysql_global_call("INSERT INTO prof_times VALUES ('$board',$run,$time,'$desc')");
  1555.     }
  1556. }
  1557.  
  1558. function make_american($com) {
  1559.     if (stripos($com, "america")!==FALSE) return $com; //already american
  1560.    
  1561.     $com = rtrim($com);
  1562.     $end = '!';
  1563.    
  1564.     if ($com == "") return $com;
  1565.  
  1566.     if (preg_match("/([.!?])$/", $com, $matches)) {$end = $matches[1]; $com = substr($com, 0, -1);}
  1567.    
  1568.     $com .= " IN AMERICA".$end;
  1569.    
  1570.     return $com;
  1571. }
  1572.  
  1573. /* Regist */
  1574. function regist($name,$email,$sub,$com,$url,$pwd,$upfile,$upfile_name,$resto,$age){
  1575.   global $path,$pwdc,$textonly,$admin,$spoiler,$dest;
  1576.   if ($pwd==ADMIN_PASS) $admin=$pwd;
  1577.   if ($admin!=ADMIN_PASS || !valid() ) $admin='';
  1578.   $mes="";
  1579.  
  1580.   if(!$upfile && !$resto) { // allow textonly threads for moderators!
  1581.     if(valid('textonly'))
  1582.         $textonly = 1;
  1583.   }
  1584.   elseif(JANITOR_BOARD == 1) { // only allow mods/janitors to post, and textonly is always ok
  1585.     $textonly = 1;
  1586.     if(!valid('janitor_board'))
  1587.         die();
  1588.   }
  1589.  
  1590.  
  1591.   // time
  1592.   $time = time();
  1593.   $tim = $time.substr(microtime(),2,3);
  1594.  
  1595.  /* logtime("locking tables: ".($resto?'reply':'thread').", ".($upfile?'image':'text'));
  1596.   if(PROCESSLIST == 1 && BOARD_DIR != 'b' && 0) {
  1597.     if(!mysql_board_call("LOCK TABLES ".SQLLOG." WRITE,proclist WRITE"))
  1598.         die(S_SQLCONF.'<!--lk:'.mysql_errno().'-->');
  1599.   }
  1600.   else if(BOARD_DIR != 'b' && 0) {
  1601.   if(!mysql_board_call("LOCK TABLES ".SQLLOG." WRITE"))
  1602.     die(S_SQLCONF.'<!--lk:'.mysql_errno().'-->');
  1603. }
  1604.   logtime("got lock");*/
  1605.   $locked_time = time();
  1606.   mysql_board_call("set session query_cache_type=0");
  1607.   // check closed
  1608.   $resto=(int)$resto;
  1609.   if ($resto) {
  1610.     if(!$cchk=mysql_board_call("select closed from ".SQLLOG." where no=".$resto)){echo S_SQLFAIL;}
  1611.     list($closed)=mysql_fetch_row($cchk);
  1612.         if ($closed==1&&!$admin) error("You can't reply to this thread anymore.",$upfile);
  1613.     mysql_free_result($cchk);
  1614.   }
  1615.  
  1616.     if(OEKAKI_BOARD == 1 && $_POST['oe_chk']) {
  1617.         require_once 'oekaki.php';
  1618.         oe_regist_check();
  1619.         $upfile = realpath('tmp/' . $_POST['oe_ip'] . '.png');
  1620.         $upfile_name = 'Oekaki';
  1621.         $pchfile = realpath('tmp/' . $_POST['oe_ip'] . '.pch');
  1622.         if(!file_exists($pchfile)) $pchfile = '';
  1623.     }
  1624.    
  1625.     $has_image = $upfile&&file_exists($upfile);
  1626.    
  1627.   if($has_image){
  1628.    // check image limit
  1629.     if ($resto) {
  1630.         if(!$result=mysql_board_call("select COUNT(*) from ".SQLLOG." where resto=$resto and fsize!=0")){echo S_SQLFAIL;}
  1631.         $countimgres=mysql_result($result,0,0);
  1632.       if ($countimgres>MAX_IMGRES) error("Max limit of ".MAX_IMGRES." image replies has been reached.",$upfile);
  1633.         mysql_free_result($result);
  1634.         }
  1635.  
  1636.   //upload processing
  1637.     $dest = tempnam(substr($path,0,-1), "img");
  1638.     //$dest = $path.$tim.'.tmp';
  1639.     if(OEKAKI_BOARD == 1 && $_POST['oe_chk']) {
  1640.         rename($upfile, $dest);
  1641.         chmod($dest, 0644);
  1642.         if($pchfile)
  1643.             rename($pchfile, "$dest.pch");
  1644.     }
  1645.     else
  1646.         move_uploaded_file($upfile, $dest);  
  1647.    
  1648.     clearstatcache(); // otherwise $dest looks like 0 bytes!
  1649.     logtime("Moved uploaded file");
  1650.    
  1651.     $upfile_name = CleanStr($upfile_name);
  1652.     $fsize=filesize($dest);
  1653.     if(!is_file($dest)) error(S_UPFAIL,$dest);
  1654.     if(!$fsize || $fsize>MAX_KB * 1024) error(S_TOOBIG,$dest);
  1655.  
  1656.     // PDF processing
  1657.     if(ENABLE_PDF==1 && strcasecmp('.pdf',substr($upfile_name,-4))==0) {
  1658.         $ext='.pdf';
  1659.         $W=$H=1;       
  1660.         $md5 = md5_of_file($dest);
  1661.         // run through ghostscript to check for validity
  1662.         if(pclose(popen("/usr/local/bin/gs -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE=nullpage $dest",'w'))) { error(S_UPFAIL,$dest); }
  1663.     } else {
  1664.     $size = getimagesize($dest);
  1665.     if(!is_array($size)) error(S_NOREC,$dest);
  1666.     $md5 = md5_of_file($dest);
  1667.  
  1668.     //chmod($dest,0666);
  1669.     $W = $size[0];
  1670.     $H = $size[1];
  1671.     switch ($size[2]) {
  1672.       case 1 : $ext=".gif";break;
  1673.       case 2 : $ext=".jpg";break;
  1674.       case 3 : $ext=".png";break;
  1675.       case 4 : $ext=".swf";error(S_UPFAIL,$dest);break;
  1676.       case 5 : $ext=".psd";error(S_UPFAIL,$dest);break;
  1677.       case 6 : $ext=".bmp";error(S_UPFAIL,$dest);break;
  1678.       case 7 : $ext=".tiff";error(S_UPFAIL,$dest);break;
  1679.       case 8 : $ext=".tiff";error(S_UPFAIL,$dest);break;
  1680.       case 9 : $ext=".jpc";error(S_UPFAIL,$dest);break;
  1681.       case 10 : $ext=".jp2";error(S_UPFAIL,$dest);break;
  1682.       case 11 : $ext=".jpx";error(S_UPFAIL,$dest);break;
  1683.       case 13 : $ext=".swf";error(S_UPFAIL,$dest);break;
  1684.       default : $ext=".xxx";error(S_UPFAIL,$dest);break;
  1685.     }
  1686.     if(GIF_ONLY == 1 && $size[2] != 1) error(S_UPFAIL,$dest);
  1687.     } // end PDF processing -else
  1688.         $insfile=substr($upfile_name, 0, -strlen($ext));
  1689.        
  1690.     spam_filter_post_image($name, $dest, $md5, $upfile_name, $ext);
  1691.  
  1692.     // Picture reduction
  1693.     if (!$resto) {
  1694.         $maxw = MAX_W;
  1695.         $maxh = MAX_H;
  1696.     } else {
  1697.         $maxw = MAXR_W;
  1698.         $maxh = MAXR_H;
  1699.         }
  1700.     if (defined('MIN_W') && MIN_W > $W) error(S_UPFAIL,$dest);
  1701.     if (defined('MIN_H') && MIN_H > $H) error(S_UPFAIL,$dest);
  1702.     if(defined('MAX_DIMENSION'))
  1703.         $maxdimension = MAX_DIMENSION;
  1704.     else
  1705.         $maxdimension = 5000;
  1706.     if ($W > $maxdimension || $H > $maxdimension) {
  1707.         error(S_TOOBIGRES,$dest);
  1708.     } elseif($W > $maxw || $H > $maxh){
  1709.       $W2 = $maxw / $W;
  1710.       $H2 = $maxh / $H;
  1711.       ($W2 < $H2) ? $key = $W2 : $key = $H2;
  1712.       $TN_W = ceil($W * $key);
  1713.       $TN_H = ceil($H * $key);
  1714.     }
  1715.     $mes = $upfile_name . ' ' . S_UPGOOD;
  1716.   }
  1717.  
  1718. if(OEKAKI_BOARD == 1 && $_POST['oe_chk']) {
  1719. }
  1720. else {
  1721.   if($_FILES["upfile"]["error"]>0){
  1722.     if($_FILES["upfile"]["error"]==UPLOAD_ERR_INI_SIZE)
  1723.         error(S_TOOBIG,$dest);
  1724.     if($_FILES["upfile"]["error"]==UPLOAD_ERR_FORM_SIZE)
  1725.         error(S_TOOBIG,$dest);
  1726.     if($_FILES["upfile"]["error"]==UPLOAD_ERR_PARTIAL)
  1727.         error(S_UPFAIL,$dest);
  1728.     if($_FILES["upfile"]["error"]==UPLOAD_ERR_CANT_WRITE)
  1729.         error(S_UPFAIL,$dest);
  1730.   }
  1731.  
  1732.   if($upfile_name&&$_FILES["upfile"]["size"]==0){
  1733.     error(S_TOOBIGORNONE,$dest);
  1734.   }
  1735. }
  1736.  
  1737. if(ENABLE_EXIF==1) {
  1738.     $exif = htmlspecialchars(shell_exec("/usr/local/bin/exiftags $dest"));
  1739. }
  1740.  
  1741.   //The last result number
  1742.   $lastno = mysql_result(mysql_board_call("select max(no) from ".SQLLOG),0,0);
  1743.  
  1744.   $resto=(int)$resto;
  1745.   if($resto){
  1746.     if (!mysql_result(mysql_board_call("select count(no) from ".SQLLOG." where root>0 and no=$resto"),0,0))
  1747.         error(S_NOTHREADERR,$dest);
  1748.   }
  1749.  
  1750.   if($_SERVER["REQUEST_METHOD"] != "POST") error(S_UNJUST,$dest);
  1751.   // Form content check
  1752.   if(!$name||ereg("^[ |&#12288;|]*$",$name)) $name="";
  1753.   if(!$com||ereg("^[ |&#12288;|\t]*$",$com)) $com="";
  1754.   if(!$sub||ereg("^[ |&#12288;|]*$",$sub))   $sub="";
  1755.  
  1756.   if(NO_TEXTONLY==1 && !$admin) {
  1757.     if(!$resto&&!$has_image) error(S_NOPIC,$dest);
  1758.   } else {
  1759.     if(!$resto&&!$textonly&&!$has_image) error(S_NOPIC,$dest);
  1760.   }
  1761.   if(!trim($com) && !$has_image) error(S_NOTEXT,$dest);
  1762.  
  1763.  $name=ereg_replace(S_MANAGEMENT,"\"".S_MANAGEMENT."\"",$name);
  1764.  $name=ereg_replace(S_DELETION,"\"".S_DELETION."\"",$name);
  1765.  
  1766. if(!$admin && strlen($com) > 2000) error(S_TOOLONG,$dest);
  1767. if(strlen($name) > 100) error(S_TOOLONG,$dest);
  1768. if(strlen($email) > 100) error(S_TOOLONG,$dest);
  1769. if(strlen($sub) > 100) error(S_TOOLONG,$dest);
  1770. if(strlen($resto) > 10) error(S_UNUSUAL,$dest);
  1771. if(strlen($url) > 10) error(S_UNUSUAL,$dest);
  1772.  
  1773. logtime("starting autoban checks");
  1774.     spam_filter_post_content($com, $sub, $name, $fsize, $resto, $W, $H, $dest, $upfile_name, $email);
  1775.    
  1776.   //host check
  1777.   //$host = gethostbyaddr($_SERVER["REMOTE_ADDR"]);
  1778.   $host = $_SERVER["REMOTE_ADDR"];
  1779.  
  1780.   //lol /b/
  1781.   $xff = getenv("HTTP_X_FORWARDED_FOR");
  1782.  
  1783.     spam_filter_post_ip($dest);
  1784.    
  1785.     logtime("inserting xff");
  1786.     if (SAVE_XFF==1&&getenv("HTTP_X_FORWARDED_FOR")) {
  1787.     mysql_global_do(sprintf("INSERT INTO xff (tim,board,host) VALUES ('%s','%s','%s')", $tim,BOARD_DIR,mysql_escape_string(getenv("HTTP_X_FORWARDED_FOR"))) );
  1788.     }
  1789.  
  1790.  
  1791.   // No, path, time, and url format
  1792.   if($pwd==""){
  1793.     if($pwdc==""){
  1794.       $pwd=rand();$pwd=substr($pwd,0,8);
  1795.     }else{
  1796.       $pwd=$pwdc;
  1797.     }
  1798.   }
  1799.  
  1800.   $c_pass = $pwd;
  1801.   $pass = ($pwd) ? substr(md5($pwd),2,8) : "*";
  1802.  $youbi = array(S_SUN, S_MON, S_TUE, S_WED, S_THU, S_FRI, S_SAT);
  1803.   $yd = $youbi[date("w", $time)] ;
  1804.   if(SHOW_SECONDS == 1) {
  1805.       $now = date("m/d/y",$time)."(".(string)$yd.")".date("H:i:s",$time);
  1806.   } else {
  1807.       $now = date("m/d/y",$time)."(".(string)$yd.")".date("H:i",$time);
  1808.   }
  1809.   if(DISP_ID){
  1810.     if($email&&DISP_ID==1){
  1811.       $now .= " ID:???";
  1812.     }else{
  1813.       $now.=" ID:".substr(crypt(md5($_SERVER["REMOTE_ADDR"].'id'.date("Ymd", $time)),'id'),+3);
  1814.     }
  1815.   }
  1816.  
  1817.   $c_name = $name;
  1818.   $c_email = $email;
  1819.  
  1820.   if(JANITOR_BOARD == 1) { // now that the cookie_name and _email are separated, we can modify the real ones
  1821.     $name = $_COOKIE['4chan_auser'];
  1822.     $email = '';
  1823.   }
  1824.  
  1825.   //Text plastic surgery (rorororor)
  1826.   $email= CleanStr($email);  $email=ereg_replace("[\r\n]","",$email);
  1827.   $sub  = CleanStr($sub);    $sub  =ereg_replace("[\r\n]","",$sub);
  1828.   $url  = CleanStr($url);    $url  =ereg_replace("[\r\n]","",$url);
  1829.   $resto= CleanStr($resto);  $resto=ereg_replace("[\r\n]","",$resto);
  1830.   $com  = CleanStr($com,1);
  1831.  
  1832.   if(SPOILERS==1&&$spoiler) {
  1833.     $sub = "SPOILER<>$sub";
  1834.   }
  1835.   // Standardize new character lines
  1836.   $com = str_replace( "\r\n",  "\n", $com);
  1837.   $com = str_replace( "\r",  "\n", $com);
  1838.   //$com = preg_replace("/\A([0-9A-Za-z]{10})+\Z/", "!s8AAL8z!", $com);
  1839.   // Continuous lines
  1840.   $com = ereg_replace("\n((&#12288;| )*\n){3,}","\n",$com);
  1841.  
  1842.   if(!$admin && substr_count($com,"\n")>MAX_LINES) error("Error: Too many lines.",$dest);
  1843.  
  1844.   $com = nl2br($com);       //br is substituted before newline char
  1845.  
  1846.   $com = str_replace("\n",  "", $com);  //\n is erased
  1847.  
  1848. if(ROBOT9000==1) {  
  1849.    include '/www/global/plugins/robot9000.php';  
  1850.    $r9k = robot9000($r9kname,$email,$sub,$com,$md5,ip2long($host),valid('floodbypass'));  
  1851.    if($r9k != "ok") error($r9k, $dest);  
  1852. }
  1853.     if(ENABLE_EXIF==1 && $exif) {
  1854.         //turn exif into a table
  1855.         $exiflines = explode("\n",$exif);
  1856.         $exif = "<table class=\"exif\" id=\"exif$tim\" style=\"display:none;\">";
  1857.         foreach($exiflines as $exifline) {
  1858.             list($exiftag,$exifvalue) = explode(': ',$exifline);
  1859.             if($exifvalue != '')
  1860.                 $exif .= "<tr><td>$exiftag</td><td>$exifvalue</td></tr>";
  1861.             else
  1862.                 $exif .= "<tr><td><b>$exiftag</b></td></tr>";
  1863.         }
  1864.         $exif .= '</table>';
  1865.         $com .= "<br/><span class=\"abbr\">EXIF data available. Click <a href=\"javascript:void(0)\" onclick=\"toggle('exif$tim')\">here</a> to show/hide.</span><br/>";
  1866.         $com .= "$exif";
  1867.     }
  1868.     if(OEKAKI_BOARD==1 && $_POST['oe_chk']) {
  1869.         $com .= oe_info($dest,$tim);
  1870.     }
  1871.  
  1872.   //$name=ereg_replace("&#9670;","&#9671;",$name);  //replace filled diamond with hollow diamond (sjis)
  1873.   $name=ereg_replace("[\r\n]","",$name);
  1874.   $names=iconv("UTF-8", "CP932//IGNORE", $name); // convert to Windows Japanese #&#65355;&#65345;&#65357;&#65353;
  1875.  
  1876.   //start new tripcode crap
  1877.     list ($name) = explode("#", $name);
  1878.     $name = CleanStr($name);
  1879.  
  1880.     if(preg_match("/\#+$/", $names)){
  1881.         $names = preg_replace("/\#+$/", "", $names);
  1882.     }
  1883.     if (preg_match("/\#/", $names)) {
  1884.         $names = str_replace("&#","&&",htmlspecialchars($names)); # otherwise HTML numeric entities screw up explode()!
  1885.         list ($nametemp,$trip,$sectrip) = str_replace("&&", "&#", explode("#",$names,3));
  1886.         $names = $nametemp;
  1887.         $name .= "</span>";
  1888.  
  1889.         if ($trip != "") {
  1890.             if (FORTUNE_TRIP == 1 && $trip == "fortune") {
  1891.                 $fortunes = array("Bad Luck","Average Luck","Good Luck","Excellent Luck","Reply hazy, try again","Godly Luck","Very Bad Luck","Outlook good","Better not tell you now","You will meet a dark handsome stranger","&#65399;&#65408;&#9473;&#9473;&#9473;&#9473;&#9473;&#9473;(&#65439;&#8704;&#65439;)&#9473;&#9473;&#9473;&#9473;&#9473;&#9473; !!!!","&#65288;&#12288;´_&#12445;`&#65289;&#65420;&#65392;&#65437; ","Good news will come to you by mail");
  1892.                 $fortunenum = rand(0,sizeof($fortunes)-1);
  1893.                 $fortcol = "#" . sprintf("%02x%02x%02x",
  1894.                     127+127*sin(2*M_PI * $fortunenum / sizeof($fortunes)),
  1895.                     127+127*sin(2*M_PI * $fortunenum / sizeof($fortunes)+ 2/3 * M_PI),
  1896.                     127+127*sin(2*M_PI * $fortunenum / sizeof($fortunes) + 4/3 * M_PI));
  1897.                 $com = "<font color=$fortcol><b>Your fortune: ".$fortunes[$fortunenum]."</b></font><br /><br />".$com;
  1898.                 $trip = "";
  1899.                 if($sectrip == "") {
  1900.                     if($name == "</span>" && $sectrip == "")
  1901.                         $name = S_ANONAME;
  1902.                 else
  1903.                     $name = str_replace("</span>","",$name);   
  1904.         }
  1905.         } else if($trip=="fortune") {
  1906.         //remove fortune even if FORTUNE_TRIP is off
  1907.         $trip="";
  1908.                 if($sectrip == "") {
  1909.                         if($name == "</span>" && $sectrip == "")
  1910.                                 $name = S_ANONAME;
  1911.                         else
  1912.                                 $name = str_replace("</span>","",$name);
  1913.                 }
  1914.  
  1915.         } else {
  1916.  
  1917.             $salt = strtr(preg_replace("/[^\.-z]/",".",substr($trip."H.",1,2)),":;<=>?@[\\]^_`","ABCDEFGabcdef");
  1918.             $trip = substr(crypt($trip, $salt),-10);
  1919.             $name.=" <span class=\"postertrip\">!".$trip;
  1920.             }
  1921.         }
  1922.  
  1923.  
  1924.         if ($sectrip != "") {
  1925.             $salt = "LOLLOLOLOLOLOLOLOLOLOLOLOLOLOLOL"; #this is ONLY used if the host doesn't have openssl
  1926.                                                     #I don't know a better way to get random data
  1927.         if (file_exists(SALTFILE)) { #already generated a key
  1928.             $salt = file_get_contents(SALTFILE);
  1929.         } else {
  1930.             system("openssl rand 448 > '".SALTFILE."'",$err);
  1931.             if ($err === 0) {
  1932.                 chmod(SALTFILE,0400);
  1933.                 $salt = file_get_contents(SALTFILE);
  1934.             }
  1935.         }
  1936.             $sha = base64_encode(pack("H*",sha1($sectrip.$salt)));
  1937.             $sha = substr($sha,0,11);
  1938.                 if($trip=="") $name.=" <span class=\"postertrip\">";
  1939.                 $name.="!!".$sha;
  1940.         }
  1941.     } //end new tripcode crap
  1942.  
  1943.     if(!$name) $name=S_ANONAME;
  1944.     if(!$com) $com=S_ANOTEXT;
  1945.     if(!$sub) $sub=S_ANOTITLE;
  1946.  
  1947.     if(DICE_ROLL==1) {
  1948.     if ($email) {
  1949.         if (preg_match("/dice[ +](\\d+)[ d+](\\d+)(([ +-]+?)(-?\\d+))?/", $email, $match)) {
  1950.             $dicetxt = "rolled ";
  1951.             $dicenum = min(25, $match[1]);
  1952.             $diceside = $match[2];
  1953.             $diceaddexpr = $match[3];
  1954.             $dicesign = $match[4];
  1955.             $diceadd = intval($match[5]);
  1956.            
  1957.             for ($i = 0; $i < $dicenum; $i++) {
  1958.                 $dicerand = mt_rand(1, $diceside);
  1959.                 if ($i) $dicetxt .= ", ";
  1960.                 $dicetxt .= $dicerand;
  1961.                 $dicesum += $dicerand;
  1962.             }
  1963.            
  1964.             if ($diceaddexpr) {
  1965.                 if (strpos($dicesign, "-") > 0) $diceadd *= -1;
  1966.                 $dicetxt .= ($diceadd >= 0 ? " + " : " - ").abs($diceadd);
  1967.                 $dicesum += $diceadd;
  1968.             }
  1969.            
  1970.             $dicetxt .= " = $dicesum<br /><br />";
  1971.             $com = "<b>$dicetxt</b>".$com;
  1972.         }
  1973.     }
  1974.     }
  1975.     $emails=$email;
  1976.   if(ereg("(#|&#65283;)(.*)",$emails,$regs)){
  1977.     if ($regs[2]=="pubies") {
  1978.         list($email)=explode("#",$email,2);
  1979.         if(valid()) {
  1980.           $color1="#800080";
  1981.           $color2="#900090";
  1982.           $ma="Mod";
  1983.           if(stristr($name,"moot")||stristr($name,"coda")) {
  1984.             $color1="#F00000";
  1985.             $color2="#FF0000";
  1986.             $ma="Admin";
  1987.           }
  1988.           $name="<span title='$email' style=\"color:$color1\">".$name;
  1989.           $name=str_replace(" <span class=\"postertrip\">","</span> <span class=\"postertrip\"><span title='$email' style=\"color:$color2;font-weight:normal\">",$name);
  1990.           $name.="</span></span> <span class=\"commentpostername\"><span title='$email' style=\"color:$color1\">## $ma</span>";
  1991.       }
  1992.         $email = '';
  1993.  /*   } elseif ($regs[2]=="munroexkcd") {
  1994.         $name="<span style=\"color:#0000F0\">".$name;
  1995.         $name=str_replace(" <span class=\"postertrip\">","</span> <span class=\"postertrip\"><span style=\"color:#0000FF;font-weight:normal\">",$name);
  1996.         $name.="</span></span> <span class=\"commentpostername\"><span style=\"color:#0000F0\">## BlOgGeR</span>";
  1997.       list($email)=explode("#",$email,2);
  1998.     } elseif ($regs[2]=="netkingdongs") {
  1999.             $name='</span> <span class="postertrip">!!NETKING...';
  2000.             list($email)=explode("#",$email,2);
  2001.     } elseif ($regs[2]=="redhammer") {
  2002.         if(!valid()) auto_ban("<b>autobanmenow</b>",$name,"redhammer capcode");
  2003.       list($email)=explode("#",$email,2); */
  2004.     }
  2005.   }
  2006.  
  2007.     $nameparts=explode('</span> <span class="postertrip">!',$name);
  2008.     check_blacklist(array(
  2009.         'name' => $nameparts[0],
  2010.         'trip' => $trip,
  2011.         'nametrip' => "{$nameparts[0]} #{$trip}",
  2012.         'md5' => $md5,
  2013.         'email' => $email,
  2014.         'sub' => $sub,
  2015.         'com' => $com,
  2016.         'pwd' => $pass,
  2017.         'xff' => $xff,
  2018.         'filename' => $insfile,
  2019.         ), $dest);
  2020.  
  2021.     spam_filter_post_trip($name, $trip, $dest);
  2022.    
  2023.     if(SPOILERS==1) {
  2024.         $com = spoiler_parse($com);
  2025.     }
  2026.     if(SAGE_FILTER==1&&(stripos($sub,"sage")!==FALSE||stripos($com,"sage")!==FALSE)&&stripos($email,"sage")!==FALSE) $email=""; //lol /b/
  2027.     if(WORD_FILT&&file_exists("wf.php")){
  2028.         $com = word_filter($com,"com");
  2029.         if($sub)
  2030.             $sub = word_filter($sub,"sub");
  2031.         $com = str_replace(":getprophet:",$no,$com);
  2032.         $namearr=explode('</span> <span class="postertrip">',$name);
  2033.         if (strstr($name,'</span> <span class="postertrip">')) { $nametrip='</span> <span class="postertrip">'.$namearr[1]; } else { $nametrip=""; }
  2034.         if($namearr[0] != S_ANONAME)
  2035.             $name = word_filter($namearr[0],"name").$nametrip;
  2036.     }
  2037.  
  2038.     if(FORCED_ANON==1) {$name = "</span>$now<span>"; $sub = ''; $now = '';}
  2039.     $com = wordwrap2($com, 100, "<br />");
  2040.     $com = preg_replace("!(^|>)(&gt;[^<]*)!", "\\1<font class=\"unkfunc\">\\2</font>", $com);
  2041.    
  2042.     $is_sage = stripos($email, "sage") !== FALSE;
  2043.     //post is now completely created(?)
  2044.  
  2045.     logtime("Before flood check");
  2046.     $may_flood = valid('floodbypass');
  2047.    
  2048.     if (!$may_flood) {
  2049.         if ($com) {
  2050.             // Check for duplicate comments
  2051.             $query="select count(no)>0 from ".SQLLOG." where com='".mysql_escape_string($com)."' ".
  2052.                 "and host='".mysql_escape_string($host)."' ".
  2053.                 "and time>".($time-RENZOKU_DUPE);
  2054.             $result=mysql_board_call($query);
  2055.             if(mysql_result($result,0,0))error(S_RENZOKU,$dest);
  2056.             mysql_free_result($result);
  2057.         }
  2058.  
  2059.         if (!$has_image) {
  2060.             // Check for flood limit on replies
  2061.             $query="select count(no)>0 from ".SQLLOG." where time>".($time - RENZOKU)." ".
  2062.                 "and host='".mysql_escape_string($host)."' and resto>0";
  2063.             $result=mysql_board_call($query);
  2064.             if(mysql_result($result,0,0))error(S_RENZOKU, $dest);
  2065.             mysql_free_result($result);
  2066.         }
  2067.        
  2068.         if ($is_sage) {
  2069.             // Check flood limit on sage posts
  2070.             $query="select count(no)>0 from ".SQLLOG." where time>".($time - RENZOKU_SAGE)." ".
  2071.                 "and host='".mysql_escape_string($host)."' and resto>0 and permasage=1";
  2072.             $result=mysql_board_call($query);
  2073.             if(mysql_result($result,0,0))error(S_RENZOKU, $dest);
  2074.             mysql_free_result($result);
  2075.         }
  2076.        
  2077.         if (!$resto) {
  2078.             // Check flood limit on new threads
  2079.             $query="select count(no)>0 from ".SQLLOG." where time>".($time - RENZOKU3)." ".
  2080.                 "and host='".mysql_escape_string($host)."' and root>0"; //root>0 == non-sticky
  2081.             $result=mysql_board_call($query);
  2082.             if(mysql_result($result,0,0))error(S_RENZOKU3, $dest);
  2083.             mysql_free_result($result);
  2084.         }
  2085.     }
  2086.  
  2087.     // Upload processing
  2088.     if($has_image) {
  2089.         if(!$may_flood) {
  2090.             $query="select count(no)>0 from ".SQLLOG." where time>".($time - RENZOKU2)." ".
  2091.                 "and host='".mysql_escape_string($host)."' and resto>0";
  2092.             $result=mysql_board_call($query);
  2093.             if(mysql_result($result,0,0))error(S_RENZOKU2,$dest);
  2094.             mysql_free_result($result);
  2095.         }
  2096.  
  2097.         //Duplicate image check
  2098.         $result = mysql_board_call("select no,resto from ".SQLLOG." where md5='$md5'");
  2099.         if(mysql_num_rows($result)){
  2100.             list($dupeno,$duperesto) = mysql_fetch_row($result);
  2101.             if(!$duperesto) $duperesto = $dupeno;
  2102.             error('<a href="'.DATA_SERVER . BOARD_DIR . "/res/" . $duperesto . PHP_EXT . '#' . $dupeno . '">'.S_DUPE.'</a>',$dest);
  2103.         }
  2104.         mysql_free_result($result);
  2105.     }
  2106.  
  2107.    $rootqu = $resto ? "0" : "now()";
  2108.  
  2109.     // thumbnail
  2110.   if($has_image){
  2111.     rename($dest,$path.$tim.$ext);
  2112.     if(USE_THUMB){
  2113.         $tn_name = thumb($path,$tim,$ext,$resto);
  2114.         if (!$tn_name && $ext != ".pdf") {
  2115.             error(S_UNUSUAL);
  2116.         }
  2117.         }
  2118.     if(OEKAKI_BOARD == 1 && $_POST['oe_chk']) {
  2119.         rename("$dest.pch",$path.$tim.'.pch');
  2120.         unlink($upfile); // get rid of the tmp/ entries
  2121.         unlink($pchfile);
  2122.     }
  2123.   }
  2124. logtime("Thumbnail created");
  2125.  
  2126.     logtime("Before insertion");
  2127.     // noko (stay) actions
  2128.     if($email == 'noko') {
  2129.         $email = ''; $noko = 1;
  2130.     }
  2131.     else if($email == 'noko2') {
  2132.         $email = ''; $noko = 2;
  2133.     }
  2134.    
  2135.     //find sticky & autosage
  2136.     // auto-sticky
  2137.     $sticky = false;
  2138.     $autosage = spam_filter_should_autosage($com, $sub, $name, $fsize, $resto, $W, $H, $dest, $insertid);
  2139.    
  2140.     if(defined('AUTOSTICKY') && AUTOSTICKY) {
  2141.         $autosticky = preg_split("/,\s*/", AUTOSTICKY);
  2142.         if($resto == 0) {
  2143.             if($insertid % 1000000 == 0 || in_array($insertid,$autosticky))
  2144.                 $sticky = true;
  2145.         }
  2146.     }
  2147.    
  2148.     $flag_cols = "";
  2149.     $flag_vals = "";
  2150.    
  2151.     if ($sticky) {
  2152.         $flag_cols = ",sticky";
  2153.         $flag_vals = ",1";
  2154.     }
  2155.    
  2156.     //permasage just means "is sage" for replies
  2157.     if ($resto ? $is_sage : $autosage) {
  2158.         $flag_cols .= ",permasage";
  2159.         $flag_vals .= ",1";
  2160.     }
  2161.    
  2162.   $query="insert into ".SQLLOG." (now,name,email,sub,com,host,pwd,filename,ext,w,h,tn_w,tn_h,tim,time,md5,fsize,root,resto$flag_cols) values (".
  2163. "'".$now."',".
  2164. "'".mysql_escape_string($name)."',".
  2165. "'".mysql_escape_string($email)."',".
  2166. "'".mysql_escape_string($sub)."',".
  2167. "'".mysql_escape_string($com)."',".
  2168. "'".mysql_escape_string($host)."',".
  2169. "'".mysql_escape_string($pass)."',".
  2170. "'".mysql_escape_string($insfile)."',".
  2171. "'".$ext."',".
  2172. (int)$W.",".
  2173. (int)$H.",".
  2174. (int)$TN_W.",".
  2175. (int)$TN_H.",".
  2176. "'".$tim."',".
  2177. (int)$time.",".
  2178. "'".$md5."',".
  2179. (int)$fsize.",".
  2180. $rootqu.",".
  2181. (int)$resto.
  2182. $flag_vals.")";
  2183.   if(!$result=mysql_board_call($query)){echo S_SQLFAIL;}  //post registration
  2184.  
  2185.     $cookie_domain = (NOT4CHAN==1)?'.not4chan.org':'.4chan.org';
  2186.   //Cookies
  2187.   setrawcookie("4chan_name", rawurlencode($c_name), time()+($c_name?(7*24*3600):-3600),'/',$cookie_domain);
  2188.   //header("Set-Cookie: 4chan_name=$c_name; expires=".date("D, d-M-Y H:i:s",time()+7*24*3600)." GMT",false);
  2189.   if (($c_email!="sage")&&($c_email!="age")){
  2190.     setcookie ("4chan_email", $c_email,time()+($c_email?(7*24*3600):-3600),'/',$cookie_domain);  // 1 week cookie expiration
  2191.   }
  2192.   setcookie("4chan_pass", $c_pass,time()+7*24*3600,'/',$cookie_domain);  // 1 week cookie expiration
  2193.  
  2194.   $insertid = mysql_board_insert_id();
  2195.    
  2196.     if($resto){ //sage or age action
  2197.         $resline=mysql_board_call("select count(no) from ".SQLLOG." where resto=".$resto);
  2198.         $countres=mysql_result($resline,0,0);
  2199.         mysql_free_result($resline);
  2200.         $resline=mysql_board_call("select sticky,permasage from ".SQLLOG." where no=".$resto);
  2201.         list($stuck,$psage)=mysql_fetch_row($resline);
  2202.         mysql_free_result($resline);
  2203.         if((stripos($email,'sage')===FALSE && $countres < MAX_RES && $stuck != "1" && $psage != "1") || ($admin&&$age&&$stuck != "1")){
  2204.             $query="update ".SQLLOG." set root=now() where no=$resto"; //age
  2205.             mysql_board_call($query);
  2206.         }
  2207.     }
  2208.    
  2209.     $static_rebuild = defined("STATIC_REBUILD") && (STATIC_REBUILD==1);
  2210.     logtime("Before trim_db");  
  2211.     // trim database
  2212.     if(!$resto && !$static_rebuild)
  2213.       trim_db();
  2214.     logtime("After trim_db");
  2215. if(PROCESSLIST == 1 && (time() > ($locked_time+7))) {
  2216.             $dump = mysql_real_escape_string(serialize(array('GET'=>$_GET,'POST'=>$_POST,'SERVER'=>$_SERVER)));
  2217.             mysql_board_call("INSERT INTO proclist VALUES (connection_id(),'$dump','slow post')");
  2218. }
  2219. /*mysql_board_unlock();
  2220.  
  2221.     logtime("Tables unlocked"); */
  2222. if(BOARD_DIR == 'b')
  2223. iplog_add(BOARD_DIR, $insertid, $host);
  2224.     logtime("Ip logged");
  2225.  
  2226. if(RAPIDSEARCH_LOGGING == 1) {
  2227.     rapidsearch_check(BOARD_DIR, $insertid, $com);
  2228. }
  2229.     logtime("rapidsearch check finished");
  2230.  
  2231.     $deferred = false;
  2232.     // update html
  2233.     if($resto) {
  2234.     $deferred = updatelog($resto, $static_rebuild);
  2235.     } else {
  2236.       $deferred = updatelog($insertid, $static_rebuild);
  2237.   }
  2238.   logtime("Pages rebuilt");
  2239.   // determine url to redirect to
  2240.     if($noko && !$resto) {
  2241.         $redirect = DATA_SERVER . BOARD_DIR . "/res/" . $insertid . PHP_EXT;
  2242.     }
  2243.     else if($noko==1) {
  2244.         $redirect = DATA_SERVER . BOARD_DIR . "/res/" . $resto . PHP_EXT . '#' . $insertid;
  2245.     }
  2246.     else {
  2247.         $redirect = PHP_SELF2_ABS;
  2248.     }
  2249.  
  2250.   if($deferred) {
  2251.     echo "<html><head><META HTTP-EQUIV=\"refresh\" content=\"2;URL=$redirect\"></head>";
  2252.     echo "<body>$mes ".S_SCRCHANGE."<br>Your post may not appear immediately.<!-- thread:$resto,no:$insertid --></body></html>";
  2253.   }
  2254.   else {
  2255.     echo "<html><head><META HTTP-EQUIV=\"refresh\" content=\"1;URL=$redirect\"></head>";
  2256.     echo "<body>$mes ".S_SCRCHANGE."<!-- thread:$resto,no:$insertid --></body></html>";
  2257.   }
  2258.  
  2259. }
  2260.  
  2261. function resredir($res) {
  2262.     $res = (int)$res;
  2263.     mysql_board_lock();
  2264.     if(!$redir=mysql_board_call("select no,resto from ".SQLLOG." where no=".$res)){echo S_SQLFAIL;}
  2265.     list($no,$resto)=mysql_fetch_row($redir);
  2266.     if(!$no) {
  2267.         $maxq = mysql_board_call("select max(no) from ".SQLLOG."");
  2268.         list($max)=mysql_fetch_row($maxq);
  2269.         if(!$max || ($res > $max))
  2270.             header("HTTP/1.0 404 Not Found");
  2271.         else // res < max, so it must be deleted!
  2272.             header("HTTP/1.0 410 Gone");
  2273.         error(S_NOTHREADERR,$dest);
  2274.     }
  2275.  
  2276.   if($resto=="0") // thread
  2277.     $redirect = DATA_SERVER . BOARD_DIR . "/res/" . $no . PHP_EXT . '#' . $no;
  2278.   else
  2279.     $redirect = DATA_SERVER . BOARD_DIR . "/res/" . $resto . PHP_EXT . '#' . $no;  
  2280.  
  2281.    
  2282.     echo "<META HTTP-EQUIV=\"refresh\" content=\"0;URL=$redirect\">";
  2283.     if($resto=="0")
  2284.         log_cache();
  2285.     mysql_board_unlock();
  2286.    
  2287.     if($resto=="0") { // thread
  2288.         updatelog($res);
  2289.     }
  2290. }
  2291.  
  2292. //thumbnails
  2293. function thumb($path,$tim,$ext,$resto){
  2294.   if(!function_exists("ImageCreate")||!function_exists("ImageCreateFromJPEG"))return;
  2295.   $fname=$path.$tim.$ext;
  2296.   $thumb_dir = THUMB_DIR;     //thumbnail directory
  2297.   $outpath = $thumb_dir.$tim.'s.jpg';
  2298.   if (!$resto) {
  2299.       $width     = MAX_W;            //output width
  2300.       $height    = MAX_H;            //output height
  2301.   } else {
  2302.       $width     = MAXR_W;            //output width (imgreply)
  2303.       $height    = MAXR_H;            //output height (imgreply)
  2304.   }
  2305.   // width, height, and type are aquired
  2306.   if(ENABLE_PDF==1 && $ext=='.pdf') {
  2307.     // create jpeg for the thumbnailer
  2308.     $pdfjpeg = $path.$tim.'.pdf.tmp';
  2309.     @exec("/usr/local/bin/gs -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE=jpeg -sOutputFile=$pdfjpeg $fname");
  2310.     if(!file_exists($pdfjpeg)) unlink($fname);
  2311.     $fname = $pdfjpeg;
  2312.   }
  2313.   $size = GetImageSize($fname);
  2314.   $memory_limit_increased = false;
  2315.   if($size[0]*$size[1] > 3000000) {
  2316.     $memory_limit_increased = true;
  2317.       ini_set('memory_limit', memory_get_usage() + $size[0]*$size[1]*10); // for huge images
  2318.   }
  2319.   switch ($size[2]) {
  2320.     case 1 :
  2321.       if(function_exists("ImageCreateFromGIF")){
  2322.         $im_in = ImageCreateFromGIF($fname);
  2323.         if($im_in){break;}
  2324.       }
  2325.       if(!is_executable(realpath("/www/global/gif2png"))||!function_exists("ImageCreateFromPNG"))return;
  2326.       @exec(realpath("/www/global/gif2png")." $fname",$a);
  2327.       if(!file_exists($path.$tim.'.png'))return;
  2328.       $im_in = ImageCreateFromPNG($path.$tim.'.png');
  2329.       unlink($path.$tim.'.png');
  2330.       if(!$im_in)return;
  2331.       break;
  2332.     case 2 : $im_in = ImageCreateFromJPEG($fname);
  2333.       if(!$im_in){return;}
  2334.        break;
  2335.     case 3 :
  2336.       if(!function_exists("ImageCreateFromPNG"))return;
  2337.       $im_in = ImageCreateFromPNG($fname);
  2338.       if(!$im_in){return;}
  2339.       break;
  2340.     default : return;
  2341.   }
  2342.   // Resizing
  2343.   if ($size[0] > $width || $size[1] > $height || $size[2]==1) {
  2344.     $key_w = $width / $size[0];
  2345.     $key_h = $height / $size[1];
  2346.     ($key_w < $key_h) ? $keys = $key_w : $keys = $key_h;
  2347.     $out_w = ceil($size[0] * $keys) +1;
  2348.     $out_h = ceil($size[1] * $keys) +1;
  2349.     /*if ($size[2]==1) {
  2350.         $out_w = $size[0];
  2351.         $out_h = $size[1];
  2352.     } //what was this for again? */
  2353.   } else {
  2354.     $out_w = $size[0];
  2355.     $out_h = $size[1];
  2356.   }
  2357.   // the thumbnail is created
  2358.   if(function_exists("ImageCreateTrueColor")&&get_gd_ver()=="2"){
  2359.     $im_out = ImageCreateTrueColor($out_w, $out_h);
  2360.   }else{$im_out = ImageCreate($out_w, $out_h);}
  2361.   // copy resized original
  2362.   ImageCopyResampled($im_out, $im_in, 0, 0, 0, 0, $out_w, $out_h, $size[0], $size[1]);
  2363.   // thumbnail saved
  2364.   ImageJPEG($im_out, $outpath ,60);
  2365.   //chmod($thumb_dir.$tim.'s.jpg',0666);
  2366.   // created image is destroyed
  2367.   ImageDestroy($im_in);
  2368.   ImageDestroy($im_out);
  2369.   if(isset($pdfjpeg)) { unlink($pdfjpeg); } // if PDF was thumbnailed delete the orig jpeg
  2370.   if($memory_limit_increased)
  2371.     ini_restore('memory_limit');
  2372.  
  2373.   return $outpath;
  2374. }
  2375.  
  2376. //check version of gd
  2377. function get_gd_ver(){
  2378.   if(function_exists("gd_info")){
  2379.     $gdver=gd_info();
  2380.     $phpinfo=$gdver["GD Version"];
  2381.   }else{ //earlier than php4.3.0
  2382.     ob_start();
  2383.     phpinfo(8);
  2384.     $phpinfo=ob_get_contents();
  2385.     ob_end_clean();
  2386.     $phpinfo=strip_tags($phpinfo);
  2387.     $phpinfo=stristr($phpinfo,"gd version");
  2388.     $phpinfo=stristr($phpinfo,"version");
  2389.   }
  2390.   $end=strpos($phpinfo,".");
  2391.   $phpinfo=substr($phpinfo,0,$end);
  2392.   $length = strlen($phpinfo)-1;
  2393.   $phpinfo=substr($phpinfo,$length);
  2394.   return $phpinfo;
  2395. }
  2396.  
  2397. //md5 calculation for earlier than php4.2.0
  2398. function md5_of_file($inFile) {
  2399.  if (file_exists($inFile)){
  2400.   if(function_exists('md5_file')){
  2401.     return md5_file($inFile);
  2402.   }else{
  2403.     $fd = fopen($inFile, 'r');
  2404.     $fileContents = fread($fd, filesize($inFile));
  2405.     fclose ($fd);
  2406.     return md5($fileContents);
  2407.   }
  2408.  }else{
  2409.   return false;
  2410. }}
  2411.  
  2412. /* text plastic surgery */
  2413. // you can call with skip_bidi=1 if cleaning a paragraph element (like $com)
  2414. function CleanStr($str,$skip_bidi=0){
  2415.   global $admin,$html;
  2416.   $str = trim($str);//blankspace removal
  2417.   if (get_magic_quotes_gpc()) {//magic quotes is deleted (?)
  2418.     $str = stripslashes($str);
  2419.   }
  2420.   if($admin!=ADMIN_PASS){
  2421.     $str = htmlspecialchars($str);
  2422.   } elseif(( $admin==ADMIN_PASS)&&$html!=1) {
  2423.     $str = htmlspecialchars($str);
  2424.   }
  2425.   if($skip_bidi == 0) {
  2426.       // fix malformed bidirectional overrides - insert as many PDFs as RLOs
  2427.     //RLO
  2428.       $str .= str_repeat("\xE2\x80\xAC", substr_count($str, "\xE2\x80\xAE"/* U+202E */));
  2429.       $str .= str_repeat("&#8236;", substr_count($str, "&#8238;"));
  2430.       $str .= str_repeat("&#x202c;", substr_count($str, "&#x202e;"));
  2431.     //RLE
  2432.       $str .= str_repeat("\xE2\x80\xAC", substr_count($str, "\xE2\x80\xAB"/* U+202B */));
  2433.       $str .= str_repeat("&#8236;", substr_count($str, "&#8235;"));
  2434.       $str .= str_repeat("&#x202c;", substr_count($str, "&#x202b;"));
  2435.   }
  2436.   return str_replace(",", "&#44;", $str);//remove commas
  2437. }
  2438.  
  2439. //check for table existance
  2440. function table_exist($table){
  2441.   $result = mysql_board_call("show tables like '$table'");
  2442.   if(!$result){return 0;}
  2443.   $a = mysql_fetch_row($result);
  2444.   mysql_free_result($result);
  2445.   return $a;
  2446. }
  2447.  
  2448. function report() {
  2449.     require '/www/global/forms/report.php';
  2450.     require '/www/global/modes/report.php';
  2451.     if($_SERVER['REQUEST_METHOD'] == 'GET') {
  2452.         if(!report_post_exists($_GET['no']))
  2453.             fancydie('That post doesn\'t exist anymore.');
  2454.         if(report_post_sticky($_GET['no']))
  2455.             fancydie('Stop trying to report a sticky.');
  2456.         report_check_ip(BOARD_DIR, $_GET['no']);
  2457.         form_report(BOARD_DIR, $_GET['no']);
  2458.     }
  2459.     else {
  2460.         report_check_ip(BOARD_DIR, $_POST['no']);
  2461.         report_submit(BOARD_DIR, $_POST['no'], $_POST['cat']);
  2462.     }
  2463.     die('</body></html>');
  2464. }
  2465.  
  2466. /* user image deletion */
  2467. function usrdel($no,$pwd){
  2468.   global $path,$pwdc,$onlyimgdel;
  2469.   $host = $_SERVER["REMOTE_ADDR"];
  2470.   $delno = array();
  2471.   $delflag = FALSE;
  2472.   $rebuildindex = !(defined("STATIC_REBUILD") && STATIC_REBUILD);
  2473.   reset($_POST);
  2474.   while ($item = each($_POST)){
  2475.     if($item[1]=='delete'){array_push($delno,$item[0]);$delflag=TRUE;}
  2476.   }
  2477.   if(($pwd=="")&&($pwdc!="")) $pwd=$pwdc;
  2478.   $countdel=count($delno);
  2479.  
  2480.   $flag = FALSE;
  2481.   //mysql_board_call("LOCK TABLES ".SQLLOG." WRITE");
  2482.   $rebuild = array(); // keys are pages that need to be rebuilt (0 is index, of course)
  2483.   for($i = 0; $i<$countdel; $i++){
  2484.     $resto = delete_post($delno[$i], $pwd, $onlyimgdel, 0, 1, $countdel == 1); // only show error for user deletion, not multi
  2485.     if($resto)
  2486.         $rebuild[$resto] = 1;
  2487.   }
  2488.   log_cache();
  2489.   //mysql_board_call("UNLOCK TABLES");  
  2490.   foreach($rebuild as $key=>$val) {
  2491.     updatelog($key, 1); // leaving the second parameter as 0 rebuilds the index each time!
  2492.   }
  2493.   if ($rebuildindex) updatelog(); // update the index page last
  2494. }
  2495.  
  2496. /*password validation */
  2497. function oldvalid($pass){
  2498.     error(S_WRONGPASS);
  2499.   /*if($pass && ($pass != ADMIN_PASS) ) {
  2500.     auto_ban_poster($name, 2, 1, 'failed the password check on imgboard manager mode', 'Trying to exploit administrative pages.');
  2501.     error(S_WRONGPASS);
  2502.   }*/
  2503.  
  2504.   head($dat,0);
  2505.   echo $dat;
  2506.   echo "[<a href=\"".PHP_SELF2."\">".S_RETURNS."</a>]\n";
  2507.   echo "[<a href=\"".PHP_SELF."\">".S_LOGUPD."</a>]\n";
  2508.   echo "<table width='100%'><tr><th bgcolor=#E08000>\n";
  2509.   echo "<font color=#FFFFFF>".S_MANAMODE."</font>\n";
  2510.   echo "</th></tr></table>\n";
  2511.   echo "<p><form action=\"".PHP_SELF."\" method=POST>\n";
  2512.   // Mana login form
  2513.   if(!$pass){
  2514.     echo "<center><input type=hidden name=admin value=post><input type=hidden name=mode value=admin>\n";
  2515.     echo "<input class=inputtext type=password name=pass size=8>";
  2516.     echo "<input type=submit value=\"".S_MANASUB."\"></form></center>\n";
  2517.     die("</body></html>");
  2518.   }
  2519. }
  2520.  
  2521. function rebuild($all=0) {
  2522.     header("Pragma: no-cache");
  2523.     echo "Rebuilding ";
  2524.     if($all) { echo "all"; } else { echo "missing"; }
  2525.     echo " replies and pages... <a href=\"".PHP_SELF2_ABS."\">Go back</a><br><br>\n";
  2526.     ob_end_flush();
  2527.     mysql_board_lock();
  2528.     $starttime = microtime(true);
  2529.     if(!$treeline=mysql_board_call("select no,resto from ".SQLLOG." where root>0 order by root desc")){echo S_SQLFAIL;}
  2530.     log_cache();
  2531.     mysql_board_unlock();
  2532.     echo "Writing...\n";
  2533.     if($all || !defined('CACHE_TTL')) {
  2534.         while(list($no,$resto)=mysql_fetch_row($treeline)) {
  2535.             if(!$resto) {
  2536.                 updatelog($no,1);
  2537.                 echo "No.$no created.<br>\n";
  2538.                 }
  2539.         }
  2540.         updatelog();
  2541.         echo "Index pages created.<br>\n";
  2542.     }
  2543.     else {
  2544.         $posts = rebuildqueue_take_all();
  2545.         foreach($posts as $no) {
  2546.             $deferred = ( updatelog($no,1) ? ' (deferred)' : '' );
  2547.             if($no)
  2548.                 echo "No.$no created.$deferred<br>\n";
  2549.             else
  2550.                 echo "Index pages created.$deferred<br>\n";
  2551.         }
  2552.     }
  2553.     $totaltime = microtime(true) - $starttime;
  2554.     echo "<br>Time elapsed (lock excluded): $totaltime seconds","<br>Pages created.<br><br>\nRedirecting back to board.\n<META HTTP-EQUIV=\"refresh\" content=\"10;URL=".PHP_SELF2."\">";
  2555. }
  2556.  
  2557. /*-----------Main-------------*/
  2558. switch($mode){
  2559.   case 'regist':
  2560.     regist($name,$email,$sub,$com,'',$pwd,$upfile,$upfile_name,$resto,$age);
  2561.     break;
  2562.   case 'report':
  2563.     report();
  2564.     break;
  2565.   case 'admin':
  2566.     oldvalid($pass);
  2567.     if($admin=="post"){
  2568.       echo "</form>";
  2569.       form($post,$res,1);
  2570.       echo $post;
  2571.       die("</body></html>");
  2572.     }
  2573.     break;
  2574.   case 'rebuild':
  2575.       rebuild();
  2576.       break;
  2577.   case 'rebuildall':
  2578.       rebuild(1);
  2579.       break;
  2580.   case 'admindel':
  2581.       usrdel($no,$pwd);
  2582.       echo "<META HTTP-EQUIV=\"refresh\" content=\"0;URL=admin.php\">";
  2583.       break;
  2584.   case 'nothing':
  2585.       break;
  2586.   case 'usrdel':
  2587.       usrdel($no,$pwd);
  2588.   default:
  2589.   if(JANITOR_BOARD == 1 && $mode == 'latest') {
  2590.     broomcloset_latest();
  2591.   }
  2592.   if(OEKAKI_BOARD == 1 && $mode == 'oe_finish') {
  2593.    require_once 'oekaki.php';
  2594.    oe_finish();
  2595.   }
  2596.   elseif(OEKAKI_BOARD == 1 && $mode == 'oe_paint') {
  2597.    require_once 'oekaki.php';
  2598.    oe_paint();
  2599.   }
  2600.   if($res){
  2601.       resredir($res);
  2602.       echo "<META HTTP-EQUIV=\"refresh\" content=\"10;URL=".PHP_SELF2_ABS."\">";
  2603.     }else{
  2604.     //mysql_board_call("LOCK TABLES ".SQLLOG." READ");
  2605.       echo "Updating index...\n";
  2606.         updatelog();
  2607.      //mysql_board_call("UNLOCK TABLES");
  2608.       echo "<META HTTP-EQUIV=\"refresh\" content=\"0;URL=".PHP_SELF2_ABS."\">";
  2609.     }
  2610. }
  2611.  
  2612. ?>
Add Comment
Please, Sign In to add comment