News:

Please note these forums are mostly a testing ground for my SMF work and I don't really use them otherwise.

Main Menu
Menu

Show posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.

Show posts Menu

Topics - SleePy

#61
The test zone / test
Jan 14, 2009, 02:16 AM
test "For topics and boards I've requested notification on, notify me of:"
#62
The test zone / Smiley test
Jan 04, 2009, 11:43 PM
 :)
;)
:D
;D
>:(
:(
:o
8)
??? :) :o :-[ :-[ :-[ :-[
::) >:( :-X :'( :'( >:(
:P :) :D :o ::) ::) ??? ???
:-[ :o :D :'( O0 O0 ^-^ >:D
:-X ;D :D :o ??? :-[ :-*
:-\ >:( :) :P :'( :( :(
:-* ??? ::) :-[ >:( ;D
:'( :'( :'( ;D :D ;) :)
;) ??? ;D :( :P :-* :'(

>:( >:( :( :(
#63
mysql> SHOW FULL PROCESSLIST
    -> ;
+-----+--------+-----------+---------------+---------+------+----------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Id  | User   | Host      | db            | Command | Time | State                | Info                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
+-----+--------+-----------+---------------+---------+------+----------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 140 | SMF    | localhost | smf_svn__7721 | Query   |  310 | Copying to tmp table | SELECT
               t.id_topic, t.id_first_msg, t.id_last_msg,
               CASE WHEN MIN(ma.id_msg) > 0 THEN
                  CASE WHEN MIN(mu.id_msg) > 0 THEN
                     CASE WHEN MIN(mu.id_msg) < MIN(ma.id_msg) THEN MIN(mu.id_msg) ELSE MIN(ma.id_msg) END ELSE
                  MIN(ma.id_msg) END ELSE
               MIN(mu.id_msg) END AS myid_first_msg,
               CASE WHEN MAX(ma.id_msg) > 0 THEN MAX(ma.id_msg) ELSE MIN(mu.id_msg) END AS myid_last_msg,
               t.approved, mf.approved, mf.approved AS firstmsg_approved
            FROM smf_topics AS t
               LEFT JOIN smf_messages AS ma ON (ma.id_topic = t.id_topic AND ma.approved = 1)
               LEFT JOIN smf_messages AS mu ON (mu.id_topic = t.id_topic AND mu.approved = 0)
               LEFT JOIN smf_messages AS mf ON (mf.id_msg = t.id_first_msg)
            WHERE t.id_topic BETWEEN 0 AND 199
            GROUP BY t.id_topic, t.id_first_msg, t.id_last_msg, t.approved, mf.approved
            ORDER BY t.id_topic |
| 149 | jeremy | localhost | NULL          | Query   |    0 | NULL                 | SHOW FULL PROCESSLIST                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
+-----+--------+-----------+---------------+---------+------+----------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)
#64
The test zone / Big Post
Dec 29, 2008, 10:34 PM
Here is an example of a topic that is failing to load in Firefox, Windows XP -




Enclosed is my attempt to document a step-by-step procedure for the famous KLR-650 doo swap. There are many site with Doo walk-thruís. I tried to detail the steps based on my experiences. This was my first doo swap.

I also installed the Electrosport 400 watt stator while I was swapping the Doo. That pitch is located here: http://klrworld.com/forums/index.php?topic=829.0



Start with a little research, donít want any surprises!...Youíll have to excuse the crudity of my KLR-650 library. I really need to organize the topics better...hehehe



First Drain the oil, I use the center stand for this task



Low profile magnetic drain plug, new crush washer with every oil change.



Now jack-up the bike, Jack is a Sears Craftman brand with a few added brackets



remove side covers, notice re-located helmet lock with cable. Easy access and attach full face helmet.



remove seat. All my KLR fasteners have been upgraded to stainless ìcapî style fasteners (Allen Key) See: http://klrworld.com/forums/index.php?topic=878.0



Remove tank bolts



Gas off, remove gas line



rag to catch gas drippings



side covers pry from tank



All the Items removed. Note: Some do not remove side covers, seat and tank. I did for 2x reasons. First I replaced my stator and regulator with the 400 watt aftermarket. I needed access to the wire bundles under the seat and tank. Second my garage has overhead lighting and I need as much light as possible to photograph the project. Don't want a tank shadow on the work area.



set up bike for task....Lots of light



Shop space/tables open...tools available



the doo kit from Eagle Mike...May need those gaskets. Have them handy



Area to open up!



Shifter lever off. Small mark to re-align teeth when re-installing



Take bolt all the way out...rachet wrench works best...wiggle lever off...



set aside with bolt in place as to not lose



one peg bolt off...loosen other...swivel aside as to clear outer case



Like this



sprocket cover next....3x fasteners



set aside



neutral wire....grab with fingers...wiggle straight back..no problem



wire off ....connector exposed



loosen outer cover.....NOT inner cover...triple check which bolt is attached to outer cover



loosen all about this much...your fasteners may not be cap heads



notice inner cover fastener still fully engaged



crack the case...try to maintain integrity of gasket...If tears....you will need a new one. Mine tore.



remove all fasteners here shown is 2x helper tabs to assist in prying with fingers



keep all parts on table with labels



pull outer case straight back...some oil will drip...have rags handy



tie off stator...donít let wires hold itís weight! Have wires/string/bungee available prior to removal



Attach here



here is is



Area of interest, need to remove most of this stuff.



It has really been explained if the gears need to be installed back exactly as removed, so I marked them for re-install. You donít need to do this. Remove these gears. Lower one first. Just pull it straight back. Then the upper one. Reach behind to take any washers or bushings with the gear. No issues all comes off well. Place on table.



Place that large Eagle Mike bent wrench over the 2x parallel notches on the shaft. Opposite end of wrench under foot peg Your going to un-trhread a 19mm large highly torqued bolt, rotate the bolt counter- clockwise. The whole bike will want to rotate. I placed a crate under the front tire to keep bike from falling. I used and recommend a 19mm car tire lug wrench. This will ensure you are only placing a moment on the bolt, not shear forces. Two co-linear forces offset by the by a distance is a couple. Every couple has itís moment! Hehehe



bolt un-threading. You can do this whole task alone. This was the most difficult step in the entire process. The bolt is torqued to 130 ft-lbs. It is really on there.



bolt off...whew!



next is the rotor and starter gear. The starter gear is behind this rotor. They are on the same shaft



need this Eagle Mike supplied bolt. It is really a rotor removal tool. You will use it to remove a press fit rotor. The rotor will not rotate and slide off a shaft.



lube it...as to minimize galling



thread it in



Place wrench over foot peg and rotate lug wrench clockwise



pull out rotor and starter gear. Straight out. Watch for woodruff key. A small crescnt shaped metal piece. Mine came out no problem



starter gear



this is where that keys goes



My Doo...loosen the balancer adjustment bolt. Rotate counter clockwise



the bolt is coming out



keep your finger here as you pull off your doo. Straight back



This is what all the fuss is about! Not broken.



The inner case is next. Need to get in here to replace that spring. Remove all outer case parameter fasteners



one internal fastener also right here! NOTE: it is shorter in length than the inner case attach fasteners...Edit comment from member pterzian



keep fasteners here



brake seal on case try to maintain gasket integrity. Mine broke. Dough! Good thing I ordered those extra gaskets!



Inner case coming off. Keep finger on the doo shaft while you remove the inner case



here is the stock spring. At lower section of the case. Not broken.



remove the spring



replace with the longer of the 2x Eagle Mike springs



new unsprung gap = .5 inches. Hope that is ok!



slide the spring end over stud like this with small tool



measure gaps between coils



gap = .025 inch. Hope that is ok!



Spring on...now reinstall all parts!



inspect inner case...remove all residual gasket sealant



little left is ok



new gasket



Very light coat of this stuff



re-attach inner cover. Make sure everything aligns



torque all fasteners to 15 in-lbs in cris-cross pattern, then torque all to 69 inch-lbs.



attach the doo and adjuster bolt. Do not tighten bolt yet



Attach starter sprocket



Slides right on



That slot on the shaft is for the woodruff key



place like this



in here. Clean all grease from the shaft



the rotor next...This part is tricky. Need to align rotor slot with key in shaft. BIG TIP HERE: take your left index finger and spin that big starter sprocket clockwise while pushing the stator on the shaft. This was the second most difficult step.



stator on....now to install that bolt that came with Eaglemike's kit



bolt on



torque to 85 foot-lbs Clock-wise...then back off totally...then torque to 130 ft-lbs. Use a ¬Ω torque wrench. Note: holder wrench on top of foot peg. Back end will want to come down.



install upper gear. Just slide it on



now lower gear....just slide it on mesh with starter teeth...



rotate starter sprocket clockwise to align teeth...Like what you did to attach the rotor



all internal parts re-installed. Torque the balancer bolt to 69-inch-lbs.



ready to reinstall case



finger thread bolts...note: a .25 inch gap exists between case and frame. Cannot close with hand pressure....carefully tighten fasteners...cris-cross pattern 1x turn at a time. It will slowly close up the gap.



toruque to 25 inch-lbs cris cross pattern...repeat with 68 in-lbs.



All buttoned up.

re-attach wire bundle clip and push wires back into slot with small tool



add oil, re-attach shifter, foot peg, neutral wire      
      


all done.

Review and observations:

1. Bike started....
2. No leaks....
3. Have left side outer and inner cover gasket handy. I needed them.
4. Once installed I fired up the bike, it rattled a lot. I turned it off. Leaned the bike to the right at 25 degrees. It was propped on the garage door frame.† Removed the rubber balancer adjust cover. Rotated the balancer adjust bolt 1x full turn counter-clockwise. The rotate the bolt clockwise and torque the bolt to 69 inch-lbs. Note Units! Then the bike purred! It also seemed to induce less vibration at the higher RPM's.
5. Although no parts were failed, I'll have piece of mind.
#65
The test zone / ASCII 15
Dec 04, 2008, 11:21 PM

#66
<?php

// We have a cache file?
if (file_exists(dirname(__FILE__) . '/.cache'))
{
   // Redirect it.
   $file = file_get_contents(dirname(__FILE__) . '/.cache');
   if (!empty($file))
      header('Location: ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $file);

   // Now secretly we will unlink it.
   if ((time() - filemtime(dirname(__FILE__) . '/.cache') > 3600))
      unlink(dirname(__FILE__) . '/.cache');

   // Only exit, if we sent the header.
   if (!empty($file))
      exit;
}

// Find all files.
$files = scandir(dirname(__FILE__));

// Remove bad ones.
foreach ($files as $key => $file)
   if (in_array($file, array('.', '..', 'index.php', '.cache')))
      unset($files[$key]);

// Sort it.
sort($files);

// Get a key.
$key = rand(0, count($files));

// Sent the user away.
header('Location: ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $files[$key]);

// But we still get the cache setup for this.
file_put_contents(dirname(__FILE__) . '/.cache', $files[$key]);

// Good bye.
exit;
?>
#67
// Find the SVN revision number
function findSVNrevision($svn_dir)
{
   // No file, forget it.
   if (!file_exists($svn_dir . '/.svn/entries'))
      return date('Y-m-d_H-i', time());

   // Open the file, read it and close it.
   $opened_file = fopen($svn_dir . '/.svn/entries', "r");
   $junk = fread($opened_file, 13);
   fclose($opened_file);

   // Pull out the revision
   preg_match("~dir([0-9]*)~mis", str_replace(array("\r", "\n", "\r\n"), '', $junk), $match);

   // If it fails.. I guess we get out.
   if (empty($match[0]) || empty($match[1]))
      return date('Y-m-d_H-i', time());

   // woohoo!
   return $match[1];
}
#68
<?php

$contents = '
/******************************************************************************/
--- Preparing for categories conversion...
/******************************************************************************/

TRUNCATE {$to_prefix}categories;

---{
// Add a tempID column.
$knownKeys = array();
$knownColumns = array(
   \'tempID\' => "ADD COLUMN tempID mediumint(8) NOT NULL default 0",
   \'tempID2\' => "ADD COLUMN tempID mediumint(8) NOT NULL default 0",
   \'tempID3\' => "ADD COLUMN tempID mediumint(8) NOT NULL default 0"
);
alterTable(\'categories\', $knownKeys, $knownColumns);
';

// Find all arrays.
preg_match_all('/^\s*\$(\S+)\s*=\s*(array\(.*?\);)/ms', $contents, $matches);

// Loop through our matches.
foreach ($matches[2] as $key => $data)
{
   // Get the keys and values of those arrays.
   preg_match("~'([a-zA-Z0-9]+)' => \"(.+?)\"(,)~", $data, $line);

   // The variable name.
   $variable = $matches[1][$key];

   // Empty array? Just forget it.
   if (empty($line[0]))
      continue;
   $string = strtolower($line[0]);

   // If it is for known columns, we do something different.
   if ($variable == 'knownColumns')
   {
      // Bring out the value.
      preg_match('~"([add|edit|drop]+ column)\s([a-zA-Z0-9]+)\s([a-zA-Z0-9]+)\((\d)\)+\s(not null|null)\s(default ([\d|\s\"\']+))"~', $string, $values);

      $result[$variable][$key] = array(
         'key' => $key,
         'variable' => $variable,
         'action' => trim($values[1]),
         'name' => trim($values[2]),
         'type' => trim($values[3]),
         'size' => trim($values[4]),
         'not_null' => trim($values[5]) == 'not null' ? true : false,
         'default' => strpos(trim($values[6]), 'default') !== false ? trim($values[7]) : null,
      );
   }
   // For this we will do different things.
   elseif ($variable == 'knownKeys')
   {
   
   }
}


$shouldbe = "
/******************************************************************************/
--- Preparing for categories conversion...
/******************************************************************************/

TRUNCATE {\$to_prefix}categories;

---{
// Add a temp_id column.
alterDatabase('categories', 'add column', array(
   'name' => 'temp_id',
   'type' => 'mediumint',
   'size' => 8,
   'default' => 0));
---}

";
?>
#69
// Format a block of code into a readable usable format.
function mod_format_php_code($data)
{
   global $context;

   // Convert all line endings to html returns.
   $data = preg_replace('~[\r]?\n~', "
", $data);

   // This part was borrowed from SMF. This is basically the code that handles formating the code bbc.
   $php_parts = preg_split('~(&lt;\?php|\?&gt;)~', $data, -1, PREG_SPLIT_DELIM_CAPTURE);
   for ($php_i = 0, $php_n = count($php_parts); $php_i < $php_n; $php_i++)
   {
      // Do PHP code coloring?
      if ($php_parts[$php_i] != '&lt;?php')
         continue;

      $php_string = '';
      while ($php_i + 1 < count($php_parts) && $php_parts[$php_i] != '?&gt;')
      {
         $php_string .= $php_parts[$php_i];
         $php_parts[$php_i++] = '';
      }
      $php_parts[$php_i] = highlight_php_code($php_string . $php_parts[$php_i]);
   }

   // Fix the PHP code stuff...
   $data = str_replace("<pre style=\"display: inline;\">\t", "\t", implode('', $php_parts));

   // Older browsers are annoying, aren\'t they?
   if ($context['browser']['is_ie4'] || $context['browser']['is_ie5'] || $context['browser']['is_ie5.5'])
      $data = str_replace("\t", "<pre style=\"display: inline;\">\t", $data);
   elseif (!$context['browser']['is_gecko'])
      $data = str_replace("\t", "<span style=\"white-space: pre;\">\t</span>", $data);
   else if (!$context['browser']['is_firefox'])
      $data = str_replace("\t", "&nbsp;&nbsp;&nbsp;", $data);

   // Firefox doesn't understand line breaks in <code> tags very well.
   if ($context['browser']['is_firefox'])
      return '<pre language="php" class="php_code">' . $data . '';
   return '<code>' . $data . '</code>';
}
#70
The test zone / test topic 3
Oct 14, 2008, 09:33 PM
test topic 3
#71
The test zone / test topic 2
Oct 14, 2008, 09:31 PM
test topic 2
#72
The test zone / test topic 1
Oct 14, 2008, 09:29 PM
test topic 1.
#73
The test zone / hr test
Oct 14, 2008, 06:13 PM
sfds




hehehe
#74
The test zone / smileys
Sep 16, 2008, 07:40 PM
 ??? ;D ;D ;D ::) :P
#75
The-SleePy-Laptop:~ jeremy$ mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 819
Server version: 5.1.25-rc MySQL Community Server (GPL)

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> use smf_svn__7502;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show full columns from smf_log_search_subjects;
+----------+-----------------------+-----------------+------+-----+---------+-------+---------------------------------+---------+
| Field    | Type                  | Collation       | Null | Key | Default | Extra | Privileges                      | Comment |
+----------+-----------------------+-----------------+------+-----+---------+-------+---------------------------------+---------+
| word     | varchar(20)           | utf8_general_ci | NO   | PRI |         |       | select,insert,update,references |         |
| id_topic | mediumint(8) unsigned | NULL            | NO   | PRI | 0       |       | select,insert,update,references |         |
+----------+-----------------------+-----------------+------+-----+---------+-------+---------------------------------+---------+
2 rows in set (0.00 sec)

mysql> show keys from smf_log_search_subjects;
+-------------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table                   | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+-------------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| smf_log_search_subjects |          0 | PRIMARY  |            1 | word        | A         |           3 |     NULL | NULL   |      | BTREE      |         |
| smf_log_search_subjects |          0 | PRIMARY  |            2 | id_topic    | A         |           3 |     NULL | NULL   |      | BTREE      |         |
| smf_log_search_subjects |          1 | id_topic |            1 | id_topic    | A         |           1 |     NULL | NULL   |      | BTREE      |         |
+-------------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
3 rows in set (0.00 sec)


#76
Return-path: <jsclee@ms47.hinet.net>
Envelope-to: xxxx@xxxxxx.com
Delivery-date: Fri, 12 Sep 2008 02:16:57 -0700
Received: from 66.89.158.2.ptr.us.xo.net ([66.89.158.2])
   by server.xxxxxx.com with esmtp (Exim 4.69)
   (envelope-from <jsclee@ms47.hinet.net>)
   id 1Ke4lp-0003PV-5D
   for xxxx@xxxxxx.com; Fri, 12 Sep 2008 02:16:57 -0700
Message-ID: <04752.rob@hiroshi>
Date: Fri, 12 Sep 2008 07:29:32 +0000
From: "ICS Monitoring Team" <jsclee@ms47.hinet.net>
User-Agent: Thunderbird 2.0.0.12 (Windows/20080213)
MIME-Version: 1.0
To: "client" <xxxx@xxxxxx.com>
Content-Type: multipart/mixed;
 boundary="830E5B4FC2D61AD"
X-Spam-Status: Yes, score=19.6
X-Spam-Score: 196
X-Spam-Bar: +++++++++++++++++++
X-Spam-Report: Spam detection software, running on the system "server.brainsg.com", has
   identified this incoming email as possible spam.  The original message
   has been attached to this so you can view it (if it isn't spam) or label
   similar future email.  If you have any questions, see
   the administrator of that system for details.
   Content preview:  Your internet access is going to get suspended The Internet
   Service Provider Consorcium was made to protect the rights of software authors,
   artists. We conduct regular wiretapping on our networks, to monitor criminal
   acts. [...]
   Content analysis details:   (19.6 points, 4.0 required)
   pts rule name              description
   ---- ---------------------- --------------------------------------------------
   3.0 RCVD_IN_XBL            RBL: Received via a relay in Spamhaus XBL
   [66.89.158.2 listed in zen.spamhaus.org]
   4.4 HELO_DYNAMIC_IPADDR2   Relay HELO'd using suspicious hostname (IP addr
   2)
   3.5 HELO_DYNAMIC_SPLIT_IP  Relay HELO'd using suspicious hostname (Split
   IP)
   1.9 TVD_RCVD_IP            TVD_RCVD_IP
   2.0 RCVD_IN_BL_SPAMCOP_NET RBL: Received via a relay in bl.spamcop.net
   [Blocked - see <http://www.spamcop.net/bl.shtml?66.89.158.2>]
   2.1 RCVD_NUMERIC_HELO      Received: contains an IP address used for HELO
   2.0 BAYES_80               BODY: Bayesian spam probability is 80 to 95%
   [score: 0.8241]
   0.6 RCVD_IN_SORBS_WEB      RBL: SORBS: sender is a abuseable web server
   [66.89.158.2 listed in dnsbl.sorbs.net]
   0.1 RDNS_DYNAMIC           Delivered to trusted network by host with
   dynamic-looking rDNS
X-Spam-Flag: YES
Subject: ***SPAM*** Your internet access is going to get suspended

This is a multi-part message in MIME format.

--830E5B4FC2D61AD
Content-Type: text/plain;
 charset=iso-8859-1
Content-Transfer-Encoding: 7bit

Your internet access is going to get suspended

The Internet Service Provider Consorcium was made to protect the rights of software authors, artists.
We conduct regular wiretapping on our networks, to monitor criminal acts.

We are aware of your illegal activities on the internet wich were originating from

You can check the report of your activities in the past 6 month that we have attached. We strongly advise you to stop your activities regarding the illegal downloading of copyrighted material of your internet access will be suspended.

Sincerely
ICS Monitoring Team


#77
The test zone / The colors
Sep 11, 2008, 07:29 PM
Not Black

Red

Yellow

Pink

Green

Orange

Purple

Blue

Beige

Brown

Teal

Navy

Maroon

Lime Green

White


#78
The test zone / test editor
Sep 09, 2008, 08:16 PM
"For topics and boards I've requested notification on, notify me of:" fdfs
#79
The test zone / Polls Test - Multiple Optoins
Sep 09, 2008, 05:55 PM
 ;D ;D ;D :D :D :-[ :-* :'(
#80
<?php
/**********************************************************************************
* convert.php                                                                     *
***********************************************************************************
* SMF: Simple Machines Forum                                                      *
* Open-Source Project Inspired by Zef Hemel (zef@zefhemel.com)                    *
* =============================================================================== *
* Software Version:           SMF 2.0                                             *
* Software by:                Simple Machines (http://www.simplemachines.org)     *
* Copyright 2006 by:          Simple Machines LLC (http://www.simplemachines.org) *
*           2001-2006 by:     Lewis Media (http://www.lewismedia.com)             *
* Support, News, Updates at:  http://www.simplemachines.org                       *
***********************************************************************************
* This program is free software; you may redistribute it and/or modify it under   *
* the terms of the provided license as published by Simple Machines LLC.          *
*                                                                                 *
* This program is distributed in the hope that it is and will be useful, but      *
* WITHOUT ANY WARRANTIES; without even any implied warranty of MERCHANTABILITY    *
* or FITNESS FOR A PARTICULAR PURPOSE.                                            *
*                                                                                 *
* See the "license.txt" file for details of the Simple Machines license.          *
* The latest version can always be found at http://www.simplemachines.org.        *
**********************************************************************************/
ob_start();
require_once(dirname(__FILE__) . '/SSI.php');
initialize_inputs();
show_header();

$my_func = 'doStep' . (!empty($_REQUEST['step']) ? $_REQUEST['step'] : 0);

if (function_exists($my_func))
   $my_func();
else
   doStep0();

show_footer();

function initialize_inputs()
{
   global $this_url, $smcFunc, $tables, $column_default, $special_tables;

   // In SMF 2.0 we need this.
   if (function_exists('db_extend'))
      db_extend('packages');

   // Turn off magic quotes runtime and enable error reporting.
   if (function_exists('set_magic_quotes_runtime'))
      @set_magic_quotes_runtime(0);
   error_reporting(E_ALL);

   // Add slashes, as long as they aren't already being added.
   if (!function_exists('get_magic_quotes_gpc') || @get_magic_quotes_gpc() == 0)
   {
      foreach ($_POST as $k => $v)
         $_POST[$k] = addslashes($v);
   }

   $_GET['a'] = (string) @$_GET['a'];
   $this_url = 'http://' . (empty($_SERVER['HTTP_HOST']) ? $_SERVER['SERVER_NAME'] . (empty($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == '80' ? '' : ':' . $_SERVER['SERVER_PORT']) : $_SERVER['HTTP_HOST']) . $_SERVER['PHP_SELF'];

   // Tables that have the membergroup id in them. (table_name => column_name)
   $tables = array(
      'membergroups' => 'id_group',
      'board_permissions' => 'id_group',
      'members' => 'id_group',
      'permissions' => 'id_group',
      'boards' => 'member_groups',
      'members' => 'additional_groups'
   );

   // Lets us know our special tables.
   $special_tables = array(
      'boards' => 'id_board',
      'members' => 'id_member'
   );

   // Default column info for reverting.
   $column_default = array(
      'id_group' => array('type' => 'smallint', 'size' => 5),
      'additional_groups' => array('type' => 'tinytext'),
      'member_groups' => array('type' => 'varchar', 'size' => 255),
   );
      
}

// Welcome you.
function doStep0()
{
   global $this_url, $user_info;

   if ($user_info['is_guest'] || !$user_info['is_admin'])
   {
      ssi_login();
      exit;
   }

echo '
<form method="post" action="', $this_url, '?step=1">
   <div class="panel">
      <h2>Welcome, ', $user_info['username'], '</h2>
      <p>Welcome to the recount Membergroup ID script.</p>
      <div class="error_message">BE SURE TO RUN BACKUPS BEFORE PROCEEDING WITH THIS!!!</div>
      <p>This script will recount all your membergroup IDs to use lower numbers. Why? Well some people during conversions may receive extremely high membergroup IDs that can cause issues. The purpose of this script to to help prevent that by recounting the ids.</p>
      <p>Are you ready? Click <input type="submit" name="submit" value="submit" /> to start</p>   
   </div>
</form>';

}

// Alter the columns in preperation.
function doStep1()
{
   global $this_url, $db_prefix, $tables, $special_tables;

   script_modify_column('membergroups', 'id_group', array('auto' => false));

   foreach ($tables AS $table => $column)
      if (empty($special_tables[$table]))
         script_modify_column($table, $column, array('type' => 'bigint'));
      else
         script_modify_column($table, $column, array('type' => 'longtext'));

   echo '
   <div class="panel">
      <h3>The conversion may start now</h3>
      <p>If you have not yet converted the forum. You should do so now as the tables have been altered to hold bigger values for their Category IDs</p>
   </div>';

   show_pause(2);
}

// Update all of the ids to be higher than 255 (Prevents issues).
function doStep2()
{
   global $this_url, $db_prefix, $tables, $special_tables;

   // Get the CATS.
   $request = script_query("
      SELECT
         id_group AS group_id, id_group AS g_order
      FROM {$db_prefix}membergroups
      WHERE id_group > 8
      ORDER BY id_group ASC");

   $cats = array();
   while ($row = script_fetch($request))
      $cats[$row['group_id'] + 255] = $row['g_order'];

   foreach ($tables as $table => $column)
   {
      // A regular table.
      if (empty($special_tables[$table]))
         script_query("
            UPDATE {$db_prefix}{$table}
            SET id_group = {$column} + 255
            WHERE id_group > 8");
      else
      {
         $key_column = $special_tables[$table];

         // Now for the dirty work for our less easy tables.
         $request = script_query("
            SELECT {$column} as maincol, {$key_column} as keycol
            FROM {$db_prefix}{$table}");

         // Loop through it quickly for each entry (this could suck for a big board members table).
         while ($row = script_fetch($request))
         {
            // Get our keys.
            $key_select = $row['keycol'];
            $temp = explode(',', $row['maincol']);

            // For each group, add 255 to it.
            foreach ($temp as $key => $gtemp)
               if ($gtemp > 9)
                  $temp[$key] = $gtemp + 255;

            // Back into a string now.
            $groups = implode(',', $temp);

            // Back into the entry from which you came.
            script_query("
               UPDATE {$db_prefix}{$table}
               SET {$column} = '{$groups}'
               WHERE {$key_column} = {$key_select}");
         }
      }
   }

   show_pause(3);
}

// Update the columns now
function doStep3()
{
   global $this_url, $db_prefix, $tables, $special_tables;

   // Get the CATS.
   $request = script_query("
      SELECT
         id_group AS group_id
      FROM {$db_prefix}membergroups
      WHERE id_group > 8
      ORDER BY id_group ASC");

   $groups = array();
   $new_id = 8;
   while ($row = script_fetch($request))
      $groups[$row['group_id']] = ++$new_id;

echo '
', var_dump($groups), '
';

   // Now we actually update it.
   foreach ($tables as $table => $column)
   {
      // A regular table.
      if (empty($special_tables[$table]))
      {
/*         foreach ($groups as $old_id => $new_id)
            script_query("
               UPDATE {$db_prefix}{$table}
               SET {$column} = {$new_id}
               WHERE {$column} = {$old_id}");
*/
// Just say no for now.
      }
      else
      {
         $key_column = $special_tables[$table];

         // Now for the dirty work for our less easy tables.
         $request = script_query("
            SELECT {$column} as maincol, {$key_column} as keycol
            FROM {$db_prefix}{$table}");

         // This could get messy for big boards.
         while ($row = script_fetch($request))
         {
            // We need to know our keys.
            $key_select = $row['keycol'];
            $temp = explode(',', $row['maincol']);

            foreach ($temp as $key => $value)
               $temp[$key] = (int) $value;

echo 'ID:' . $key_select . '
';
echo '---pre temp:' . $row['maincol'] . '
';
echo '---pre temp array:
' . var_dump($temp, true) . '

';
echo '---findings:';

            // This is easy, just find the info in the array.
            $groups = '';
            foreach ($temp as $gtemp)
            {
               $gtemp = (int) $gtemp;
               if ($gtemp > 9)
{
echo '(' . $gtemp . ':' . $groups[$gtemp] . ')';
                  $groups .= $groups[$gtemp] . ',';
}
               else
                  $groups .= $gtemp;
            }

            // Now back into a string.
            $groups = substr($groups, 0, -1);

echo '
---after temp:' . $groups . '
';


/*            // Back into the entry you came from!
            script_query("
               UPDATE {$db_prefix}{$table}
               SET {$column} = '{$groups}'
               WHERE {$key_column} = {$key_select}");
*/
         }
      }
   }

   show_pause(4);
}

// Reset some stuff and get out.
function doStep4()
{
   global $this_url, $db_prefix, $tables, $column_default;

   // Now to get the auto_increment setup.
   $request = script_query("
      SELECT MAX(id_group) AS group_id
      FROM {$db_prefix}membergroups
      LIMIT 1");

   list($max_cat_id) = script_fetch($request, true);

   if (isset($smcFunc['db_change_column']))
   {
      // Once to drop it.
      $smcFunc['db_change_column']("{$db_prefix}membergroups", 'id_cat',
         array(
            'name' => 'id_group',
            'auto' => true,
         ), array('no_prefix' => true));
      // Again to add it.
      $smcFunc['db_change_column']("{$db_prefix}membergroups", 'id_cat',
         array(
            'name' => 'id_group',
            'auto' => true,
         ), array('no_prefix' => true));
   }
   else
   {
      // Its actually easier.
      script_query("
         ALTER TABLE {$db_prefix}membergroups AUTO_INCREMENT=" . ++$max_cat_id);
   }

   foreach ($tables AS $table => $column)
      script_modify_column($table, $column, $column_default[$column]);

   // Call it directly
   doStep5();
}

function doStep5()
{
   echo '
   <div class="panel">
      <h2>Process completed</h2>
      <p>That wasn\'t to hard was it?</p>';

}

function show_pause($next_step)
{
   global $this_url;

   echo '
<form method="post" action="', $this_url, '?step=', $next_step, '">
   <div class="panel">
      <h2>Process paused</h2>
      <p>The script has been halted here to prevent overloading the server.</p>
      <p>Are you ready? Click <input type="submit" name="submit" value="submit" /> to continue</p>   
   </div>
</form>';
}
function show_header()
{
   global $start_time, $txt;
   $start_time = time();

   $smfsite = 'http://simplemachines.org/smf';

   echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"', !empty($txt['lang_rtl']) ? ' dir="rtl"' : '', '>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=', isset($txt['lang_character_set']) ? $txt['lang_character_set'] : 'ISO-8859-1', '" />
      <title>SMF Recount Category script</title>
      <script language="JavaScript" type="text/javascript" src="Themes/default/scripts/script.js"></script>
      <link rel="stylesheet" type="text/css" href="', $smfsite, '/style.css" />
   </head>
   <body>
      <div id="header">
         <a href="http://www.simplemachines.org/" target="_blank"><img src="', $smfsite, '/smflogo.gif" style="float: ', empty($txt['lang_rtl']) ? 'right' : 'left', ';" alt="Simple Machines" border="0" /></a>
         <div title="Moogle Express!">Recount Category script</div>
      </div>
      <div id="content">
         <table width="100%" border="0" cellpadding="0" cellspacing="0" style="padding-top: 1ex;">
         <tr>
            <td width="250" valign="top" style="padding-right: 10px;">
               <table border="0" cellpadding="8" cellspacing="0" class="tborder" width="240">
                  <tr>
                     <td class="titlebg">Recount Steps</td>
                  </tr>
                  <tr>
                     <td class="windowbg2">
                  <span class="', empty($_REQUEST['step']) ? 'stepcurrent' : 'stepwaiting', '">Welcome</span>

                  <span class="', !empty($_REQUEST['step']) && $_REQUEST['step'] == 1 ? 'stepcurrent' : 'stepwaiting', '">Alter Tables</span>

                  <span class="', !empty($_REQUEST['step']) && $_REQUEST['step'] == 2 ? 'stepcurrent' : 'stepwaiting', '">Update Columns</span>

                  <span class="', !empty($_REQUEST['step']) && $_REQUEST['step'] == 3 ? 'stepcurrent' : 'stepwaiting', '">Correct Categorys</span>

                  <span class="', !empty($_REQUEST['step']) && $_REQUEST['step'] == 4 ? 'stepcurrent' : 'stepwaiting', '">Clean up</span>

                     </td>
                  </tr>
               </table>
            </td>
            <td width="100%" valign="top">';
}

function show_footer()
{
   echo '
      </div>
   </body>
</html>';
}

function script_query($query, $file = __FILE__, $line = __LINE__)
{
   global $smcFunc, $func;
   
   if (isset($smcFunc['db_query']))
      return $smcFunc['db_query']('', $query, 'security_override');
   elseif (function_exists('db_query'))
   {
      $query = str_replace(
         array(
            'id_group',
            'member_groups',
            'additional_groups',
            'id_board',
            'id_member',
         ),
         array(
            'ID_GROUP',
            'memberGroups',
            'additionalGroups',
            'ID_BOARD',
            'ID_MEMBER',
         ), $query);
      return db_query($query, $file, $line);
   }
   else
      exit('No valid version of SMF found');
}

function script_fetch($resource_id, $use_row = false)
{
   global $smcFunc, $func;

   if ($use_row)
   {
      if (isset($smcFunc['db_fetch_row']))
         return $smcFunc['db_fetch_row']($resource_id);
      else
         return mysql_fetch_row($resource_id);
   }
   else
   {
      if (isset($smcFunc['db_fetch_assoc']))
         return $smcFunc['db_fetch_assoc']($resource_id);
      else
         return mysql_fetch_assoc($resource_id);
   }
}

function script_modify_column($table_name, $column_name, $column_info)
{
   global $smcFunc, $func, $db_prefix;

   if (isset($smcFunc['db_add_column']))
   {
      $column_info = array_merge($column_info, array('no_prefix' => true));
      return $smcFunc['db_change_column']("{$db_prefix}{$table_name}", $column_name, $column_info, array('no_prefix' => TRUE));
   }
   else
   {
      $columns = script_list_columns("{$db_prefix}{$table_name}");
      $old_info = null;
      foreach ($columns as $column)
         if (strtolower($column['name']) == strtolower($column_name))
            $old_info = $column;

      // Get the right bits.
      if (!isset($column_info['name']))
         $column_info['name'] = $column_name;
      if (!isset($column_info['default']))
         $column_info['default'] = $old_info['default'];
      if (!isset($column_info['null']))
         $column_info['null'] = $old_info['null'];
      if (!isset($column_info['auto']))
         $column_info['auto'] = $old_info['auto'];
      if (!isset($column_info['type']))
         $column_info['type'] = $old_info['type'];
      if (!isset($column_info['size']))
         $column_info['size'] = $old_info['size'];
      else
         $column_info['size'] = '(' . $column_info['size'] . ')';

      $column_info['type'] .= $column_info['size'];

      return script_query('ALTER TABLE ' . $db_prefix . $table_name . '
         CHANGE `' . $column_info['name'] . '` `' . $column_info['name'] . '` ' . $column_info['type'] . ' ' . (empty($column_info['null']) ? 'NOT NULL' : '') . ' ' .
      (empty($column_info['default']) ? '' : 'default \'' . $column_info['default'] . '\'') . ' ' .
      (empty($column_info['auto']) ? '' : 'auto_increment') . ' ');
   }
}

function script_list_columns($table_name)
{
   $result = script_query('
      SHOW FIELDS
      FROM ' . $table_name);
   $columns = array();
   while ($row = mysql_fetch_assoc($result))
   {
      // Is there an auto_increment?
      $auto = strpos($row['Extra'], 'auto_increment') !== false ? true : false;

      // Can we split out the size?
      if (preg_match('~(.+?)\s*(\(\d+\))~i', $row['Type'], $matches))
      {
         $type = $matches[1];
         $size = $matches[2];
      }
      else
      {
         $type = $row['Type'];
         $size = null;
      }

      $columns[] = array(
         'name' => $row['Field'],
         'null' => $row['Null'] != 'YES' ? false : true,
         'default' => isset($row['Default']) ? $row['Default'] : null,
         'type' => $type,
         'size' => $size,
         'auto' => $auto,
      );
   }
   mysql_free_result($result);

   return $columns;
}
?>