Permalink
Browse files

Added some functions for command line and whatnot.

  • Loading branch information...
1 parent 7243b2c commit 5af03af77b8071ff20981c4c713c0c399e115e57 @tburry tburry committed Nov 13, 2012
Showing with 372 additions and 0 deletions.
  1. +189 −0 functions.commandline.php
  2. +183 −0 functions.php
View
189 functions.commandline.php
@@ -0,0 +1,189 @@
+<?php
+
+$GlobalOptions = array(
+ 'host' => array('Host to connect to (IP address or hostname).', 'Req' => TRUE, 'Sx' => ':', 'Field' => 'dbhost'),
+ 'dbname' => array('The name of the database.', 'Req' => TRUE, 'Sx' => ':', 'Field' => 'dbname'),
+ 'user' => array('The username of the database.', 'Req' => TRUE, 'Sx' => ':', 'Field' => 'dbuser', 'Short' => 'u'),
+ 'password' => array('The password to use when connecting to the server.', 'Sx' => '::', 'Field' => 'dbpass', 'Short' => 'p', 'Default' => ''),
+ 'type' => array('The type of forum to export from.', 'Req' => TRUE, 'Sx' => ':', 'Field' => 'type'),
+ 'prefix' => array('The table prefix in the database.', 'Field' => 'prefix', 'Default' => ''),
+ 'help' => array('Show help.')
+);
+
+// Go through all of the supported types and add them to the type description.
+$GlobalOptions['type']['Values'] = array_keys($Supported);
+
+function GetAllCommandLineOptions($Sections = FALSE) {
+ global $GlobalOptions, $Supported;
+
+ if ($Sections)
+ $Result['Global Options'] = $GlobalOptions;
+ else
+ $Result = $GlobalOptions;
+
+ foreach ($Supported as $Type => $Options) {
+ $CommandLine = V('CommandLine', $Options);
+ if (!$CommandLine)
+ continue;
+
+ if ($Sections) {
+ $Result[$Options['name']] = $CommandLine;
+ } else {
+ // We need to add the types to each command line option for validation purposes.
+ foreach ($CommandLine as $LongCode => $Row) {
+ if (isset($Result[$LongCode])) {
+ $Result[$LongCode]['Types'][] = $Type;
+ } else {
+ $Row['Types'] = array($Type);
+ $Result[$LongCode] = $Row;
+ }
+ }
+ }
+ }
+
+ return $Result;
+}
+
+function GetOptCodes($Options) {
+ $ShortCodes = '';
+ $LongCodes = array();
+
+ foreach ($Options as $LongCode => $Row) {
+ $Sx = V('Sx', $Row, '');
+ $Short = V('Short', $Row, '');
+
+ if ($Short)
+ $ShortCodes .= $Short.$Sx;
+ $LongCodes[] = $LongCode.$Sx;
+ }
+
+ return array($ShortCodes, $LongCodes);
+}
+
+function ParseCommandLine() {
+ $CommandOptions = GetAllCommandLineOptions();
+ list($ShortCodes, $LongCodes) = GetOptCodes($CommandOptions);
+
+// print_r($LongCodes);
+
+ $Opts = getopt($ShortCodes, $LongCodes);
+
+ if (isset($Opts['help'])) {
+ WriteCommandLineHelp();
+ die();
+ }
+
+ $Opts = ValidateCommandLine($Opts, $CommandOptions);
+
+ if ($Opts === FALSE)
+ die();
+
+ $_POST = $Opts;
+}
+
+function ValidateCommandLine($Values, $Options) {
+ $Errors = array();
+ $Result = array();
+
+// print_r($Values);
+// print_r($Options);
+
+ $Type = V('type', $Values, V('t', $Values));
+
+ foreach ($Options as $LongCode => $Row) {
+ $Req = V('Req', $Row);
+ $Short = V('Short', $Row);
+
+ $Sx = V('Sx', $Row);
+ $Types = V('Types', $Row);
+
+ if ($Types && !in_array($Type, $Types)) {
+ echo "Skipping $LongCode\n";
+
+ continue;
+ }
+
+ if (isset($Values[$LongCode])) {
+ $Value = $Values[$LongCode];
+ if (!$Value)
+ $Value = TRUE;
+ } elseif ($Short && isset($Values[$Short])) {
+ $Value = $Values[$Short];
+ if (!$Value)
+ $Value = TRUE;
+ } elseif (isset($Row['Default'])) {
+ $Value = $Row['Default'];
+ } else {
+ $Value = NULL;
+ }
+
+ if (!$Value) {
+ $Default = V('Default', $Row, NULL);
+ if ($Default === NULL) {
+ if ($Req) {
+ $Errors[] = "Missing required parameter: $LongCode";
+ }
+
+ continue;
+ } else {
+ $Value = $Default;
+ }
+ }
+
+ if ($AllowedValues = V('Values', $Row)) {
+ if (!in_array($Value, $AllowedValues)) {
+ $Errors[] = "Invalid value for parameter: $LongCode. Must be one of: ".implode(', ', $AllowedValues);
+ continue;
+ }
+ }
+
+ $Field = V('Field', $Row, $LongCode);
+ $Result[$Field] = $Value;
+ }
+
+ if (count($Errors)) {
+ echo implode("\n", $Errors)."\n";
+ return FALSE;
+ }
+
+
+ return $Result;
+}
+
+function WriteCommandLineHelp($Options = NULL, $Section = '') {
+ if ($Options === NULL) {
+ $Options = GetAllCommandLineOptions(TRUE);
+ foreach ($Options as $Section => $Options) {
+ WriteCommandLineHelp($Options, $Section);
+ }
+ return;
+ }
+
+ echo "$Section\n\n";
+ foreach ($Options as $Longname => $Options) {
+ echo " ";
+
+ if (isset($Options['Short']))
+ echo '-'.$Options['Short'].', ';
+
+ echo "--$Longname";
+
+ if (!V('Req', $Options))
+ echo ' (Optional)';
+
+ echo "\n {$Options[0]}\n";
+
+ if ($Values = V('Values', $Options)) {
+ echo ' Valid Values: '.implode(', ', $Values)."\n";
+ }
+
+ echo "\n";
+ }
+}
+
+function V($Name, $Array, $Default = NULL) {
+ if (isset($Array[$Name]))
+ return $Array[$Name];
+ return $Default;
+}
+?>
View
183 functions.php
@@ -0,0 +1,183 @@
+<?php
+
+function decho($Var, $Prefix = 'debug') {
+ echo '<pre><b>'.$Prefix.'</b>: '.htmlspecialchars(print_r($Var, TRUE)).'</pre>';
+}
+
+function GenerateThumbnail($Path, $ThumbPath, $Height = 50, $Width = 50) {
+ list($WidthSource, $HeightSource, $Type) = getimagesize($Path);
+
+ if (!$WidthSource)
+ return FALSE;
+
+ if (!file_exists(dirname($ThumbPath)))
+ mkdir(dirname($ThumbPath), 0777, TRUE);
+
+ if ($WidthSource <= $Width && $HeightSource <= $Width) {
+ copy($Path, $ThumbPath);
+ return TRUE;
+ }
+
+ $XCoord = 0;
+ $YCoord = 0;
+ $HeightDiff = $HeightSource - $Height;
+ $WidthDiff = $WidthSource - $Width;
+ if ($WidthDiff > $HeightDiff) {
+ // Crop the original width down
+ $NewWidthSource = round(($Width * $HeightSource) / $Height);
+
+ // And set the original x position to the cropped start point.
+ $XCoord = round(($WidthSource - $NewWidthSource) / 2);
+ $WidthSource = $NewWidthSource;
+ } else {
+ // Crop the original height down
+ $NewHeightSource = round(($Height * $WidthSource) / $Width);
+
+ // And set the original y position to the cropped start point.
+ $YCoord = round(($HeightSource - $NewHeightSource) / 2);
+ $HeightSource = $NewHeightSource;
+ }
+
+ switch ($Type) {
+ case 1:
+ $SourceImage = imagecreatefromgif($Path);
+ break;
+ case 2:
+ $SourceImage = imagecreatefromjpeg($Path);
+ break;
+ case 3:
+ $SourceImage = imagecreatefrompng($Path);
+ imagealphablending($SourceImage, TRUE);
+ break;
+ }
+
+ $TargetImage = imagecreatetruecolor($Width, $Height);
+ imagecopyresampled($TargetImage, $SourceImage, 0, 0, $XCoord, $YCoord, $Width, $Height, $WidthSource, $HeightSource);
+ imagedestroy($SourceImage);
+
+ switch ($Type) {
+ case 1:
+ imagegif($TargetImage, $ThumbPath);
+ break;
+ case 2:
+ imagejpeg($TargetImage, $ThumbPath);
+ break;
+ case 3:
+ imagepng($TargetImage, $ThumbPath);
+ break;
+ }
+ imagedestroy($TargetImage);
+ return TRUE;
+}
+
+function ParseSelect($Sql) {
+ if (!preg_match('`^\s*select\s+(.+)\s+from\s+(.+)\s*`is', $Sql, $Matches)) {
+ trigger_error("Could not parse '$Sql'", E_USER_ERROR);
+ }
+ $Result = array('Select' => array(), 'From' => '');
+ $Select = $Matches[1];
+ $From = $Matches[2];
+
+ // Replace commas within function calls.
+ $Select = preg_replace_callback('`\(([^)]+?)\)`', '_ReplaceCommas', $Select);
+// echo($Select);
+ $Parts = explode(',', $Select);
+
+ $Selects = array();
+ foreach ($Parts as $Expr) {
+ $Expr = trim($Expr);
+ $Expr = str_replace('!COMMA!', ',', $Expr);
+
+ // Check for the star match.
+ if (preg_match('`(\w+)\.\*`', $Expr, $Matches)) {
+ $Result['Star'] = $Matches[1];
+ }
+
+ // Check for an alias.
+ if (preg_match('`^(.*)\sas\s(.*)$`is', $Expr, $Matches)) {
+// decho($Matches, 'as');
+ $Alias = trim($Matches[2], '`');
+ $Selects[$Alias] = $Matches[1];
+ } elseif (preg_match('`^[a-z_]?[a-z0-9_]*$`i', $Expr)) {
+ // We are just selecting one column.
+ $Selects[$Expr] = $Expr;
+ } elseif (preg_match('`^[a-z_]?[a-z0-9_]*\.([a-z_]?[a-z0-9_]*)$`i', $Expr, $Matches)) {
+ // We are looking at an alias'd select.
+ $Alias = $Matches[1];
+ $Selects[$Alias] = $Expr;
+ } else {
+ $Selects[] = $Expr;
+ }
+ }
+
+ $Result['Select'] = $Selects;
+ $Result['From'] = $From;
+ $Result['Source'] = $Sql;
+ return $Result;
+}
+
+function _ReplaceCommas($Matches) {
+ return str_replace(',', '!COMMA!', $Matches[0]);
+}
+
+/**
+ *
+ * @param type $Sql
+ * @param array $Columns An array in the form Alias => Column or just Column
+ * @return type
+ */
+function ReplaceSelect($Sql, $Columns) {
+ if (is_string($Sql)) {
+ $Parsed = ParseSelect($Sql);
+ } else {
+ $Parsed = $Sql;
+ }
+
+ // Set a prefix for new selects.
+ if (isset($Parsed['Star']))
+ $Px = $Parsed['Star'].'.';
+ else
+ $Px = '';
+
+ $Select = $Parsed['Select'];
+
+ $NewSelect = array();
+ foreach ($Columns as $Index => $Value) {
+ if (is_numeric($Index))
+ $Alias = $Value;
+ else
+ $Alias = $Index;
+
+ if (isset($Select[$Value])) {
+ $NewSelect[$Alias] = $Select[$Value];
+ } else {
+ $NewSelect[$Alias] = $Px.$Value;
+ }
+ }
+ $Parsed['Select'] = $NewSelect;
+
+ if (is_string($Sql)) {
+ return SelectString($Parsed);
+ } else {
+ return $Parsed;
+ }
+}
+
+function SelectString($Parsed) {
+ // Build the select.
+ $Parts = $Parsed['Select'];
+ $Selects = array();
+ foreach ($Parts as $Alias => $Expr) {
+ if (is_numeric($Alias) || $Alias == $Expr)
+ $Selects[] = $Expr;
+ else
+ $Selects[] = "$Expr as `$Alias`";
+ }
+ $Select = implode(",\n ", $Selects);
+
+ $From = $Parsed['From'];
+
+ $Result = "select\n $Select\nfrom $From";
+ return $Result;
+}
+?>

0 comments on commit 5af03af

Please sign in to comment.