Browse Source

Reformat.

Joe Clarke 1 year ago
parent
commit
afdfb875e7

+ 123 - 113
www/add_logic.php

@@ -43,7 +43,7 @@ try {
     die($e->getMessage());
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Add Logical Switch');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Add Logical Switch');
 if ($logger === false) {
     die("Failed to open logfile.\n");
 }
@@ -72,18 +72,18 @@ if (isset($_REQUEST['submit'])) {
             continue;
         }
         if ($pid[$i] == '__BOGUS__') {
-            array_push($errors, 'Please select a Product ID on row '.($i + 1));
+            array_push($errors, 'Please select a Product ID on row ' . ($i + 1));
         }
 
         /*if ($ports[$i] == '__BOGUS__') {
-            array_push($errors, 'Please select ports required on row '.($i + 1));
+        array_push($errors, 'Please select ports required on row '.($i + 1));
         }*/
         if ($mdf[$i] == '__BOGUS__') {
-            array_push($errors, 'Please select an MDF for row '.($i + 1));
+            array_push($errors, 'Please select an MDF for row ' . ($i + 1));
         }
 
         if (ADDRESS_SCHEME == 'IDF' && $idf[$i] == '__BOGUS__' && $curr_idf == 0) {
-            array_push($errors, 'Please select an IDF for row '.($i + 1));
+            array_push($errors, 'Please select an IDF for row ' . ($i + 1));
         }
 
         $name[$i] = trim($name[$i]);
@@ -100,7 +100,7 @@ if (isset($_REQUEST['submit'])) {
                         $sth = $dbh->prepare($sql);
                         $sth->execute(array($idf[$i]));
                     } catch (PDOException $e) {
-                        array_push($errors, 'Failed to get IDF IP for row '.($i + 1).": {$e->getMessage()}");
+                        array_push($errors, 'Failed to get IDF IP for row ' . ($i + 1) . ": {$e->getMessage()}");
                     }
                     if ($sth !== null) {
                         $row = $sth->fetch();
@@ -108,20 +108,20 @@ if (isset($_REQUEST['submit'])) {
 
                         preg_match("/^(\d+\.\d+\.\d+\.)/", $row['ip_address'], $matches);
                         $sql = 'SELECT address FROM ADDRESSES WHERE location = ? AND address LIKE ? AND used = ? AND reserved = ? ORDER BY INET_ATON(address) LIMIT 1';
-                        $params = array($mdf[$i], $matches[1].'%', '0', '0');
+                        $params = array($mdf[$i], $matches[1] . '%', '0', '0');
                     }
                 } elseif (ADDRESS_SCHEME == 'NEXT_FREE') {
                     $sql = 'SELECT address FROM ADDRESSES WHERE location = ? AND used = ? AND reserved = ? ORDER BY INET_ATON(address) LIMIT 1';
                     $params = array($mdf[$i], '0', '0');
                 } elseif (ADDRESS_SCHEME == 'DNS') {
-                    $hostname = $name[$i].'.'.DNS_ZONE;
+                    $hostname = $name[$i] . '.' . DNS_ZONE;
                     $ip = gethostbyname($hostname);
                     if ($ip == $hostname) {
                         $ip = gethostbyname($name[$i]);
                         if ($ip == $name[$i]) {
                             /* Don't make this fatal as we can fallback to manual
-                             * allocation.
-                             array_push($errors, "Unable to obtain IP address for either $hostame or {$name[$i]} on row " . ($i + 1));*/
+                            * allocation.
+                            array_push($errors, "Unable to obtain IP address for either $hostame or {$name[$i]} on row " . ($i + 1));*/
                             $ip = null;
                         }
                     }
@@ -134,10 +134,10 @@ if (isset($_REQUEST['submit'])) {
                             $row = $sth->fetch();
                             $sth->closeCursor();
                             if (!$row['address']) {
-                                array_push($errors, "IP address $ip is not valid in the ZTP system for {$name[$i]} at row ".($i + 1));
+                                array_push($errors, "IP address $ip is not valid in the ZTP system for {$name[$i]} at row " . ($i + 1));
                             }
                         } catch (PDOException $e) {
-                            array_push($errors, 'Failed to validate IP for row '.($i + 1).": {$e->getMessage()}");
+                            array_push($errors, 'Failed to validate IP for row ' . ($i + 1) . ": {$e->getMessage()}");
                         }
                     }
                 }
@@ -150,7 +150,7 @@ if (isset($_REQUEST['submit'])) {
                         $sth->closeCursor();
                         $ip = $row['address'];
                     } catch (PDOException $e) {
-                        array_push($errors, 'Failed to get next IP for row '.($i + 1).": {$e->getMessage()}");
+                        array_push($errors, 'Failed to get next IP for row ' . ($i + 1) . ": {$e->getMessage()}");
                     }
                 }
             }
@@ -170,11 +170,11 @@ if (isset($_REQUEST['submit'])) {
                             $sth->execute(array('1', $ip));
                             $sth->closeCursor();
                         } catch (PDOException $ie) {
-                            array_push($errors, 'Failed to checkout IP for row '.($i + 1).": {$ie->getMessage()}");
+                            array_push($errors, 'Failed to checkout IP for row ' . ($i + 1) . ": {$ie->getMessage()}");
                         }
                     }
                 } catch (PDOException $e) {
-                    array_push($errors, 'Failed to add new logical switch for row '.($i + 1).": {$e->getMessage()}");
+                    array_push($errors, 'Failed to add new logical switch for row ' . ($i + 1) . ": {$e->getMessage()}");
                 }
             }
         }
@@ -209,120 +209,130 @@ foreach ($MDFS as $m) {
     }
 }
 
-print_header(TOOL_NAME.': Add Logical Switch');
+print_header(TOOL_NAME . ': Add Logical Switch');
 ?>
-  <body class="flex">
-<script language="Javascript">
-var idfs = JSON.parse('<?=json_encode($idfs)?>');
-function onMDFChange(mdf, row) {
-	var midfs = idfs[mdf];
-	var sel = document.getElementById('idf['+row+']');
-	deleteOptions(sel);
-	createOption(sel, '--Please Select--', '__BOGUS__');
-	for (mi in midfs) {
-		createOption(sel, midfs[mi], midfs[mi]);
-	}
-}
 
-</script>
+<body class="flex">
+    <script language="Javascript">
+        var idfs = JSON.parse('<?= json_encode($idfs) ?>');
+        function onMDFChange(mdf, row) {
+            var midfs = idfs[mdf];
+            var sel = document.getElementById('idf[' + row + ']');
+            deleteOptions(sel);
+            createOption(sel, '--Please Select--', '__BOGUS__');
+            for (mi in midfs) {
+                createOption(sel, midfs[mi], midfs[mi]);
+            }
+        }
+
+    </script>
     <div id="headswreg">
         <div id="header">
-	  <h1><?=TOOL_NAME?>: Add Logical Switch</h1>
+            <h1>
+                <?= TOOL_NAME ?>: Add Logical Switch
+            </h1>
         </div>
-        <br/>
+        <br />
     </div>
     <div id="page">
-      <div id="itemhead">
-        <h2 class="tabeltitle">Logical Switches</h2>
-       </div>
-       <div align="center">
-<?php
-foreach ($errors as $error) {
-    ?>
-         <p class="error"><?=$error?></p>
-<?php
+        <div id="itemhead">
+            <h2 class="tabeltitle">Logical Switches</h2>
+        </div>
+        <div align="center">
+            <?php
+            foreach ($errors as $error) {
+                ?>
+                <p class="error">
+                    <?= $error ?>
+                </p>
+                <?php
 
-}
-?>
-       </div>
-       <form name="logical_switch_add_form" method="POST" action="<?=$_SERVER['PHP_SELF']?>">
-         <table class="full" summary="New Logical Switch Table">
-           <tr>
-             <th>Row No.</th>
-             <th>Hostname</th>
-             <th>Product ID</th>
-             <th>MDF</th>
-             <th>Is IDF?</th>
-             <th>IDF</th>
-             <!--<th>Ports Required</th>-->
-           </tr>
-<?php
-for ($i = 0; $i < 10; ++$i) {
-    ?>
-           <tr <?=get_row_color($i)?>>
-             <td><?=$i + 1?>.</td>
-             <td><input type="text" size="16" name="name[<?=$i?>]"></td>
-	     <td><select name="pid[<?=$i?>]">
-               <option value="__BOGUS__" selected>--Please Select--</option>
-<?php
-    foreach ($ZTP_PIDS as $p) {
-        ?>
-	       <option value="<?=$p?>"><?=$p?></option>
-<?php
+            }
+            ?>
+        </div>
+        <form name="logical_switch_add_form" method="POST" action="<?= $_SERVER['PHP_SELF'] ?>">
+            <table class="full" summary="New Logical Switch Table">
+                <tr>
+                    <th>Row No.</th>
+                    <th>Hostname</th>
+                    <th>Product ID</th>
+                    <th>MDF</th>
+                    <th>Is IDF?</th>
+                    <th>IDF</th>
+                    <!--<th>Ports Required</th>-->
+                </tr>
+                <?php
+                for ($i = 0; $i < 10; ++$i) {
+                    ?>
+                    <tr <?= get_row_color($i) ?>>
+                        <td>
+                            <?= $i + 1 ?>.
+                        </td>
+                        <td><input type="text" size="16" name="name[<?= $i ?>]"></td>
+                        <td><select name="pid[<?= $i ?>]">
+                                <option value="__BOGUS__" selected>--Please Select--</option>
+                                <?php
+                                foreach ($ZTP_PIDS as $p) {
+                                    ?>
+                                    <option value="<?= $p ?>"><?= $p ?></option>
+                                    <?php
 
-    } ?>
-             </select></td>
-	     <td><select name="mdf[<?=$i?>]" onChange='onMDFChange(this.options[this.selectedIndex].value, <?=$i?>); return true;'>
-               <option value="__BOGUS__" selected>--Please Select--</option>
-<?php
-    foreach ($MDFS as $m) {
-        ?>
-               <option value="<?=$m?>"><?=$m?></option>
-<?php
+                                } ?>
+                            </select></td>
+                        <td><select name="mdf[<?= $i ?>]"
+                                onChange='onMDFChange(this.options[this.selectedIndex].value, <?= $i ?>); return true;'>
+                                <option value="__BOGUS__" selected>--Please Select--</option>
+                                <?php
+                                foreach ($MDFS as $m) {
+                                    ?>
+                                    <option value="<?= $m ?>"><?= $m ?></option>
+                                    <?php
 
-    } ?>
-             </select></td>
-	     <td><input type="checkbox" name="is_idf[<?=$i?>]" value="1" onClick="if (this.checked == true) { this.document.getElementById('idf[<?=$i?>]').disabled = true; } else { this.document.getElementById('idf[<?=$i?>]').disabled = false; }"></td>
-             <td><select name="idf[<?=$i?>]" id="idf[<?=$i?>]">
-               <option value="__BOGUS__" selected>--Please Select--</option>
-             </select></td>
-	    <!-- <td><select name="ports[<?=$i?>]" id="ports[<?=$i?>]">
+                                } ?>
+                            </select></td>
+                        <td><input type="checkbox" name="is_idf[<?= $i ?>]" value="1"
+                                onClick="if (this.checked == true) { this.document.getElementById('idf[<?= $i ?>]').disabled = true; } else { this.document.getElementById('idf[<?= $i ?>]').disabled = false; }">
+                        </td>
+                        <td><select name="idf[<?= $i ?>]" id="idf[<?= $i ?>]">
+                                <option value="__BOGUS__" selected>--Please Select--</option>
+                            </select></td>
+                        <!-- <td><select name="ports[<?= $i ?>]" id="ports[<?= $i ?>]">
                <option value="__BOGUS__" selected>- -Please Select- -</option>
 <?php
-    /*$nports = array_values($PID_PORTS);
-    sort($nports, SORT_NUMERIC);
-    $np_seen = [];
-    foreach ($nports as $n) {
+        /*$nports = array_values($PID_PORTS);
+        sort($nports, SORT_NUMERIC);
+        $np_seen = [];
+        foreach ($nports as $n) {
         if (!isset($np_seen[$n])) {
-            $np_seen[$n] = true; ?>
-               <option value="<?=$n?>"><?=$n?></option>
-<?php
-
+        $np_seen[$n] = true; ?>
+        <option value="<?=$n?>"><?=$n?></option>
+        <?php
         }
-    }*/ ?>
+        }*/?>
   </select></td>-->
-           </tr>
-<?php
+                    </tr>
+                    <?php
+
+                }
+                ?>
+            </table>
+            <br />
+            <div align="center">
+                <input type="reset" name="reset" value="Reset">
+                <input type="submit" name="submit" value="Add">
+            </div>
+        </form>
+        <table class="noborder" summary="Return Table">
+            <tr>
+                <td class="left_act">
+                    <a href="<?= $base ?>/logicsw.php">&lt;&lt;&lt;Return to Main Page</a>
+                </td>
+            </tr>
+        </table>
+    </div>
+</body>
 
-}
-?>
-         </table>
-         <br/>
-         <div align="center">
-           <input type="reset" name="reset" value="Reset">
-           <input type="submit" name="submit" value="Add">
-         </div>
-       </form>
-       <table class="noborder" summary="Return Table">
-         <tr>
-           <td class="left_act">
-             <a href="<?=$base?>/logicsw.php">&lt;&lt;&lt;Return to Main Page</a>
-           </td>
-         </tr>
-       </table>
-     </div>
-   </body>
 </html>
 <?php
 cleanup();
-?>
+?>

+ 112 - 104
www/add_phys.php

@@ -32,20 +32,20 @@ require_once 'functions.php';
 $dsn = "$db_driver:host=$db_host;dbname=$db_name";
 
 $options = [
-    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
-    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
-    PDO::ATTR_EMULATE_PREPARES => false,
+  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
+  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
+  PDO::ATTR_EMULATE_PREPARES => false,
 ];
 
 try {
-    $dbh = new PDO($dsn, $db_user, $db_pass, $options);
+  $dbh = new PDO($dsn, $db_user, $db_pass, $options);
 } catch (PDOException $e) {
-    die($e->getMessage());
+  die($e->getMessage());
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Add Physical Switch');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Add Physical Switch');
 if ($logger === false) {
-    die("Failed to open logfile.\n");
+  die("Failed to open logfile.\n");
 }
 $mask = Log::UPTO(LOG_LEVEL);
 $logger->setMask($mask);
@@ -55,118 +55,126 @@ $errors = array();
 
 $ruser = '<AUTHENTICATION NOT ENABLED>';
 if (isset($_SERVER['REMOTE_USER'])) {
-    $ruser = $_SERVER['REMOTE_USER'];
+  $ruser = $_SERVER['REMOTE_USER'];
 }
 
 if (isset($_REQUEST['submit'])) {
-    $sn = $_REQUEST['sn'];
-    $pid = $_REQUEST['pid'];
-    $ports = [];
-    for ($i = 0; $i < count($sn); ++$i) {
-        if ($sn[$i] === null || $sn[$i] == '') {
-            continue;
-        }
-        foreach ($PID_PORTS as $pp => $np) {
-            if ($pid[$i] == $pp) {
-                $ports[$i] = $np;
-                break;
-            }
-        }
-
-        if ($pid[$i] == '__BOGUS__') {
-            array_push($errors, 'Please select a Product ID on row '.($i + 1));
-        }
+  $sn = $_REQUEST['sn'];
+  $pid = $_REQUEST['pid'];
+  $ports = [];
+  for ($i = 0; $i < count($sn); ++$i) {
+    if ($sn[$i] === null || $sn[$i] == '') {
+      continue;
+    }
+    foreach ($PID_PORTS as $pp => $np) {
+      if ($pid[$i] == $pp) {
+        $ports[$i] = $np;
+        break;
+      }
+    }
 
-        $sn[$i] = trim($sn[$i]);
+    if ($pid[$i] == '__BOGUS__') {
+      array_push($errors, 'Please select a Product ID on row ' . ($i + 1));
+    }
 
-        if (count($errors) == 0) {
-            $sql = 'REPLACE INTO DEVICE_MAP (serial_number, pid, max_ports) VALUES (?, ?, ?)';
-            try {
-                $sth = $dbh->prepare($sql);
+    $sn[$i] = trim($sn[$i]);
 
-                $sth->execute(array($sn[$i], $pid[$i], $ports[$i]));
-                $sth->closeCursor();
-                $logger->info("User {$ruser} added physical switch: serial_number={$sn[$i]} and pid={$pid[$i]}");
-            } catch (PDOException $e) {
-                array_push($errors, 'Failed to add new physical switch at row '.($i + 1).": {$e->getMessage()}");
-            }
-        }
-    }
     if (count($errors) == 0) {
-        cleanup();
-        header("Location: $base/index.php");
-        exit;
+      $sql = 'REPLACE INTO DEVICE_MAP (serial_number, pid, max_ports) VALUES (?, ?, ?)';
+      try {
+        $sth = $dbh->prepare($sql);
+
+        $sth->execute(array($sn[$i], $pid[$i], $ports[$i]));
+        $sth->closeCursor();
+        $logger->info("User {$ruser} added physical switch: serial_number={$sn[$i]} and pid={$pid[$i]}");
+      } catch (PDOException $e) {
+        array_push($errors, 'Failed to add new physical switch at row ' . ($i + 1) . ": {$e->getMessage()}");
+      }
     }
+  }
+  if (count($errors) == 0) {
+    cleanup();
+    header("Location: $base/index.php");
+    exit;
+  }
 }
 
-print_header(TOOL_NAME.': Add Physical Switch');
+print_header(TOOL_NAME . ': Add Physical Switch');
 ?>
-  <body class="flex">
-    <div id="headswreg">
-        <div id="header">
-	  <h1><?=TOOL_NAME?>: Add Physical Switch</h1>
-        </div>
-        <br/>
-    </div>
-    <div id="page">
-      <div id="itemhead">
-        <h2 class="tabeltitle">Physical Switches</h2>
-       </div>
-       <div align="center">
-<?php
-foreach ($errors as $error) {
-    ?>
-         <p class="error"><?=$error?></p>
-<?php
 
-}
-?>
-       </div>
-       <form name="phys_switch_add_form" method="POST" action="<?=$_SERVER['PHP_SELF']?>">
-         <table class="full" summary="New Physical Switch Table">
-           <tr>
-             <th>Row No.</th>
-             <th>Serial Number</th>
-             <th>Product ID</th>
-           </tr>
-<?php
-for ($i = 0; $i < 10; ++$i) {
-    ?>
-           <tr <?=get_row_color($i)?>>
-             <td><?=$i + 1?>.</td>
-             <td><input type="text" size="16" name="sn[<?=$i?>]"></td>
-             <td><select name="pid[<?=$i?>]">
-               <option value="__BOGUS__" selected>--Please Select--</option>
-<?php
-    foreach ($ZTP_PIDS as $p) {
+<body class="flex">
+  <div id="headswreg">
+    <div id="header">
+      <h1>
+        <?= TOOL_NAME ?>: Add Physical Switch
+      </h1>
+    </div>
+    <br />
+  </div>
+  <div id="page">
+    <div id="itemhead">
+      <h2 class="tabeltitle">Physical Switches</h2>
+    </div>
+    <div align="center">
+      <?php
+      foreach ($errors as $error) {
         ?>
-	       <option value="<?=$p?>"><?=$p?></option>
-<?php
+        <p class="error">
+          <?= $error ?>
+        </p>
+        <?php
 
-    } ?>
-             </select></td>
-           </tr>
-<?php
+      }
+      ?>
+    </div>
+    <form name="phys_switch_add_form" method="POST" action="<?= $_SERVER['PHP_SELF'] ?>">
+      <table class="full" summary="New Physical Switch Table">
+        <tr>
+          <th>Row No.</th>
+          <th>Serial Number</th>
+          <th>Product ID</th>
+        </tr>
+        <?php
+        for ($i = 0; $i < 10; ++$i) {
+          ?>
+          <tr <?= get_row_color($i) ?>>
+            <td>
+              <?= $i + 1 ?>.
+            </td>
+            <td><input type="text" size="16" name="sn[<?= $i ?>]"></td>
+            <td><select name="pid[<?= $i ?>]">
+                <option value="__BOGUS__" selected>--Please Select--</option>
+                <?php
+                foreach ($ZTP_PIDS as $p) {
+                  ?>
+                  <option value="<?= $p ?>"><?= $p ?></option>
+                  <?php
+
+                } ?>
+              </select></td>
+          </tr>
+          <?php
+
+        }
+        ?>
+      </table>
+      <br />
+      <div align="center">
+        <input type="reset" name="reset" value="Reset">
+        <input type="submit" name="submit" value="Add">
+      </div>
+    </form>
+    <table class="noborder" summary="Return Table">
+      <tr>
+        <td class="left_act">
+          <a href="<?= $base ?>/index.php">&lt;&lt;&lt;Return to Main Page</a>
+        </td>
+      </tr>
+    </table>
+  </div>
+</body>
 
-}
-?>
-         </table>
-         <br/>
-         <div align="center">
-           <input type="reset" name="reset" value="Reset">
-           <input type="submit" name="submit" value="Add">
-         </div>
-       </form>
-       <table class="noborder" summary="Return Table">
-         <tr>
-           <td class="left_act">
-             <a href="<?=$base?>/index.php">&lt;&lt;&lt;Return to Main Page</a>
-           </td>
-         </tr>
-       </table>
-     </div>
-   </body>
 </html>
 <?php
 cleanup();
-?>
+?>

+ 270 - 255
www/add_port_profile.php

@@ -32,20 +32,20 @@ require_once 'functions.php';
 $dsn = "$db_driver:host=$db_host;dbname=$db_name";
 
 $options = [
-    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
-    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
-    PDO::ATTR_EMULATE_PREPARES => false,
+  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
+  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
+  PDO::ATTR_EMULATE_PREPARES => false,
 ];
 
 try {
-    $dbh = new PDO($dsn, $db_user, $db_pass, $options);
+  $dbh = new PDO($dsn, $db_user, $db_pass, $options);
 } catch (PDOException $e) {
-    die($e->getMessage());
+  die($e->getMessage());
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Add Port Profile');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Add Port Profile');
 if ($logger === false) {
-    die("Failed to open logfile.\n");
+  die("Failed to open logfile.\n");
 }
 $mask = Log::UPTO(LOG_LEVEL);
 $logger->setMask($mask);
@@ -54,210 +54,213 @@ $base = get_base($_SERVER['SCRIPT_NAME']);
 $errors = array();
 
 if (isset($_REQUEST['submit'])) {
-    $pname = $_REQUEST['pname'];
-    $pid = $_REQUEST['pid'];
-    $vlans = $_REQUEST['vlan'];
-    $start_ports = $_REQUEST['start_port'];
-    $end_ports = $_REQUEST['end_port'];
-
-    if (!isset($pname) || !isset($pid) || $pname == '') {
-        array_push($errors, 'You must specify a profile name and PID');
-    } else {
-        $profile = '';
-        $seen_sports = array();
-        $seen_eports = array();
-        $max_port = 0;
-
-        for ($i = 0; $i < count($start_ports); ++$i) {
-            $vlan = $vlans[$i];
-            $start_port = $start_ports[$i];
-            $end_port = $end_ports[$i];
-            $row = $i + 1;
-
-            if ($vlan == '__BOGUS__') {
-                continue;
-            }
-
-            if ($start_port == '__BOGUS__' || $end_port == '__BOGUS__') {
-                array_push($errors, "You must select a starting and ending port at row $row");
-                continue;
-            }
-
-            if ($pid != '__ANY__') {
-                preg_match("/\/(\d+)$/", $start_port, $sm);
-
-                if ($sm[1] > $end_port) {
-                    array_push($errors, "Starting port must be less than equal to the ending port at row $row");
-                    continue;
-                }
-            } elseif ($vlan == 'DYNAMIC') {
-                array_push($errors, "In order to make ports dynamic, you must choose an explicit PID at row $row");
-                continue;
-            }
-
-            if (isset($seen_sports[$start_port])) {
-                array_push($errors, "Starting port $start_port was already used at row {$seen_sports[$start_port]}");
-                continue;
-            }
-
-            $seen_sports[$start_port] = $row;
-
-            if (isset($seen_eports[$end_port])) {
-                array_push($errors, "Ending port $end_port was already used at row {$seen_eports[$end_port]}");
-                continue;
-            }
-
-            $seen_eports[$end_port] = $row;
-
-            $profile .= generate_port_profile($start_port, $end_port, $vlan, $pid);
-            $profile .= "!\n";
-            if ($pid != '__ANY__' && $end_port > $max_port) {
-                $max_port = $end_port;
-            }
-        }
+  $pname = $_REQUEST['pname'];
+  $pid = $_REQUEST['pid'];
+  $vlans = $_REQUEST['vlan'];
+  $start_ports = $_REQUEST['start_port'];
+  $end_ports = $_REQUEST['end_port'];
+
+  if (!isset($pname) || !isset($pid) || $pname == '') {
+    array_push($errors, 'You must specify a profile name and PID');
+  } else {
+    $profile = '';
+    $seen_sports = array();
+    $seen_eports = array();
+    $max_port = 0;
+
+    for ($i = 0; $i < count($start_ports); ++$i) {
+      $vlan = $vlans[$i];
+      $start_port = $start_ports[$i];
+      $end_port = $end_ports[$i];
+      $row = $i + 1;
+
+      if ($vlan == '__BOGUS__') {
+        continue;
+      }
 
-        if ($profile == '') {
-            array_push($errors, 'No profile ranges specified');
-        }
+      if ($start_port == '__BOGUS__' || $end_port == '__BOGUS__') {
+        array_push($errors, "You must select a starting and ending port at row $row");
+        continue;
+      }
 
-        if (!preg_match("/^[\w\d\-_]+$/", $pname)) {
-            array_push($errors, 'Profile name can only contain letters, numbers, hyphens, and underscores');
-        }
+      if ($pid != '__ANY__') {
+        preg_match("/\/(\d+)$/", $start_port, $sm);
 
-        if ($pid != '__ANY__') {
-            $ports = 8;
-            foreach ($PID_PORTS as $pp => $np) {
-                if ($pid == $pp) {
-                    $ports = $np;
-                    break;
-                }
-            }
-
-            if ($max_port != $ports) {
-                array_push($errors, 'All ports must be specified for a port profile');
-            }
+        if ($sm[1] > $end_port) {
+          array_push($errors, "Starting port must be less than equal to the ending port at row $row");
+          continue;
         }
+      } elseif ($vlan == 'DYNAMIC') {
+        array_push($errors, "In order to make ports dynamic, you must choose an explicit PID at row $row");
+        continue;
+      }
+
+      if (isset($seen_sports[$start_port])) {
+        array_push($errors, "Starting port $start_port was already used at row {$seen_sports[$start_port]}");
+        continue;
+      }
+
+      $seen_sports[$start_port] = $row;
+
+      if (isset($seen_eports[$end_port])) {
+        array_push($errors, "Ending port $end_port was already used at row {$seen_eports[$end_port]}");
+        continue;
+      }
+
+      $seen_eports[$end_port] = $row;
+
+      $profile .= generate_port_profile($start_port, $end_port, $vlan, $pid);
+      $profile .= "!\n";
+      if ($pid != '__ANY__' && $end_port > $max_port) {
+        $max_port = $end_port;
+      }
     }
 
-    if (count($errors) == 0) {
-        $fd = fopen(PORT_PROFILE_DIR."/{$pname}.tmpl", 'w');
-        fwrite($fd, $profile);
-        fclose($fd);
-
-        $sql = 'INSERT INTO EXCEPTIONS VALUES (?, ?, ?)';
-        try {
-            $sth = $dbh->prepare($sql);
-            /*if (isset($PID_MAP[$pid])) {
-                $pid = $PID_MAP[$pid];
-            }*/
-            $sth->execute(array($pname, $pid, "{$pname}.tmpl"));
-            $sth->closeCursor();
-            $logger->info("User {$_SERVER['REMOTE_USER']} add port profile: name={$pname}, pid={$pid}, path={$pname}.tmpl");
-        } catch (PDOException $e) {
-            array_push($errors, "Failed to add new exception: {$e->getMessage()}");
-        }
+    if ($profile == '') {
+      array_push($errors, 'No profile ranges specified');
+    }
+
+    if (!preg_match("/^[\w\d\-_]+$/", $pname)) {
+      array_push($errors, 'Profile name can only contain letters, numbers, hyphens, and underscores');
+    }
 
-        cleanup();
-        if (count($errors) == 0) {
-            header("Location: $base/port_profiles.php");
-            exit;
+    if ($pid != '__ANY__') {
+      $ports = 8;
+      foreach ($PID_PORTS as $pp => $np) {
+        if ($pid == $pp) {
+          $ports = $np;
+          break;
         }
+      }
+
+      if ($max_port != $ports) {
+        array_push($errors, 'All ports must be specified for a port profile');
+      }
+    }
+  }
+
+  if (count($errors) == 0) {
+    $fd = fopen(PORT_PROFILE_DIR . "/{$pname}.tmpl", 'w');
+    fwrite($fd, $profile);
+    fclose($fd);
+
+    $sql = 'INSERT INTO EXCEPTIONS VALUES (?, ?, ?)';
+    try {
+      $sth = $dbh->prepare($sql);
+      /*if (isset($PID_MAP[$pid])) {
+      $pid = $PID_MAP[$pid];
+      }*/
+      $sth->execute(array($pname, $pid, "{$pname}.tmpl"));
+      $sth->closeCursor();
+      $logger->info("User {$_SERVER['REMOTE_USER']} add port profile: name={$pname}, pid={$pid}, path={$pname}.tmpl");
+    } catch (PDOException $e) {
+      array_push($errors, "Failed to add new exception: {$e->getMessage()}");
     }
+
+    cleanup();
+    if (count($errors) == 0) {
+      header("Location: $base/port_profiles.php");
+      exit;
+    }
+  }
 }
 
 $nports = array_values($PID_PORTS);
 rsort($nports, SORT_NUMERIC);
 $mport = $nports[0];
 
-print_header(TOOL_NAME.': Add Port Profile');
+print_header(TOOL_NAME . ': Add Port Profile');
 ?>
-  <body class="flex" onLoad='purgePorts(); updatePorts("__ANY__", 0, 0, 1, 0); return true;'>
-<script>
-var lastStart = 1;
 
-var PID_PORTS = [];
-var PORT_PATTERNS = [];
-<?php
-foreach ($PID_PORTS as $pp => $np) {
-    ?>
-PID_PORTS["<?=$pp?>"] = <?=$np?>;
-<?php
+<body class="flex" onLoad='purgePorts(); updatePorts("__ANY__", 0, 0, 1, 0); return true;'>
+  <script>
+    var lastStart = 1;
 
-}
+    var PID_PORTS = [];
+    var PORT_PATTERNS = [];
+    <?php
+    foreach ($PID_PORTS as $pp => $np) {
+      ?>
+      PID_PORTS["<?= $pp ?>"] = <?= $np ?>;
+      <?php
 
-foreach ($PORT_PATTERNS as $p => $pa) {
-    ?>
-PORT_PATTERNS["<?=$p?>"] = "<?=$pa?>";
-<?php
+    }
 
-}
-?>
+    foreach ($PORT_PATTERNS as $p => $pa) {
+      ?>
+      PORT_PATTERNS["<?= $p ?>"] = "<?= $pa ?>";
+      <?php
 
-function setLastStart(port, increment) {
-	var regex = /([0-9]+)$/;
-	try {
-		var matches = regex.exec(port);
-		lastStart = matches[1];
-		if (increment) {
-			lastStart++;
-		}
-	} catch (err) { }
-}
+    }
+    ?>
 
-function purgePorts() {
-	for (var i = 0; i < <?=$mport?>; i++) {
-		var sSelect = document.getElementById("start_port[" + i + "]");
-		var eSelect = document.getElementById("end_port[" + i + "]");
-		deleteOptions(sSelect);
-		deleteOptions(eSelect);
+    function setLastStart(port, increment) {
+      var regex = /([0-9]+)$/;
+      try {
+        var matches = regex.exec(port);
+        lastStart = matches[1];
+        if (increment) {
+          lastStart++;
+        }
+      } catch (err) { }
+    }
 
-		createOption(sSelect, '--Please Select--', '__BOGUS__');
-		createOption(eSelect, '--Please Select--', '__BOGUS__');
-	}
-}
+    function purgePorts() {
+      for (var i = 0; i < <?= $mport ?>; i++) {
+        var sSelect = document.getElementById("start_port[" + i + "]");
+        var eSelect = document.getElementById("end_port[" + i + "]");
+        deleteOptions(sSelect);
+        deleteOptions(eSelect);
 
-function updatePorts(pid, sidx, eidx, send, eend) {
-  if (typeof send === undefined) {
-    send = <?=$mport?>;
-  }
-  if (typeof eend === undefined) {
-    eend = <?=$mport?>;
-  }
-  for (var i = sidx; i < send; i++) {
-    var sSelect = document.getElementById("start_port[" + i + "]");
-    if (pid == "__ANY__") {
-      createOption(sSelect, 'First Switch Port', '%%START_PORT%%');
-    } else {
-      endp = PID_PORTS[pid] + 1;
-      ppat = PORT_PATTERNS[pid];
-      for (var j = lastStart; j < endp; j++) {
-        createOption(sSelect, ppat + j, ppat + j);
+        createOption(sSelect, '--Please Select--', '__BOGUS__');
+        createOption(eSelect, '--Please Select--', '__BOGUS__');
       }
     }
 
-  }
+    function updatePorts(pid, sidx, eidx, send, eend) {
+      if (typeof send === undefined) {
+        send = <?= $mport ?>;
+      }
+      if (typeof eend === undefined) {
+        eend = <?= $mport ?>;
+      }
+      for (var i = sidx; i < send; i++) {
+        var sSelect = document.getElementById("start_port[" + i + "]");
+        if (pid == "__ANY__") {
+          createOption(sSelect, 'First Switch Port', '%%START_PORT%%');
+        } else {
+          endp = PID_PORTS[pid] + 1;
+          ppat = PORT_PATTERNS[pid];
+          for (var j = lastStart; j < endp; j++) {
+            createOption(sSelect, ppat + j, ppat + j);
+          }
+        }
 
-  for (var i = eidx; i < eend; i++) {
-    var eSelect = document.getElementById("end_port[" + i + "]");
-    if (pid == "__ANY__") {
-      createOption(eSelect, 'Last Switch Port', '%%MAX_PORT%%');
-    } else {
-      endp = PID_PORTS[pid] + 1;
-      for (var j = lastStart; j < endp; j++) {
-        createOption(eSelect, j, j);
+      }
+
+      for (var i = eidx; i < eend; i++) {
+        var eSelect = document.getElementById("end_port[" + i + "]");
+        if (pid == "__ANY__") {
+          createOption(eSelect, 'Last Switch Port', '%%MAX_PORT%%');
+        } else {
+          endp = PID_PORTS[pid] + 1;
+          for (var j = lastStart; j < endp; j++) {
+            createOption(eSelect, j, j);
+          }
+        }
       }
     }
-  }
-}
 
-</script>
-    <div id="headswreg">
-        <div id="header">
-	  <h1><?=TOOL_NAME?>: Add Port Profile</h1>
-        </div>
-        <br/>
+  </script>
+  <div id="headswreg">
+    <div id="header">
+      <h1>
+        <?= TOOL_NAME ?>: Add Port Profile
+      </h1>
     </div>
-    <form name="port_profile_add_form" method="POST" action="<?=$_SERVER['PHP_SELF']?>">
+    <br />
+  </div>
+  <form name="port_profile_add_form" method="POST" action="<?= $_SERVER['PHP_SELF'] ?>">
     <div class="apage">
       <table class="noborder" summary="Profile Options">
         <tr>
@@ -265,92 +268,104 @@ function updatePorts(pid, sidx, eidx, send, eend) {
             <input type="text" name="pname" size="16">
           </td>
           <td>Select PID:
-            <select name="pid" id="pid" onChange='purgePorts(); updatePorts(this.options[this.selectedIndex].value, 0, 0, 1, 0); return true;'>
+            <select name="pid" id="pid"
+              onChange='purgePorts(); updatePorts(this.options[this.selectedIndex].value, 0, 0, 1, 0); return true;'>
               <option value="__ANY__" selected>Any</option>
-<?php
-foreach ($PID_PORTS as $p => $n) {
-    ?>
-              <option value="<?=$p?>"><?=$p?></option>
-<?php
-
-}
-?>
-            </select></td>
+              <?php
+              foreach ($PID_PORTS as $p => $n) {
+                ?>
+                <option value="<?= $p ?>"><?= $p ?></option>
+                <?php
+
+              }
+              ?>
+            </select>
+          </td>
         </tr>
       </table>
     </div>
     <div id="page">
       <div id="itemhead">
         <h2 class="tabletitle">Port Profile</h2>
-       </div>
-       <div align="center">
-<?php
-foreach ($errors as $error) {
-    ?>
-         <p class="error"><?=$error?></p>
-<?php
+      </div>
+      <div align="center">
+        <?php
+        foreach ($errors as $error) {
+          ?>
+          <p class="error">
+            <?= $error ?>
+          </p>
+          <?php
 
-}
-?>
-       </div>
-         <table class="full" summary="New Port Profile Table">
-           <thead>
-             <tr>
-               <th>Row No.</th>
-               <th>Starting Port</th>
-               <th>Ending Port</th>
-               <th>VLAN</th>
-             </tr>
-           </thead>
-           <tbody>
-<?php
-for ($i = 0; $i < $mport; ++$i) {
-    ?>
-           <tr <?=get_row_color($i)?>>
-             <td><?=$i + 1?>.</td>
-	     <td><select name="start_port[<?=$i?>]" id="start_port[<?=$i?>]" onChange='setLastStart(this.options[this.selectedIndex].value, false); pSelect = document.getElementById("pid"); updatePorts(pSelect.options[pSelect.selectedIndex].value, <?=$i + 1?>, <?=$i?>, <?=$i + 1?>, <?=$i + 1?>); return true;'>
-             </select></td>
-	     <td><select name="end_port[<?=$i?>]" id="end_port[<?=$i?>]" onChange='setLastStart(this.options[this.selectedIndex].value, true); pSelect = document.getElementById("pid"); updatePorts(pSelect.options[pSelect.selectedIndex].value, <?=$i + 1?>, <?=$i + 1?>, <?=$i + 2?>, <?=$i + 1?>); return true;'>
-             </select></td>
-	     <td><select name="vlan[<?=$i?>]">
-               <option value="__BOGUS__" selected>--Please Select--</option>
-               <option value="DYNAMIC">DYNAMIC</option>
-               <option value="TRUNK">TRUNK</option>
-               <option value="UPLINK TRUNK">UPLINK TRUNK</option>
-               <option disabled>&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;</option>
-<?php
-    ksort($VLANS);
-    foreach ($VLANS as $vn => $vi) {
+        }
         ?>
-	       <option value="<?=$vn?>"><?=$vn?></option>
-<?php
-
-    } ?>
-             </select></td>
-           </tr>
-<?php
+      </div>
+      <table class="full" summary="New Port Profile Table">
+        <thead>
+          <tr>
+            <th>Row No.</th>
+            <th>Starting Port</th>
+            <th>Ending Port</th>
+            <th>VLAN</th>
+          </tr>
+        </thead>
+        <tbody>
+          <?php
+          for ($i = 0; $i < $mport; ++$i) {
+            ?>
+            <tr <?= get_row_color($i) ?>>
+              <td>
+                <?= $i + 1 ?>.
+              </td>
+              <td><select name="start_port[<?= $i ?>]" id="start_port[<?= $i ?>]"
+                  onChange='setLastStart(this.options[this.selectedIndex].value, false); pSelect = document.getElementById("pid"); updatePorts(pSelect.options[pSelect.selectedIndex].value, <?= $i + 1 ?>, <?= $i ?>, <?= $i + 1 ?>, <?= $i + 1 ?>); return true;'>
+                </select></td>
+              <td><select name="end_port[<?= $i ?>]" id="end_port[<?= $i ?>]"
+                  onChange='setLastStart(this.options[this.selectedIndex].value, true); pSelect = document.getElementById("pid"); updatePorts(pSelect.options[pSelect.selectedIndex].value, <?= $i + 1 ?>, <?= $i + 1 ?>, <?= $i + 2 ?>, <?= $i + 1 ?>); return true;'>
+                </select></td>
+              <td><select name="vlan[<?= $i ?>]">
+                  <option value="__BOGUS__" selected>--Please Select--</option>
+                  <option value="DYNAMIC">DYNAMIC</option>
+                  <option value="TRUNK">TRUNK</option>
+                  <option value="UPLINK TRUNK">UPLINK TRUNK</option>
+                  <option disabled>
+                    &#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;</option>
+                  <?php
+                  ksort($VLANS);
+                  foreach ($VLANS as $vn => $vi) {
+                    ?>
+                    <option value="<?= $vn ?>"><?= $vn ?></option>
+                    <?php
+
+                  } ?>
+                </select></td>
+            </tr>
+            <?php
+
+          }
+          ?>
+        </tbody>
+      </table>
+      <br />
+      <div align="center">
+        <input type="reset" name="reset" value="Reset">
+        <input type="submit" name="preview" value="Preview"
+          onClick='this.form.action="<?= $base ?>/profile_preview.php"; this.form.target="_blank";'>
+        <input type="submit" name="submit" value="Add"
+          onClick='this.form.action="<?= $_SERVER['PHP_SELF'] ?>"; this.form.target="_self";'>
+      </div>
+      <table class="noborder" summary="Return Table">
+        <tr>
+          <td class="left_act">
+            <a href="<?= $base ?>/port_profiles.php">&lt;&lt;&lt;Return to Main Page</a>
+          </td>
+        </tr>
+      </table>
+    </div>
+  </form>
+</body>
 
-}
-?>
-           </tbody>
-         </table>
-         <br/>
-         <div align="center">
-           <input type="reset" name="reset" value="Reset">
-	   <input type="submit" name="preview" value="Preview" onClick='this.form.action="<?=$base?>/profile_preview.php"; this.form.target="_blank";'>
-	   <input type="submit" name="submit" value="Add" onClick='this.form.action="<?=$_SERVER['PHP_SELF']?>"; this.form.target="_self";'>
-         </div>
-       <table class="noborder" summary="Return Table">
-         <tr>
-           <td class="left_act">
-             <a href="<?=$base?>/port_profiles.php">&lt;&lt;&lt;Return to Main Page</a>
-           </td>
-         </tr>
-       </table>
-     </div>
-       </form>
-   </body>
 </html>
 <?php
 cleanup();
-?>
+?>

+ 1 - 1
www/db.inc.php

@@ -4,4 +4,4 @@ $db_driver = 'mysql';
 $db_user = 'noc';
 $db_pass = '';
 $db_host = 'localhost';
-$db_name = 'noc';
+$db_name = 'noc';

+ 7 - 7
www/export.php

@@ -48,7 +48,7 @@ try {
     die($e->getMessage());
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Exporter');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Exporter');
 if ($logger === false) {
     die("Failed to open logfile.\n");
 }
@@ -69,7 +69,7 @@ try {
 $p['authentication']['user'] = PRIME_API_USER;
 $p['authentication']['password'] = PRIME_API_PASS;
 
-$url = PRIME_URL.'/webacs/api/v1/op/devices/bulkImport.json';
+$url = PRIME_URL . '/webacs/api/v1/op/devices/bulkImport.json';
 $d['devicesImport']['devices']['device'] = array();
 $dns_devices = array();
 
@@ -142,12 +142,12 @@ if (!$res) {
         echo implode('<br/>', $errors);
     } else {
         ?>
-	<script language="Javascript">
-	window.close();
-	</script>
-<?php
+        <script language="Javascript">
+            window.close();
+        </script>
+        <?php
 
     }
 }
 
-?>
+?>

+ 9 - 9
www/export_deadman.php

@@ -59,7 +59,7 @@ try {
     die($e->getMessage() . "\n");
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Exporter');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Exporter');
 if ($logger === false) {
     die("Failed to open logfile.\n");
 }
@@ -103,7 +103,7 @@ try {
 } catch (PDOException $e) {
     $msg = "Error querying for physical switches: {$e->getMessage()}";
     if ($is_script) {
-        echo $msg."\n";
+        echo $msg . "\n";
     } else {
         echo "<p><font color=\"red\">{$msg}</font></p>\r\n";
     }
@@ -141,7 +141,7 @@ try {
 } catch (Exception $e) {
     $msg = "Error parsing YAML file: '{$e->getMessage()}'";
     if ($is_script) {
-        echo $msg."\n";
+        echo $msg . "\n";
     } else {
         echo "<p><font color=\"red\">{$msg}</font></p>\r\n";
     }
@@ -168,7 +168,7 @@ while ($row = $res->fetch()) {
     } catch (PDOException $e) {
         $msg = "Error querying for IP address for {$row['assigned_switch']}: {$e->getMessage()}";
         if ($is_script) {
-            echo $msg."\n";
+            echo $msg . "\n";
         } else {
             echo "<p><font color=\"red\">{$msg}</font></p>\r\n";
         }
@@ -194,7 +194,7 @@ try {
 } catch (Exception $e) {
     $msg = "Failed to generate YAML: '{$e->getMessage()}'";
     if ($is_script) {
-        echo $msg."\n";
+        echo $msg . "\n";
     } else {
         echo "<p><font color=\"red\">{$msg}</font></p>";
     }
@@ -228,7 +228,7 @@ HEADER;
 } catch (Exception $e) {
     $msg = "Failed to write data to file: '{$e->getMessage()}";
     if ($is_script) {
-        echo $msg."\n";
+        echo $msg . "\n";
     } else {
         echo "<p><font color=\"red\">{$msg}</font></p>";
     }
@@ -289,10 +289,10 @@ if ($result != 0) {
 
 touch('/tmp/deadman_change.dat');
 if ($is_script) {
-	exit(0);
+    exit(0);
 }
 ?>
 
 <script>
-window.close();
-</script>
+    window.close();
+</script>

+ 391 - 386
www/functions.php

@@ -24,233 +24,270 @@
 // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 // SUCH DAMAGE.
 
-    require_once 'Log.php';
-
-    function cleanup()
-    {
-        global $logger;
-
-        $logger->close();
-    }
-
-    function print_header($title)
-    {
-        ?>
-<!DOCTYPE html>
-<html>
-  <head>
-    <title><?=$title?></title>
-    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
-    <link rel="stylesheet" href="<?=get_base($_SERVER['SCRIPT_NAME'])?>/mini.css" type="text/css">
-    <link rel="stylesheet" type="text/css" href="<?=get_base($_SERVER['SCRIPT_NAME'])?>/jquery.dataTables.min.css">
-    <script language="javascript" src="<?=get_base($_SERVER['SCRIPT_NAME'])?>/jquery-1.12.3.js"></script>
-    <script language="javascript" src="<?=get_base($_SERVER['SCRIPT_NAME'])?>/jquery.dataTables.min.js"></script>
-    <script language="javascript" src="<?=get_base($_SERVER['SCRIPT_NAME'])?>/jquery.color-animation.js"></script>
-    <script language="JavaScript" src="<?=get_base($_SERVER['SCRIPT_NAME'])?>/functions.js"></script>
-    <style type="text/css">
-.style1 { font-family: "Trebuchet MS" }
-    </style>
-    <script language="javascript">
-<!--
-	function MM_reloadPage(init) {
-		if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
-			document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
-		else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
-	}
-MM_reloadPage(true);
-//-->
-    </script>
-  </head>
-<?php
-
+require_once 'Log.php';
+
+function cleanup()
+{
+    global $logger;
+
+    $logger->close();
+}
+
+function print_header($title)
+{
+    ?>
+    <!DOCTYPE html>
+    <html>
+
+    <head>
+        <title>
+            <?= $title ?>
+        </title>
+        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
+        <link rel="stylesheet" href="<?= get_base($_SERVER['SCRIPT_NAME']) ?>/mini.css" type="text/css">
+        <link rel="stylesheet" type="text/css" href="<?= get_base($_SERVER['SCRIPT_NAME']) ?>/jquery.dataTables.min.css">
+        <script language="javascript" src="<?= get_base($_SERVER['SCRIPT_NAME']) ?>/jquery-1.12.3.js"></script>
+        <script language="javascript" src="<?= get_base($_SERVER['SCRIPT_NAME']) ?>/jquery.dataTables.min.js"></script>
+        <script language="javascript" src="<?= get_base($_SERVER['SCRIPT_NAME']) ?>/jquery.color-animation.js"></script>
+        <script language="JavaScript" src="<?= get_base($_SERVER['SCRIPT_NAME']) ?>/functions.js"></script>
+        <style type="text/css">
+            .style1 {
+                font-family: "Trebuchet MS"
+            }
+        </style>
+        <script language="javascript">
+            <!--
+                function MM_reloadPage(init) {
+                    if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
+                        document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
+                    else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
+                }
+            MM_reloadPage(true);
+            //-->
+        </script>
+    </head>
+    <?php
+
+}
+
+function get_row_color($row)
+{
+    return ($row % 2 != 0) ? 'bgcolor="#f0f0f0"' : '';
+}
+
+function get_base($script)
+{
+    $base = dirname($script);
+    if ($base == '/') {
+        $base = '';
     }
 
-    function get_row_color($row)
-    {
-        return ($row % 2 != 0) ? 'bgcolor="#f0f0f0"' : '';
-    }
+    return $base;
+}
 
-    function get_base($script)
-    {
-        $base = dirname($script);
-        if ($base == '/') {
-            $base = '';
-        }
+function generate_port_profile($start_port, $end_port, $vlan, $pid)
+{
+    global $VLANS, $PORT_TYPES;
 
-        return $base;
+    $zpid = $pid;
+    /*if (isset($PID_MAP[$pid])) {
+    $zpid = $PID_MAP[$pid];
+    }*/
+    $pprefix = '';
+    if (isset($PORT_TYPES[$zpid])) {
+        $pprefix = $PORT_TYPES[$zpid];
     }
-
-    function generate_port_profile($start_port, $end_port, $vlan, $pid)
-    {
-        global $VLANS, $PORT_TYPES;
-
-        $zpid = $pid;
-        /*if (isset($PID_MAP[$pid])) {
-            $zpid = $PID_MAP[$pid];
-        }*/
-        $pprefix = '';
-        if (isset($PORT_TYPES[$zpid])) {
-            $pprefix = $PORT_TYPES[$zpid];
-        }
-        $profile = "interface range {$pprefix}$start_port - $end_port\n";
-        if (file_exists(PORT_TMPL_DIR.'/ports.tmpl')) {
-            $profile .= file_get_contents(PORT_TMPL_DIR.'/ports.tmpl');
+    $profile = "interface range {$pprefix}$start_port - $end_port\n";
+    if (file_exists(PORT_TMPL_DIR . '/ports.tmpl')) {
+        $profile .= file_get_contents(PORT_TMPL_DIR . '/ports.tmpl');
+    }
+    if (file_exists(PORT_TMPL_DIR . '/' . $zpid . '/ports.tmpl')) {
+        $profile .= file_get_contents(PORT_TMPL_DIR . '/' . $zpid . '/ports.tmpl');
+    }
+    if ($vlan == 'DYNAMIC') {
+        if (file_exists(PORT_TMPL_DIR . '/DYNAMIC/ports.tmpl')) {
+            $profile .= file_get_contents(PORT_TMPL_DIR . '/DYNAMIC/ports.tmpl');
         }
-        if (file_exists(PORT_TMPL_DIR.'/'.$zpid.'/ports.tmpl')) {
-            $profile .= file_get_contents(PORT_TMPL_DIR.'/'.$zpid.'/ports.tmpl');
+        if (file_exists(PORT_TMPL_DIR . '/DYNAMIC/' . $zpid . '/ports.tmpl')) {
+            $profile .= file_get_contents(PORT_TMPL_DIR . '/DYNAMIC/' . $zpid . '/ports.tmpl');
         }
-        if ($vlan == 'DYNAMIC') {
-            if (file_exists(PORT_TMPL_DIR.'/DYNAMIC/ports.tmpl')) {
-                $profile .= file_get_contents(PORT_TMPL_DIR.'/DYNAMIC/ports.tmpl');
-            }
-            if (file_exists(PORT_TMPL_DIR.'/DYNAMIC/'.$zpid.'/ports.tmpl')) {
-                $profile .= file_get_contents(PORT_TMPL_DIR.'/DYNAMIC/'.$zpid.'/ports.tmpl');
-            }
-        } elseif ($vlan == 'TRUNK' || $vlan == 'UPLINK TRUNK') {
-            if ($vlan == 'UPLINK TRUNK') {
-                $profile .= " description STATIC: Uplink Trunk Port\n";
-            } else {
-                $profile .= " description STATIC: Trunk Port\n";
-            }
-            if (file_exists(PORT_TMPL_DIR.'/TRUNK/ports.tmpl')) {
-                $profile .= file_get_contents(PORT_TMPL_DIR.'/TRUNK/ports.tmpl');
-            }
-            if (file_exists(PORT_TMPL_DIR.'/TRUNK/'.$zpid.'/ports.tmpl')) {
-                $profile .= file_get_contents(PORT_TMPL_DIR.'/TRUNK/'.$zpid.'/ports.tmpl');
-            }
-            if ($vlan == 'UPLINK TRUNK') {
-                if (file_exists(PORT_TMPL_DIR.'/TRUNK/uplink/ports.tmpl')) {
-                    $profile .= file_get_contents(PORT_TMPL_DIR.'/TRUNK/uplink/ports.tmpl');
-                }
-                if (file_exists(PORT_TMPL_DIR.'/TRUNK/uplink/'.$zpid.'/ports.tmpl')) {
-                    $profile .= file_get_contents(PORT_TMPL_DIR.'/TRUNK/uplink/'.$zpid.'/ports.tmpl');
-                }
-            }
+    } elseif ($vlan == 'TRUNK' || $vlan == 'UPLINK TRUNK') {
+        if ($vlan == 'UPLINK TRUNK') {
+            $profile .= " description STATIC: Uplink Trunk Port\n";
         } else {
-            $vi = $VLANS[$vlan];
-            $profile .= " description STATIC: $vlan Access Port\n";
-            $profile .= " switchport access vlan $vi\n";
-            if (file_exists(PORT_TMPL_DIR.'/ACCESS/ports.tmpl')) {
-                $profile .= file_get_contents(PORT_TMPL_DIR.'/ACCESS/ports.tmpl');
-            }
-            if (file_exists(PORT_TMPL_DIR.'/ACCESS/'.$zpid.'/ports.tmpl')) {
-                $profile .= file_get_contents(PORT_TMPL_DIR.'/ACCESS/'.$zpid.'/ports.tmpl');
-            }
-            if (file_exists(PORT_TMPL_DIR.'/ACCESS/'.$vi.'/ports.tmpl')) {
-                $profile .= file_get_contents(PORT_TMPL_DIR.'/ACCESS/'.$vi.'/ports.tmpl');
+            $profile .= " description STATIC: Trunk Port\n";
+        }
+        if (file_exists(PORT_TMPL_DIR . '/TRUNK/ports.tmpl')) {
+            $profile .= file_get_contents(PORT_TMPL_DIR . '/TRUNK/ports.tmpl');
+        }
+        if (file_exists(PORT_TMPL_DIR . '/TRUNK/' . $zpid . '/ports.tmpl')) {
+            $profile .= file_get_contents(PORT_TMPL_DIR . '/TRUNK/' . $zpid . '/ports.tmpl');
+        }
+        if ($vlan == 'UPLINK TRUNK') {
+            if (file_exists(PORT_TMPL_DIR . '/TRUNK/uplink/ports.tmpl')) {
+                $profile .= file_get_contents(PORT_TMPL_DIR . '/TRUNK/uplink/ports.tmpl');
             }
-            if (file_exists(PORT_TMPL_DIR.'/ACCESS/'.$vi.'/'.$zpid.'/ports.tmpl')) {
-                $profile .= file_get_contents(PORT_TMPL_DIR.'/ACCESS/'.$vi.'/'.$zpid.'/ports.tmpl');
+            if (file_exists(PORT_TMPL_DIR . '/TRUNK/uplink/' . $zpid . '/ports.tmpl')) {
+                $profile .= file_get_contents(PORT_TMPL_DIR . '/TRUNK/uplink/' . $zpid . '/ports.tmpl');
             }
         }
-
-        return $profile;
+    } else {
+        $vi = $VLANS[$vlan];
+        $profile .= " description STATIC: $vlan Access Port\n";
+        $profile .= " switchport access vlan $vi\n";
+        if (file_exists(PORT_TMPL_DIR . '/ACCESS/ports.tmpl')) {
+            $profile .= file_get_contents(PORT_TMPL_DIR . '/ACCESS/ports.tmpl');
+        }
+        if (file_exists(PORT_TMPL_DIR . '/ACCESS/' . $zpid . '/ports.tmpl')) {
+            $profile .= file_get_contents(PORT_TMPL_DIR . '/ACCESS/' . $zpid . '/ports.tmpl');
+        }
+        if (file_exists(PORT_TMPL_DIR . '/ACCESS/' . $vi . '/ports.tmpl')) {
+            $profile .= file_get_contents(PORT_TMPL_DIR . '/ACCESS/' . $vi . '/ports.tmpl');
+        }
+        if (file_exists(PORT_TMPL_DIR . '/ACCESS/' . $vi . '/' . $zpid . '/ports.tmpl')) {
+            $profile .= file_get_contents(PORT_TMPL_DIR . '/ACCESS/' . $vi . '/' . $zpid . '/ports.tmpl');
+        }
     }
 
-    function call_hook($hook, $args)
-    {
-        global $HOOKS;
+    return $profile;
+}
 
-        $hook_parts = explode(':', $hook);
-        $hook_name = '$HOOKS';
-        foreach ($hook_parts as $hp) {
-            $hook_name .= "['$hp']";
-        }
+function call_hook($hook, $args)
+{
+    global $HOOKS;
 
-        @eval('$hook_val = '.$hook_name.';');
-        if (!isset($hook_val) || $hook_val == '') {
-            return;
-        }
+    $hook_parts = explode(':', $hook);
+    $hook_name = '$HOOKS';
+    foreach ($hook_parts as $hp) {
+        $hook_name .= "['$hp']";
+    }
 
-        $argstr = $hook.' ';
-        foreach ($args as $arg) {
-            $argstr .= escapeshellarg($arg).' ';
-        }
+    @eval('$hook_val = ' . $hook_name . ';');
+    if (!isset($hook_val) || $hook_val == '') {
+        return;
+    }
 
-        $argstr = trim($argstr);
-        @exec("$hook_val $argstr > /dev/null 2>&1 &");
+    $argstr = $hook . ' ';
+    foreach ($args as $arg) {
+        $argstr .= escapeshellarg($arg) . ' ';
     }
 
-    function get_PI_REST($url, $p = false, $decode = true, $timeout = 300)
-    {
-        $cookie = false;
-        $error = '';
+    $argstr = trim($argstr);
+    @exec("$hook_val $argstr > /dev/null 2>&1 &");
+}
 
-        if (DEBUG >= 5) {
-            echo "<h3>calling $url with params:</h3>";
-            var_dump($p);
-        }
+function get_PI_REST($url, $p = false, $decode = true, $timeout = 300)
+{
+    $cookie = false;
+    $error = '';
 
-        $i = 0;
-        $res = false;
-        while ($i < REST_RETRIES) {
-            $res = fetch_url($url, $cookie, $error, $p, $timeout);
-            if ($res) {
-                break;
-            }
-            sleep(3);
-            ++$i;
-        }
+    if (DEBUG >= 5) {
+        echo "<h3>calling $url with params:</h3>";
+        var_dump($p);
+    }
+
+    $i = 0;
+    $res = false;
+    while ($i < REST_RETRIES) {
+        $res = fetch_url($url, $cookie, $error, $p, $timeout);
         if ($res) {
-            if ($decode) {
-                $json = json_decode($res, true);
+            break;
+        }
+        sleep(3);
+        ++$i;
+    }
+    if ($res) {
+        if ($decode) {
+            $json = json_decode($res, true);
 
-                return $json;
-            } else {
-                return $res;
-            }
+            return $json;
+        } else {
+            return $res;
         }
+    }
 
-        return false;
+    return false;
+}
+
+function apicGetTicket($host, $user, $pass, &$error)
+{
+    $cookie = false;
+    $url = 'https://' . $host . '/api/v1/ticket';
+    $p = array();
+    $p['post'] = json_encode(array('username' => $user, 'password' => $pass));
+    $p['header']['Content-Type'] = 'application/json';
+
+    $i = 0;
+    $res = false;
+    while ($i < REST_RETRIES) {
+        $res = fetch_url($url, $cookie, $error, $p);
+        if ($res) {
+            break;
+        }
+        sleep(REST_RETRY_INTERVAL);
+        ++$i;
     }
+    if ($res) {
+        $json = json_decode($res, true);
 
-    function apicGetTicket($host, $user, $pass, &$error)
-    {
-        $cookie = false;
-        $url = 'https://'.$host.'/api/v1/ticket';
-        $p = array();
-        $p['post'] = json_encode(array('username' => $user, 'password' => $pass));
-        $p['header']['Content-Type'] = 'application/json';
+        return $json['response']['serviceTicket'];
+    }
 
-        $i = 0;
-        $res = false;
-        while ($i < REST_RETRIES) {
-            $res = fetch_url($url, $cookie, $error, $p);
-            if ($res) {
-                break;
-            }
-            sleep(REST_RETRY_INTERVAL);
-            ++$i;
-        }
+    return false;
+}
+
+function apicAddDevice($host, $ticket, $projid, $device, $sn, $pid, &$msg, $config = null, $image = null)
+{
+    $cookie = false;
+    $error = '';
+    $url = 'https://' . $host . '/api/v1/pnp-project/' . $projid . '/device';
+    $p = array();
+    $params = array();
+    $params['hostName'] = $device;
+    $params['serialNumber'] = $sn;
+    $params['platformId'] = $pid;
+    if ($config) {
+        $params['configId'] = $config;
+    }
+    if ($image) {
+        $params['imageId'] = $image;
+    }
+    $p['post'] = json_encode($params);
+    $p['header']['Content-Type'] = 'application/json';
+    $p['header']['X-Auth-Token'] = $ticket;
+
+    $i = 0;
+    $res = false;
+    while ($i < REST_RETRIES) {
+        $res = fetch_url($url, $cookie, $error, $p);
         if ($res) {
-            $json = json_decode($res, true);
-
-            return $json['response']['serviceTicket'];
+            break;
         }
+        sleep(REST_RETRY_INTERVAL);
+        ++$i;
+    }
+    if ($res) {
+        $json = json_decode($res, true);
 
-        return false;
-    }
-
-    function apicAddDevice($host, $ticket, $projid, $device, $sn, $pid, &$msg, $config = null, $image = null)
-    {
-        $cookie = false;
-        $error = '';
-        $url = 'https://'.$host.'/api/v1/pnp-project/'.$projid.'/device';
-        $p = array();
-        $params = array();
-        $params['hostName'] = $device;
-        $params['serialNumber'] = $sn;
-        $params['platformId'] = $pid;
-        if ($config) {
-            $params['configId'] = $config;
-        }
-        if ($image) {
-            $params['imageId'] = $image;
-        }
-        $p['post'] = json_encode($params);
-        $p['header']['Content-Type'] = 'application/json';
-        $p['header']['X-Auth-Token'] = $ticket;
+        return apicGetTaskResult($host, $ticket, $json['response']['taskId'], $msg);
+    }
+
+    $msg = $error;
+
+    return false;
+}
 
+function apicGetTaskResult($host, $ticket, $task, &$msg, $timeout = 60)
+{
+    $cookie = false;
+    $error = '';
+    $url = 'https://' . $host . '/api/v1/task/' . $task;
+    $p = array();
+    $p['header']['X-Auth-Token'] = $ticket;
+
+    $done = false;
+    $j = 0;
+    while ($j < $timeout) {
         $i = 0;
         $res = false;
         while ($i < REST_RETRIES) {
@@ -263,26 +300,58 @@ MM_reloadPage(true);
         }
         if ($res) {
             $json = json_decode($res, true);
+            if (isset($json['response']['isError']) && $json['response']['isError'] === true) {
+                $msg = $json['response']['failureReason'];
 
-            return apicGetTaskResult($host, $ticket, $json['response']['taskId'], $msg);
+                return false;
+            }
+            if (isset($json['response']['endTime']) && $json['response']['endTime'] >= $json['response']['startTime']) {
+                return true;
+            }
+            // This allows the timeout to be specified in seconds.
+            sleep(1);
+            ++$j;
         }
+    }
 
+    if ($error != '') {
         $msg = $error;
+    } else {
+        $msg = 'Failed to get result from APIC-EM';
+    }
+
+    return false;
+}
+
+function apicGetProject($host, $ticket, $proj, &$error)
+{
+    $cookie = false;
+    $url = 'https://' . $host . '/api/v1/pnp-project/count';
 
-        return false;
+    $p = array();
+    $p['header']['X-Auth-Token'] = $ticket;
+
+    $i = 0;
+    $res = false;
+    while ($i < REST_RETRIES) {
+        $res = fetch_url($url, $cookie, $error, $p);
+        if ($res) {
+            break;
+        }
+        sleep(REST_RETRY_INTERVAL);
+        ++$i;
     }
+    if ($res) {
+        $json = json_decode($res, true);
+        $count = $json['response'];
 
-    function apicGetTaskResult($host, $ticket, $task, &$msg, $timeout = 60)
-    {
-        $cookie = false;
-        $error = '';
-        $url = 'https://'.$host.'/api/v1/task/'.$task;
-        $p = array();
-        $p['header']['X-Auth-Token'] = $ticket;
+        $url = 'https://' . $host . '/api/v1/pnp-project';
+        $offset = 1;
+        $limit = 500;
+        do {
+            $p['get']['offset'] = $offset;
+            $p['get']['limit'] = $limit;
 
-        $done = false;
-        $j = 0;
-        while ($j < $timeout) {
             $i = 0;
             $res = false;
             while ($i < REST_RETRIES) {
@@ -295,212 +364,148 @@ MM_reloadPage(true);
             }
             if ($res) {
                 $json = json_decode($res, true);
-                if (isset($json['response']['isError']) && $json['response']['isError'] === true) {
-                    $msg = $json['response']['failureReason'];
-
-                    return false;
-                }
-                if (isset($json['response']['endTime']) && $json['response']['endTime'] >= $json['response']['startTime']) {
-                    return true;
+                foreach ($json['response'] as $s) {
+                    if ($s['siteName'] == $proj) {
+                        return $s;
+                    }
                 }
-                // This allows the timeout to be specified in seconds.
-                sleep(1);
-                ++$j;
             }
-        }
 
-        if ($error != '') {
-            $msg = $error;
-        } else {
-            $msg = 'Failed to get result from APIC-EM';
-        }
-
-        return false;
+            $offset += $limit;
+        } while ($offset + $limit < $count);
     }
 
-    function apicGetProject($host, $ticket, $proj, &$error)
-    {
-        $cookie = false;
-        $url = 'https://'.$host.'/api/v1/pnp-project/count';
-
-        $p = array();
-        $p['header']['X-Auth-Token'] = $ticket;
-
-        $i = 0;
-        $res = false;
-        while ($i < REST_RETRIES) {
-            $res = fetch_url($url, $cookie, $error, $p);
-            if ($res) {
-                break;
-            }
-            sleep(REST_RETRY_INTERVAL);
-            ++$i;
-        }
+    return false;
+}
+
+function apicUpdateProject($host, $ticket, $projid, $proj, $ip, &$msg, $path = '/')
+{
+    $cookie = false;
+    $error = '';
+    $url = 'https://' . $host . '/api/v1/pnp-project';
+
+    $p = array();
+    $params = array();
+    $params['id'] = $projid;
+    $params['siteName'] = $proj;
+    $params['tftpServer'] = $ip;
+    $params['tftpPath'] = $path;
+    $p['put'] = json_encode($params);
+    $p['header']['Content-Type'] = 'application/json';
+    $p['header']['X-Auth-Token'] = $ticket;
+
+    $i = 0;
+    $res = false;
+    while ($i < REST_RETRIES) {
+        $res = fetch_url($url, $cookie, $error, $p);
         if ($res) {
-            $json = json_decode($res, true);
-            $count = $json['response'];
-
-            $url = 'https://'.$host.'/api/v1/pnp-project';
-            $offset = 1;
-            $limit = 500;
-            do {
-                $p['get']['offset'] = $offset;
-                $p['get']['limit'] = $limit;
-
-                $i = 0;
-                $res = false;
-                while ($i < REST_RETRIES) {
-                    $res = fetch_url($url, $cookie, $error, $p);
-                    if ($res) {
-                        break;
-                    }
-                    sleep(REST_RETRY_INTERVAL);
-                    ++$i;
-                }
-                if ($res) {
-                    $json = json_decode($res, true);
-                    foreach ($json['response'] as $s) {
-                        if ($s['siteName'] == $proj) {
-                            return $s;
-                        }
-                    }
-                }
-
-                $offset += $limit;
-            } while ($offset + $limit < $count);
+            break;
         }
-
-        return false;
+        sleep(REST_RETRY_INTERVAL);
+        ++$i;
     }
+    if ($res) {
+        $json = json_decode($res, true);
 
-    function apicUpdateProject($host, $ticket, $projid, $proj, $ip, &$msg, $path = '/')
-    {
-        $cookie = false;
-        $error = '';
-        $url = 'https://'.$host.'/api/v1/pnp-project';
+        return apicGetTaskResult($host, $ticket, $json['response']['taskId'], $msg);
+    }
 
-        $p = array();
-        $params = array();
-        $params['id'] = $projid;
-        $params['siteName'] = $proj;
-        $params['tftpServer'] = $ip;
-        $params['tftpPath'] = $path;
-        $p['put'] = json_encode($params);
-        $p['header']['Content-Type'] = 'application/json';
-        $p['header']['X-Auth-Token'] = $ticket;
+    $msg = $error;
 
-        $i = 0;
-        $res = false;
-        while ($i < REST_RETRIES) {
-            $res = fetch_url($url, $cookie, $error, $p);
-            if ($res) {
-                break;
-            }
-            sleep(REST_RETRY_INTERVAL);
-            ++$i;
-        }
-        if ($res) {
-            $json = json_decode($res, true);
+    return false;
+}
 
-            return apicGetTaskResult($host, $ticket, $json['response']['taskId'], $msg);
-        }
+function fetch_url($url, &$cookie, &$error, $p = false, $timeout = REST_TIMEOUT)
+{
+    $ch = curl_init();
 
-        $msg = $error;
+    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
+    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
-        return false;
+    if (DEBUG > 5) {
+        curl_setopt($ch, CURLOPT_HEADER, true);
+        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
+        curl_setopt($ch, CURLOPT_VERBOSE, true);
+    } else {
+        curl_setopt($ch, CURLOPT_HEADER, false);
     }
 
-    function fetch_url($url, &$cookie, &$error, $p = false, $timeout = REST_TIMEOUT)
-    {
-        $ch = curl_init();
-
-        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
-        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
-        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
-        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-
-        if (DEBUG > 5) {
-            curl_setopt($ch, CURLOPT_HEADER, true);
-            curl_setopt($ch, CURLINFO_HEADER_OUT, true);
-            curl_setopt($ch, CURLOPT_VERBOSE, true);
-        } else {
-            curl_setopt($ch, CURLOPT_HEADER, false);
+    if (isset($p['get'])) {
+        $url .= '?' . http_build_query($p['get']);
+    }
+    if (isset($p['post'])) {
+        curl_setopt($ch, CURLOPT_POST, count($p['post']));
+        curl_setopt($ch, CURLOPT_POSTFIELDS, $p['post']);
+    }
+    if (isset($p['put'])) {
+        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
+        $p['header']['Content-Length'] = strlen($p['put']);
+        curl_setopt($ch, CURLOPT_POSTFIELDS, $p['put']);
+    }
+    if (isset($p['header'])) {
+        foreach ($p['header'] as $name => $value) {
+            $header[] = $name . ': ' . $value;
         }
+        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
+    }
+    if (isset($p['cookie'])) {
+        curl_setopt($ch, CURLOPT_COOKIE, $p['cookie']);
+    }
+    if (isset($p['authentication'])) {
+        curl_setopt($ch, CURLOPT_USERPWD, $p['authentication']['user'] . ':' . $p['authentication']['password']);
+    }
 
-        if (isset($p['get'])) {
-            $url .= '?'.http_build_query($p['get']);
-        }
-        if (isset($p['post'])) {
-            curl_setopt($ch, CURLOPT_POST, count($p['post']));
-            curl_setopt($ch, CURLOPT_POSTFIELDS, $p['post']);
-        }
-        if (isset($p['put'])) {
-            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
-            $p['header']['Content-Length'] = strlen($p['put']);
-            curl_setopt($ch, CURLOPT_POSTFIELDS, $p['put']);
-        }
-        if (isset($p['header'])) {
-            foreach ($p['header'] as $name => $value) {
-                $header[] = $name.': '.$value;
-            }
-            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
-        }
-        if (isset($p['cookie'])) {
-            curl_setopt($ch, CURLOPT_COOKIE, $p['cookie']);
-        }
-        if (isset($p['authentication'])) {
-            curl_setopt($ch, CURLOPT_USERPWD, $p['authentication']['user'].':'.$p['authentication']['password']);
-        }
+    curl_setopt($ch, CURLOPT_URL, $url);
+
+    $response = curl_exec($ch);
+    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+    $error = 'cURL error num: ' . curl_errno($ch) . ' => ' . curl_error($ch);
+    if (DEBUG >= 5) {
+        echo '<h3>Request:</h3>';
+        var_dump(curl_getinfo($ch));
+        echo '<h3>Response:</h3>';
+        var_dump($response);
+        echo curl_error($ch) . "\n";
+    }
 
-        curl_setopt($ch, CURLOPT_URL, $url);
-
-        $response = curl_exec($ch);
-        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-        $error = 'cURL error num: '.curl_errno($ch).' => '.curl_error($ch);
-        if (DEBUG >= 5) {
-            echo '<h3>Request:</h3>';
-            var_dump(curl_getinfo($ch));
-            echo '<h3>Response:</h3>';
-            var_dump($response);
-            echo curl_error($ch)."\n";
-        }
+    if (empty($response)) {
+        if (DEBUG > 0) {
+            echo "WARNING: empty response from URL<br/>\n";
+            curl_close($ch);
 
-        if (empty($response)) {
+            return false;
+        }
+    } else {
+        if (empty($httpcode)) {
             if (DEBUG > 0) {
-                echo "WARNING: empty response from URL<br/>\n";
+                echo "WARNING: no HTTP code was returned\n$response\n";
                 curl_close($ch);
 
                 return false;
             }
-        } else {
-            if (empty($httpcode)) {
-                if (DEBUG > 0) {
-                    echo "WARNING: no HTTP code was returned\n$response\n";
-                    curl_close($ch);
-
-                    return false;
-                }
-            } elseif ($httpcode < 200 || $httpcode > 299) {
-                if (DEBUG > 0) {
-                    echo "ERROR: the server returned http code: $httpcode\n$response\n";
-                }
-                if (DEBUG > 1) {
-                    echo '<h3>Request:</h3>';
-                    var_dump(curl_getinfo($ch));
-                    echo '<h3>Response:</h3>';
-                    var_dump($response);
-                }
-                curl_close($ch);
+        } elseif ($httpcode < 200 || $httpcode > 299) {
+            if (DEBUG > 0) {
+                echo "ERROR: the server returned http code: $httpcode\n$response\n";
+            }
+            if (DEBUG > 1) {
+                echo '<h3>Request:</h3>';
+                var_dump(curl_getinfo($ch));
+                echo '<h3>Response:</h3>';
+                var_dump($response);
+            }
+            curl_close($ch);
 
-                $cookie = false;
-                $error = $httpcode;
+            $cookie = false;
+            $error = $httpcode;
 
-                return false;
-            } else {
-                curl_close($ch);
+            return false;
+        } else {
+            curl_close($ch);
 
-                return $response;
-            }
+            return $response;
         }
     }
-?>
+}
+?>

+ 2 - 2
www/get_dev_stats.php

@@ -43,7 +43,7 @@ try {
     die($e->getMessage());
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : AJAX Get Device Stats');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : AJAX Get Device Stats');
 if ($logger === false) {
     die("Failed to open logfile.\n");
 }
@@ -73,4 +73,4 @@ while ($row = $sth->fetch()) {
 }
 
 echo json_encode($result);
-cleanup();
+cleanup();

+ 11 - 6
www/get_logicsw_details.php

@@ -43,7 +43,7 @@ try {
     die($e->getMessage());
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : AJAX Get Logical Switch Details');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : AJAX Get Logical Switch Details');
 if ($logger === false) {
     die("Failed to open logfile.\n");
 }
@@ -69,13 +69,18 @@ $result['response'] = array();
 
 while ($row = $sth->fetch()) {
     $tbase = '';
-    if (file_exists(PORT_TMPL_DIR.'/devices/'."{$row['name']}-ports.tmpl")) {
-        $targ = readlink(PORT_TMPL_DIR.'/devices/'."{$row['name']}-ports.tmpl");
+    if (file_exists(PORT_TMPL_DIR . '/devices/' . "{$row['name']}-ports.tmpl")) {
+        $targ = readlink(PORT_TMPL_DIR . '/devices/' . "{$row['name']}-ports.tmpl");
         $tbase = basename($targ);
     }
-    $result['response'][$row['name']] = array('location' => (is_null($row['location']) ? '' : $row['location']), 'is_idf' => $row['is_idf'],
-        'ip_address' => (is_null($row['ip_address']) ? '' : $row['ip_address']), 'pid' => (is_null($row['pid']) ? '' : $row['pid']), 'exception' => $tbase);
+    $result['response'][$row['name']] = array(
+        'location' => (is_null($row['location']) ? '' : $row['location']),
+        'is_idf' => $row['is_idf'],
+        'ip_address' => (is_null($row['ip_address']) ? '' : $row['ip_address']),
+        'pid' => (is_null($row['pid']) ? '' : $row['pid']),
+        'exception' => $tbase
+    );
 }
 
 echo json_encode($result);
-cleanup();
+cleanup();

+ 374 - 328
www/index.php

@@ -32,20 +32,20 @@ require_once 'functions.php';
 $dsn = "$db_driver:host=$db_host;dbname=$db_name";
 
 $options = [
-    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
-    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
-    PDO::ATTR_EMULATE_PREPARES => false,
+  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
+  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
+  PDO::ATTR_EMULATE_PREPARES => false,
 ];
 
 try {
-    $dbh = new PDO($dsn, $db_user, $db_pass, $options);
+  $dbh = new PDO($dsn, $db_user, $db_pass, $options);
 } catch (PDOException $e) {
-    die($e->getMessage());
+  die($e->getMessage());
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Physical Switches');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Physical Switches');
 if ($logger === false) {
-    die("Failed to open logfile.\n");
+  die("Failed to open logfile.\n");
 }
 $mask = Log::UPTO(LOG_LEVEL);
 $logger->setMask($mask);
@@ -53,207 +53,208 @@ $logger->setMask($mask);
 $base = get_base($_SERVER['SCRIPT_NAME']);
 $ruser = '<AUTHENTICATION NOT ENABLED>';
 if (isset($_SERVER['REMOTE_USER'])) {
-    $ruser = $_SERVER['REMOTE_USER'];
+  $ruser = $_SERVER['REMOTE_USER'];
 }
 
 $errors = array();
 if (isset($_REQUEST['prev_checked'])) {
-    $pc = $_REQUEST['prev_checked'];
-    $pas = $_REQUEST['prev_assigned_switch'];
-    $c = (isset($_REQUEST['checked'])) ? $_REQUEST['checked'] : array();
-    $as = $_REQUEST['assigned_switch'];
-    $d = (isset($_REQUEST['delete'])) ? $_REQUEST['delete'] : array();
-    $rz = (isset($_REQUEST['reztp'])) ? $_REQUEST['reztp'] : array();
-    foreach ($pc as $swsn => $value) {
-        $curr_del = (isset($d[$swsn])) ? $d[$swsn] : 0;
-        $curr_rz = (isset($rz[$swsn])) ? $rz[$swsn] : 0;
-        if ($curr_del == 1) {
-            $sql = "DELETE FROM DEVICE_MAP WHERE serial_number=:sn";
-            try {
-                $sth = $dbh->prepare($sql);
-                $sth->execute(['sn' => $swsn]);
-                $sth->closeCursor();
-                $logger->info("User {$ruser} deleted physical switch {$swsn}");
-            } catch (PDOException $e) {
-                array_push($errors, "Failed to delete switch {$swsn}: {$e->getMessage()}");
-            }
-            continue;
-        }
-        if ($curr_rz == 1) {
-            $sql = "UPDATE DEVICE_MAP SET should_re_ztp=:rz WHERE serial_number=:sn";
-            try {
-                $sth = $dbh->prepare($sql);
-                $sth->execute(['sn' => $swsn, 'rz' => 2]);
-                $sth->closeCursor();
-                $logger->info("User {$ruser} set physical switch {$swsn} to re-ZTP");
-            } catch (PDOException $e) {
-                array_push($errors, "Failed to set switch {$swsn} to re-ZTP: {$e->getMessage()}");
-            }
+  $pc = $_REQUEST['prev_checked'];
+  $pas = $_REQUEST['prev_assigned_switch'];
+  $c = (isset($_REQUEST['checked'])) ? $_REQUEST['checked'] : array();
+  $as = $_REQUEST['assigned_switch'];
+  $d = (isset($_REQUEST['delete'])) ? $_REQUEST['delete'] : array();
+  $rz = (isset($_REQUEST['reztp'])) ? $_REQUEST['reztp'] : array();
+  foreach ($pc as $swsn => $value) {
+    $curr_del = (isset($d[$swsn])) ? $d[$swsn] : 0;
+    $curr_rz = (isset($rz[$swsn])) ? $rz[$swsn] : 0;
+    if ($curr_del == 1) {
+      $sql = "DELETE FROM DEVICE_MAP WHERE serial_number=:sn";
+      try {
+        $sth = $dbh->prepare($sql);
+        $sth->execute(['sn' => $swsn]);
+        $sth->closeCursor();
+        $logger->info("User {$ruser} deleted physical switch {$swsn}");
+      } catch (PDOException $e) {
+        array_push($errors, "Failed to delete switch {$swsn}: {$e->getMessage()}");
+      }
+      continue;
+    }
+    if ($curr_rz == 1) {
+      $sql = "UPDATE DEVICE_MAP SET should_re_ztp=:rz WHERE serial_number=:sn";
+      try {
+        $sth = $dbh->prepare($sql);
+        $sth->execute(['sn' => $swsn, 'rz' => 2]);
+        $sth->closeCursor();
+        $logger->info("User {$ruser} set physical switch {$swsn} to re-ZTP");
+      } catch (PDOException $e) {
+        array_push($errors, "Failed to set switch {$swsn} to re-ZTP: {$e->getMessage()}");
+      }
+    }
+    $curr_checked = (isset($c[$swsn])) ? $c[$swsn] : 0;
+    if ($value != $curr_checked || $pas[$swsn] != $as[$swsn]) {
+      $nc = $curr_checked;
+      $additional = '';
+      if ($nc == 1 && $as == '__BOGUS__') {
+        array_push($errors, "You must select a logical switch assignment for $swsn");
+      } else {
+        if ($nc == 0 || $as == '__BOGUS__') {
+          $nas = 'NULL';
+          $additional = ", provisioned_status = '" . PROVISION_UNKNOWN . "', device_status = '" . REACHABILITY_NEVER_REACHABLE . "'";
+        } else {
+          $nas = "'{$as[$swsn]}'";
         }
-        $curr_checked = (isset($c[$swsn])) ? $c[$swsn] : 0;
-        if ($value != $curr_checked || $pas[$swsn] != $as[$swsn]) {
-            $nc = $curr_checked;
-            $additional = '';
-            if ($nc == 1 && $as == '__BOGUS__') {
-                array_push($errors, "You must select a logical switch assignment for $swsn");
-            } else {
-                if ($nc == 0 || $as == '__BOGUS__') {
-                    $nas = 'NULL';
-                    $additional = ", provisioned_status = '".PROVISION_UNKNOWN."', device_status = '".REACHABILITY_NEVER_REACHABLE."'";
-                } else {
-                    $nas = "'{$as[$swsn]}'";
-                }
-                $sql = "UPDATE DEVICE_MAP SET checked_out='{$nc}', assigned_switch = {$nas} {$additional} WHERE serial_number='{$swsn}'";
-                try {
-                    $dbh->query($sql);
-                    $logger->info("User {$ruser} updated physical switches, checked_out={$nc}, assigned_switch={$nas} for serial_number={$swsn}");
-                } catch (PDOException $e) {
-                    array_push($errors, "Failed to update $swsn: '{$e->getMessage()}'");
-                }
-            }
+        $sql = "UPDATE DEVICE_MAP SET checked_out='{$nc}', assigned_switch = {$nas} {$additional} WHERE serial_number='{$swsn}'";
+        try {
+          $dbh->query($sql);
+          $logger->info("User {$ruser} updated physical switches, checked_out={$nc}, assigned_switch={$nas} for serial_number={$swsn}");
+        } catch (PDOException $e) {
+          array_push($errors, "Failed to update $swsn: '{$e->getMessage()}'");
         }
+      }
     }
+  }
 }
 
 $wc = '';
 if (isset($_REQUEST['filter'])) {
-    switch ($_REQUEST['filter']) {
+  switch ($_REQUEST['filter']) {
     case 'a':
-        $wc = '';
-        break;
+      $wc = '';
+      break;
     case 'p':
-        $wc = 'WHERE assigned_switch IS NOT NULL';
-        break;
+      $wc = 'WHERE assigned_switch IS NOT NULL';
+      break;
     case 'up':
-        $wc = 'WHERE assigned_switch IS NULL';
-        break;
+      $wc = 'WHERE assigned_switch IS NULL';
+      break;
     case 'vu':
-        $wc = 'WHERE provisioned_status=\''.PROVISION_UNKNOWN.'\'';
-        break;
+      $wc = 'WHERE provisioned_status=\'' . PROVISION_UNKNOWN . '\'';
+      break;
     case 'vi':
-        $wc = 'WHERE provisioned_status=\''.PROVISION_IN_PROGRESS.'\'';
-        break;
+      $wc = 'WHERE provisioned_status=\'' . PROVISION_IN_PROGRESS . '\'';
+      break;
     case 'vf':
-        $wc = 'WHERE provisioned_status=\''.PROVISION_FAIL.'\'';
-        break;
+      $wc = 'WHERE provisioned_status=\'' . PROVISION_FAIL . '\'';
+      break;
     case 'vs':
-        $wc = 'WHERE provisioned_status=\''.PROVISION_SUCCESS.'\'';
-        break;
+      $wc = 'WHERE provisioned_status=\'' . PROVISION_SUCCESS . '\'';
+      break;
     case 'r':
-        $wc = 'WHERE device_status=\''.REACHABILITY_REACHABLE.'\'';
-        break;
+      $wc = 'WHERE device_status=\'' . REACHABILITY_REACHABLE . '\'';
+      break;
     case 'ur':
-        $wc = 'WHERE provisioned_status=\''.PROVISION_SUCCESS.'\' AND (device_status=\''.REACHABILITY_NEVER_REACHABLE.'\' OR device_status=\''.REACHABILITY_NOW_UNREACHABLE.'\')';
-        break;
+      $wc = 'WHERE provisioned_status=\'' . PROVISION_SUCCESS . '\' AND (device_status=\'' . REACHABILITY_NEVER_REACHABLE . '\' OR device_status=\'' . REACHABILITY_NOW_UNREACHABLE . '\')';
+      break;
     default:
-        if (preg_match("/^pid:([\w\d-]+)/", $_REQUEST['filter'], $match)) {
-            $wc = "WHERE pid = '{$match[1]}'";
-        } else {
-            $wc = '';
-        }
-        break;
-    }
+      if (preg_match("/^pid:([\w\d-]+)/", $_REQUEST['filter'], $match)) {
+        $wc = "WHERE pid = '{$match[1]}'";
+      } else {
+        $wc = '';
+      }
+      break;
+  }
 }
 
 $res = null;
 if (isset($_REQUEST['switch_name'])) {
-    $sql = "SELECT * FROM DEVICE_MAP WHERE serial_number LIKE :swname1 OR assigned_switch LIKE :swname2 ORDER BY LPAD(lower(serial_number), 10, 0)";
-    try {
-        $res = $dbh->prepare($sql);
-        $res->execute(['swname1' => "%{$_REQUEST['switch_name']}%", 'swname2' => "%{$_REQUEST['switch_name']}%"]);
-    } catch (PDOException $e) {
-        echo "<p><font color=\"red\">Error querying for physical switches: {$e->getMessage()}</font></p>\r\n";
-        exit(1);
-    }
+  $sql = "SELECT * FROM DEVICE_MAP WHERE serial_number LIKE :swname1 OR assigned_switch LIKE :swname2 ORDER BY LPAD(lower(serial_number), 10, 0)";
+  try {
+    $res = $dbh->prepare($sql);
+    $res->execute(['swname1' => "%{$_REQUEST['switch_name']}%", 'swname2' => "%{$_REQUEST['switch_name']}%"]);
+  } catch (PDOException $e) {
+    echo "<p><font color=\"red\">Error querying for physical switches: {$e->getMessage()}</font></p>\r\n";
+    exit(1);
+  }
 } else {
-    $sql = 'SELECT * FROM DEVICE_MAP '.$wc.' ORDER BY LPAD(lower(serial_number), 10, 0)';
-    try {
-        $res = $dbh->query($sql);
-    } catch (PDOException $e) {
-        echo "<p><font color=\"red\">Error querying for physical switches: {$e->getMessage()}</font></p>\r\n";
-        exit(1);
-    }
+  $sql = 'SELECT * FROM DEVICE_MAP ' . $wc . ' ORDER BY LPAD(lower(serial_number), 10, 0)';
+  try {
+    $res = $dbh->query($sql);
+  } catch (PDOException $e) {
+    echo "<p><font color=\"red\">Error querying for physical switches: {$e->getMessage()}</font></p>\r\n";
+    exit(1);
+  }
 }
 
 $sql = 'SELECT name, pid FROM SWITCHES WHERE ip_address IS NOT NULL ORDER BY name';
 $ls_res = null;
 try {
-    $ls_res = $dbh->query($sql);
+  $ls_res = $dbh->query($sql);
 } catch (PDOException $e) {
-    echo "<p><font color=\"red\">Error querying for logical switches: {$e->getMessage()}</font></p>\r\n";
-    exit(1);
+  echo "<p><font color=\"red\">Error querying for logical switches: {$e->getMessage()}</font></p>\r\n";
+  exit(1);
 }
 
 $lswitches = array();
 while ($row = $ls_res->fetch()) {
-    if (!isset($lswitches[$row['pid']])) {
-        $lswitches[$row['pid']] = array('__BOGUS__', $row['name']);
-    } else {
-        array_push($lswitches[$row['pid']], $row['name']);
-    }
+  if (!isset($lswitches[$row['pid']])) {
+    $lswitches[$row['pid']] = array('__BOGUS__', $row['name']);
+  } else {
+    array_push($lswitches[$row['pid']], $row['name']);
+  }
 }
 
 $switches = array();
 while ($row = $res->fetch()) {
-    array_push($switches, $row);
+  array_push($switches, $row);
 }
 
 $sql = 'SELECT DISTINCT(pid) AS pid FROM DEVICE_MAP';
 try {
-    $res = $dbh->query($sql);
+  $res = $dbh->query($sql);
 } catch (PDOException $e) {
-    echo "<p><font color=\"red\">Error querying for PIDs: {$e->getMessage()}</font></p>\r\n";
-    exit(1);
+  echo "<p><font color=\"red\">Error querying for PIDs: {$e->getMessage()}</font></p>\r\n";
+  exit(1);
 }
 
 $pids = array();
 while ($row = $res->fetch()) {
-    $pids[$row['pid']] = true;
+  $pids[$row['pid']] = true;
 }
 
 $sql = 'SELECT assigned_switch FROM DEVICE_MAP WHERE assigned_switch IS NOT NULL';
 try {
-    $res = $dbh->query($sql);
+  $res = $dbh->query($sql);
 } catch (PDOException $e) {
-    echo "<p><font color=\"red\">Error querying for assigned switches: {$e->getMessage()}</font></p>\r\n";
-    exit(1);
+  echo "<p><font color=\"red\">Error querying for assigned switches: {$e->getMessage()}</font></p>\r\n";
+  exit(1);
 }
 
 $used = array();
 while ($row = $res->fetch()) {
-    $used[$row['assigned_switch']] = true;
+  $used[$row['assigned_switch']] = true;
 }
 
 $filt = null;
 if (!isset($_REQUEST['filter'])) {
-    $filt = '';
+  $filt = '';
 } else {
-    $filt = $_REQUEST['filter'];
+  $filt = $_REQUEST['filter'];
 }
 
-print_header(TOOL_NAME.': Physical Switches');
+print_header(TOOL_NAME . ': Physical Switches');
 ?>
-  <body class="flex">
-    <script language="javascript">
+
+<body class="flex">
+  <script language="javascript">
     var deletes = 0;
 
-    var PROVISION_UNKNOWN = <?=PROVISION_UNKNOWN?>;
-    var PROVISION_IN_PROGRESS = <?=PROVISION_IN_PROGRESS?>;
-    var PROVISION_FAIL = <?=PROVISION_FAIL?>;
-    var PROVISION_SUCCESS = <?=PROVISION_SUCCESS?>;
+    var PROVISION_UNKNOWN = <?= PROVISION_UNKNOWN ?>;
+    var PROVISION_IN_PROGRESS = <?= PROVISION_IN_PROGRESS ?>;
+    var PROVISION_FAIL = <?= PROVISION_FAIL ?>;
+    var PROVISION_SUCCESS = <?= PROVISION_SUCCESS ?>;
 
-    var REACHABILITY_NEVER_REACHABLE = <?=REACHABILITY_NEVER_REACHABLE?>;
-    var REACHABILITY_NOW_UNREACHABLE = <?=REACHABILITY_NOW_UNREACHABLE?>;
-    var REACHABILITY_REACHABLE = <?=REACHABILITY_REACHABLE?>;
+    var REACHABILITY_NEVER_REACHABLE = <?= REACHABILITY_NEVER_REACHABLE ?>;
+    var REACHABILITY_NOW_UNREACHABLE = <?= REACHABILITY_NOW_UNREACHABLE ?>;
+    var REACHABILITY_REACHABLE = <?= REACHABILITY_REACHABLE ?>;
 
     var row_intervals = {};
 
     function refresh() {
       $.ajax({
-        url: '<?=$base?>/get_dev_stats.php',
+        url: '<?= $base ?>/get_dev_stats.php',
         dataType: 'json',
-        success: function(data) {
-          $.each(data.response, function(k, v) {
+        success: function (data) {
+          $.each(data.response, function (k, v) {
             var rtext = '&nbsp;';
             var color = '#FFFFFF';
             var rtitle = 'Not yet assigned';
@@ -295,7 +296,7 @@ print_header(TOOL_NAME.': Physical Switches');
                 clearInterval(row_intervals[k]);
                 $('#psr_' + k).stop(true, true);
               }
-              var pulseint = setInterval(function() {
+              var pulseint = setInterval(function () {
                 $('#psr_' + k).animate({
                   backgroundColor: '#919191',
                 }, 1000).animate({
@@ -330,58 +331,58 @@ print_header(TOOL_NAME.': Physical Switches');
             $('#dsr_' + k).attr('title', rtitle);
           });
         },
-        complete: function(xhr, message) {
+        complete: function (xhr, message) {
           setTimeout(refresh, 30000);
         }
       });
     }
 
     function reztp_all() {
-        if ($('#reztp_all_box').is(':checked')) {
-		$('.reztp').each(function() {
-			$(this).prop('checked', true);
-		});
-	} else {
-		$('.reztp').each(function() {
-			$(this).prop('checked', false);
-		});
-	}
-
-	return true;
+      if ($('#reztp_all_box').is(':checked')) {
+        $('.reztp').each(function () {
+          $(this).prop('checked', true);
+        });
+      } else {
+        $('.reztp').each(function () {
+          $(this).prop('checked', false);
+        });
+      }
+
+      return true;
     }
 
     function toggle_reztp_all(elem) {
-	    if (!$(elem).is(':checked')) {
-		    $('#reztp_all_box').prop('checked', false);
-	    }
+      if (!$(elem).is(':checked')) {
+        $('#reztp_all_box').prop('checked', false);
+      }
     }
 
     function check_confirm() {
-	    var delete_conf = true;
-	    var reztp_conf = true;
-	    if (deletes > 0) {
-		    delete_conf = confirm("Are you sure you want to delete these " + deletes + " physical switch(es)?");
-	    }
-
-	    $('.reztp').each(function() {
-		    if ($(this).is(':checked')) {
-			    one_checked = true;
-			    return;
-		    }
-	    });
-
-	    if (one_checked) {
-		    reztp_conf = confirm("Are you sure you want to re-ZTP these switches?");
-	    }
-
-	    return reztp_conf && delete_conf;
+      var delete_conf = true;
+      var reztp_conf = true;
+      if (deletes > 0) {
+        delete_conf = confirm("Are you sure you want to delete these " + deletes + " physical switch(es)?");
+      }
+
+      $('.reztp').each(function () {
+        if ($(this).is(':checked')) {
+          one_checked = true;
+          return;
+        }
+      });
+
+      if (one_checked) {
+        reztp_conf = confirm("Are you sure you want to re-ZTP these switches?");
+      }
+
+      return reztp_conf && delete_conf;
     }
 
-    if ( window.history.replaceState ) {
-        window.history.replaceState( null, null, window.location.href );
+    if (window.history.replaceState) {
+      window.history.replaceState(null, null, window.location.href);
     }
 
-    $(document).ready(function() {
+    $(document).ready(function () {
       $('#devtable').DataTable({
         "scrollY": "400px",
         "scrollCollapse": true,
@@ -389,190 +390,235 @@ print_header(TOOL_NAME.': Physical Switches');
       });
       refresh();
     });
-    </script>
-    <div id="headswreg">
-      <div class="apage">
-        <div id="header">
-	  <h1><?=TOOL_NAME?>: Physical Switches</h1>
-        </div>
-        <br/>
+  </script>
+  <div id="headswreg">
+    <div class="apage">
+      <div id="header">
+        <h1>
+          <?= TOOL_NAME ?>: Physical Switches
+        </h1>
       </div>
+      <br />
     </div>
-    <div class="apage">
-       <form method="POST" name="search_form" action="<?=$_SERVER['PHP_SELF']?>">
-       <table class="noborder" summary="Filter Table">
-         <tr>
-	   <td class="left_act">Show Only:
-             <select name="filter" onChange="MM_jumpMenu('parent', this, 0)">
-	       <option value="<?=$_SERVER['PHP_SELF']?>?filter=a" <?=($filt == 'a') ? 'selected' : ''?>>All</option>
-	       <option value="<?=$_SERVER['PHP_SELF']?>?filter=p" <?=($filt == 'p') ? 'selected' : ''?>>Assigned</option>
-	       <option value="<?=$_SERVER['PHP_SELF']?>?filter=up" <?=($filt == 'up') ? 'selected' : ''?>>Unassigned</option>
-               <option value="<?=$_SERVER['PHP_SELF']?>?filter=vu" <?=($filt == 'vu') ? 'selected' : ''?>>Not Yet Bootstrapped</option>
-               <option value="<?=$_SERVER['PHP_SELF']?>?filter=vi" <?=($filt == 'vi') ? 'selected' : ''?>>Bootstrapping In Progress</option>
-	       <option value="<?=$_SERVER['PHP_SELF']?>?filter=vf" <?=($filt == 'vf') ? 'selected' : ''?>>Verification Failed</option>
-	       <option value="<?=$_SERVER['PHP_SELF']?>?filter=vs" <?=($filt == 'vs') ? 'selected' : ''?>>Verification Succeeded</option>
-	       <option value="<?=$_SERVER['PHP_SELF']?>?filter=r" <?=($filt == 'r') ? 'selected' : ''?>>Reachable</option>
-	       <option value="<?=$_SERVER['PHP_SELF']?>?filter=ur" <?=($filt == 'ur') ? 'selected' : ''?>>Unreachable</option>
-<?php
-foreach ($pids as $lsp => $value) {
-    $selected = ($filt == "pid:$lsp") ? 'selected' : ''; ?>
-	       <option value="<?=$_SERVER['PHP_SELF']?>?filter=pid:<?=$lsp?>" <?=$selected?>><?=$lsp?></option>
-<?php
-}
-?>
-           </select></td>
-             <td class="right">Switch Search:
-	       <input type="text" size="16" name="switch_name" value="<?=(isset($_REQUEST['switch_name'])) ? $_REQUEST['switch_name'] : ''?>">
-               <input type="image" value="Submit" name="search" src="/images/submit_button.png">
-             </td>
-        </tr>
-      </table>
-      </form>
-      <br/>
-      <table class="noborder" summary="Control Table">
+  </div>
+  <div class="apage">
+    <form method="POST" name="search_form" action="<?= $_SERVER['PHP_SELF'] ?>">
+      <table class="noborder" summary="Filter Table">
         <tr>
-	  <td class="left"><a href="<?=$base?>/add_phys.php">Add Physical Switch</a> |
-      <?php
-      if (EXPORT_PRIME === true) {
-          ?>
-	    <a href="#" onClick="window.open('<?=$base?>/export.php')">Export to Prime / DNS</a> |
-      <?php
-      }
-    if (EXPORT_DEADMAN === true) {
-        ?>
-            <a href="#" onClick="window.open('<?=$base?>/export_deadman.php')">Export To Ansible</a> |
-            <?php
-    } ?>
-	    <a href="<?=$base?>/logicsw.php">Logical Switches</a></td>
+          <td class="left_act">Show Only:
+            <select name="filter" onChange="MM_jumpMenu('parent', this, 0)">
+              <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=a" <?= ($filt == 'a') ? 'selected' : '' ?>>All</option>
+              <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=p" <?= ($filt == 'p') ? 'selected' : '' ?>>Assigned</option>
+              <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=up" <?= ($filt == 'up') ? 'selected' : '' ?>>Unassigned
+              </option>
+              <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=vu" <?= ($filt == 'vu') ? 'selected' : '' ?>>Not Yet
+                Bootstrapped</option>
+              <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=vi" <?= ($filt == 'vi') ? 'selected' : '' ?>>Bootstrapping In
+                Progress</option>
+              <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=vf" <?= ($filt == 'vf') ? 'selected' : '' ?>>Verification
+                Failed</option>
+              <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=vs" <?= ($filt == 'vs') ? 'selected' : '' ?>>Verification
+                Succeeded</option>
+              <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=r" <?= ($filt == 'r') ? 'selected' : '' ?>>Reachable</option>
+              <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=ur" <?= ($filt == 'ur') ? 'selected' : '' ?>>Unreachable
+              </option>
+              <?php
+              foreach ($pids as $lsp => $value) {
+                $selected = ($filt == "pid:$lsp") ? 'selected' : ''; ?>
+                <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=pid:<?= $lsp ?>" <?= $selected ?>><?= $lsp ?></option>
+                <?php
+              }
+              ?>
+            </select>
+          </td>
+          <td class="right">Switch Search:
+            <input type="text" size="16" name="switch_name"
+              value="<?= (isset($_REQUEST['switch_name'])) ? $_REQUEST['switch_name'] : '' ?>">
+            <input type="image" value="Submit" name="search" src="/images/submit_button.png">
+          </td>
         </tr>
       </table>
-      <form name="mod_phys_switch_form" method="POST" action="<?=$_SERVER['PHP_SELF']?>" onSubmit='return check_confirm();'>
-<?php
+    </form>
+    <br />
+    <table class="noborder" summary="Control Table">
+      <tr>
+        <td class="left"><a href="<?= $base ?>/add_phys.php">Add Physical Switch</a> |
+          <?php
+          if (EXPORT_PRIME === true) {
+            ?>
+            <a href="#" onClick="window.open('<?= $base ?>/export.php')">Export to Prime / DNS</a> |
+            <?php
+          }
+          if (EXPORT_DEADMAN === true) {
+            ?>
+            <a href="#" onClick="window.open('<?= $base ?>/export_deadman.php')">Export To Ansible</a> |
+            <?php
+          } ?>
+          <a href="<?= $base ?>/logicsw.php">Logical Switches</a>
+        </td>
+      </tr>
+    </table>
+    <form name="mod_phys_switch_form" method="POST" action="<?= $_SERVER['PHP_SELF'] ?>"
+      onSubmit='return check_confirm();'>
+      <?php
 
-    foreach (array_merge($_GET, $_POST) as $name => $value) {
+      foreach (array_merge($_GET, $_POST) as $name => $value) {
         if (!is_array($value)) {
-            ?>
-          <input type="hidden" name="<?=$name?>" value="<?=$value?>">
-<?php
+          ?>
+          <input type="hidden" name="<?= $name ?>" value="<?= $value ?>">
+          <?php
         }
-    }
-?>
-        <div class="btable">
+      }
+      ?>
+      <div class="btable">
         <table summary="Button Table" width="100%" cellspacing="0">
           <tr>
             <td><input type="reset" value="Reset" name="reset">
-            <input type="submit" value="Submit" name="submit"></td>
+              <input type="submit" value="Submit" name="submit">
+            </td>
           </tr>
         </table>
-        </div>
-        <br/>
-        <div align="center">
-<?php
-foreach ($errors as $error) {
-    ?>
-          <p class="error"><?=$error?></p>
-<?php
-}
-?>
-        </div>
-        <div class="maintable">
+      </div>
+      <br />
+      <div align="center">
+        <?php
+        foreach ($errors as $error) {
+          ?>
+          <p class="error">
+            <?= $error ?>
+          </p>
+          <?php
+        }
+        ?>
+      </div>
+      <div class="maintable">
         <table id="devtable" class="cell-border compact" width="100%" cellspacing="0" summary="Physical Switch Table">
           <thead>
-          <tr>
-            <th class="headlink">Row No.</th>
-            <th class="headlink">Delete?</th>
-            <th class="headlink">Assigned?</th>
-            <th class="headlink">Re-ZTP? <input type="checkbox" id="reztp_all_box" onchange="return reztp_all();"></th>
-            <th class="headlink">Serial Number</th>
-            <th class="headlink">Product ID</th>
-            <th class="headlink">Max Ports</th>
-            <th class="headlink">Assigned Logical<br/>Switch</th>
-            <th class="headlink">Provision<br/>Status</th>
-            <th class="headlink">Reachability</th>
-          </tr>
+            <tr>
+              <th class="headlink">Row No.</th>
+              <th class="headlink">Delete?</th>
+              <th class="headlink">Assigned?</th>
+              <th class="headlink">Re-ZTP? <input type="checkbox" id="reztp_all_box" onchange="return reztp_all();">
+              </th>
+              <th class="headlink">Serial Number</th>
+              <th class="headlink">Product ID</th>
+              <th class="headlink">Max Ports</th>
+              <th class="headlink">Assigned Logical<br />Switch</th>
+              <th class="headlink">Provision<br />Status</th>
+              <th class="headlink">Reachability</th>
+            </tr>
           </thead>
           <tbody>
-<?php
-$i = 0;
-foreach ($switches as $row) {
-    $sn = $row['serial_number'];
-    $checked = false;
-    $will_rz = false;
-    if ($row['checked_out'] == 1) {
-        $checked = true;
-    }
+            <?php
+            $i = 0;
+            foreach ($switches as $row) {
+              $sn = $row['serial_number'];
+              $checked = false;
+              $will_rz = false;
+              if ($row['checked_out'] == 1) {
+                $checked = true;
+              }
 
-    if ($row['should_re_ztp'] > 0) {
-        $will_rz = true;
-    } ?>
-          <tr>
-            <td><?=$i + 1?>.</td>
-            <td><input type="checkbox" name="delete[<?=$sn?>]" value="1" onClick="if (this.checked == true) { deletes++; } else { deletes--; }"></td>
-	    <td><input type="hidden" name="prev_checked[<?=$sn?>]" value="<?=$row['checked_out']?>">
-                <input id="checked_<?=$i?>" type="checkbox" name="checked[<?=$sn?>]" value="1" <?=($checked) ? 'checked' : ''?>></td>
-		<td><input id="reztp_<?=$i?>" class="reztp" type="checkbox" name="reztp[<?=$sn?>]" value="1" onchange="toggle_reztp_all(this);" <?=($will_rz) ? 'disabled' : ''?>></td>
-	    <td><?=$row['serial_number']?></td>
-            <td><?=$row['pid']?></td>
-            <td><?=$row['max_ports']?></td>
-	    <td><input type="hidden" name="prev_assigned_switch[<?=$sn?>]" value="<?=$row['assigned_switch']?>">
-                <select id="asw<?=$i?>" name="assigned_switch[<?=$sn?>]" onChange='var elem = document.getElementById("checked_<?=$i?>"); if (this.value == "__BOGUS__") { elem.checked = false; } else { elem.checked = true; }'>
-<?php
-    $has_avail = false;
-    foreach ($lswitches[$row['pid']] as $lsw) {
-        $selected = ($row['assigned_switch'] == $lsw) ? 'selected' : '';
-        if ($selected == '' && isset($used[$lsw]) && $used[$lsw] === true) {
-            continue;
-        }
-        if ($lsw == '__BOGUS__') {
+              if ($row['should_re_ztp'] > 0) {
+                $will_rz = true;
+              } ?>
+              <tr>
+                <td>
+                  <?= $i + 1 ?>.
+                </td>
+                <td><input type="checkbox" name="delete[<?= $sn ?>]" value="1"
+                    onClick="if (this.checked == true) { deletes++; } else { deletes--; }"></td>
+                <td><input type="hidden" name="prev_checked[<?= $sn ?>]" value="<?= $row['checked_out'] ?>">
+                  <input id="checked_<?= $i ?>" type="checkbox" name="checked[<?= $sn ?>]" value="1" <?= ($checked) ? 'checked' : '' ?>>
+                </td>
+                <td><input id="reztp_<?= $i ?>" class="reztp" type="checkbox" name="reztp[<?= $sn ?>]" value="1"
+                    onchange="toggle_reztp_all(this);" <?= ($will_rz) ? 'disabled' : '' ?>></td>
+                <td>
+                  <?= $row['serial_number'] ?>
+                </td>
+                <td>
+                  <?= $row['pid'] ?>
+                </td>
+                <td>
+                  <?= $row['max_ports'] ?>
+                </td>
+                <td><input type="hidden" name="prev_assigned_switch[<?= $sn ?>]" value="<?= $row['assigned_switch'] ?>">
+                  <select id="asw<?= $i ?>" name="assigned_switch[<?= $sn ?>]"
+                    onChange='var elem = document.getElementById("checked_<?= $i ?>"); if (this.value == "__BOGUS__") { elem.checked = false; } else { elem.checked = true; }'>
+                    <?php
+                    $has_avail = false;
+                    foreach ($lswitches[$row['pid']] as $lsw) {
+                      $selected = ($row['assigned_switch'] == $lsw) ? 'selected' : '';
+                      if ($selected == '' && isset($used[$lsw]) && $used[$lsw] === true) {
+                        continue;
+                      }
+                      if ($lsw == '__BOGUS__') {
+                        ?>
+                        <option value="__BOGUS__" <?= $selected ?>>--Please Select--</option>
+                        <?php
+                      } else {
+                        $has_avail = true; ?>
+                        <option value="<?= $lsw ?>" <?= $selected ?>><?= $lsw ?></option>
+                        <?php
+                      }
+                    }
+                    if (!$has_avail) {
+                      ?>
+                      <option value="__BOGUS__" <?= $selected ?>>--Please Select--</option>
+                      <?php
+                    } ?>
+                  </select>
+                  &nbsp;<a href="#"
+                    onClick='var lsw = document.getElementById("asw<?= $i ?>"); if (lsw.value == "__BOGUS__") { alert("There is no logical switch associated to this device."); return false; } else { window.open("<?= $base ?>/logicsw.php?switch_name=" + lsw.value, "Logical switch " + lsw.value, "height=480,width=1048"); return false; }'><img
+                      src="/images/switch.gif" border="0" title="View logical switch"></a>&nbsp;<a href="#"
+                    onClick='var pros = document.getElementById("pros<?= $row['serial_number'] ?>"); var lsw = document.getElementById("asw<?= $i ?>"); if (pros.value < PROVISION_FAIL) { alert("This switch config has not yet been generated."); return false; } else { window.open("<?= $base ?>/show_config.php?cfg=" + lsw.value + "-config.txt&dname=" + lsw.value, "Config for switch " + lsw.value, "height=650,width=980"); return false; }'><img
+                      src="/images/mag.gif" border="0" title="View switch config"></a>
+                </td>
+                <?php
+                $color = '#FFFFFF';
+                $rtext = 'N/A';
+                $rtitle = 'Not yet assigned'; ?>
+                <td id="psr_<?= $row['serial_number'] ?>" style="background: <?= $color ?>;" title="<?= $rtitle ?>"><input
+                    type="hidden" id="pros<?= $row['serial_number'] ?>" value="<?= $row['provisioned_status'] ?>"><span
+                    style="display: none">
+                    <?= $row['provisioned_status'] ?>
+                  </span>
+                  <?= $rtext ?>
+                </td>
+                <?php
+
+                $color = '#FFFFFF';
+                $rtext = 'N/A';
+                $rtitle = 'Not yet assigned'; ?>
+                <td id="dsr_<?= $row['serial_number'] ?>" style="background: <?= $color ?>;" title="<?= $rtitle ?>"><span
+                    style="display: none">
+                    <?= $row['device_status'] ?>
+                  </span>
+                  <?= $rtext ?>
+                </td>
+              </tr>
+              <?php
+              ++$i;
+            }
             ?>
-              <option value="__BOGUS__" <?=$selected?>>--Please Select--</option>
-<?php
-        } else {
-            $has_avail = true; ?>
-	      <option value="<?=$lsw?>" <?=$selected?>><?=$lsw?></option>
-<?php
-        }
-    }
-    if (!$has_avail) {
-        ?>
-                <option value="__BOGUS__" <?=$selected?>>--Please Select--</option>
-<?php
-    } ?>
-	      </select>
-	      &nbsp;<a href="#" onClick='var lsw = document.getElementById("asw<?=$i?>"); if (lsw.value == "__BOGUS__") { alert("There is no logical switch associated to this device."); return false; } else { window.open("<?=$base?>/logicsw.php?switch_name=" + lsw.value, "Logical switch " + lsw.value, "height=480,width=1048"); return false; }'><img src="/images/switch.gif" border="0" title="View logical switch"></a>&nbsp;<a href="#" onClick='var pros = document.getElementById("pros<?=$row['serial_number']?>"); var lsw = document.getElementById("asw<?=$i?>"); if (pros.value < PROVISION_FAIL) { alert("This switch config has not yet been generated."); return false; } else { window.open("<?=$base?>/show_config.php?cfg=" + lsw.value + "-config.txt&dname=" + lsw.value, "Config for switch " + lsw.value, "height=650,width=980"); return false; }'><img src="/images/mag.gif" border="0" title="View switch config"></a>
-            </td>
-<?php
-    $color = '#FFFFFF';
-    $rtext = 'N/A';
-    $rtitle = 'Not yet assigned'; ?>
-             <td id="psr_<?=$row['serial_number']?>" style="background: <?=$color?>;" title="<?=$rtitle?>"><input type="hidden" id="pros<?=$row['serial_number']?>" value="<?=$row['provisioned_status']?>"><span style="display: none"><?=$row['provisioned_status']?></span><?=$rtext?></td>
-<?php
-
-    $color = '#FFFFFF';
-    $rtext = 'N/A';
-    $rtitle = 'Not yet assigned'; ?>
-            <td id="dsr_<?=$row['serial_number']?>" style="background: <?=$color?>;" title="<?=$rtitle?>"><span style="display: none"><?=$row['device_status']?></span><?=$rtext?></td>
-          </tr>
-<?php
-    ++$i;
-}
-?>
           </tbody>
         </table>
-        </div>
-        <br/>
-        <div class="btable">
+      </div>
+      <br />
+      <div class="btable">
         <table summary="Button Table" width="100%" cellspacing="0">
           <tr>
             <td><input type="reset" value="Reset" name="reset">
-            <input type="submit" value="Submit" name="submit"></td>
+              <input type="submit" value="Submit" name="submit">
+            </td>
           </tr>
         </table>
-        </div>
-      </form>
-    </div>
-  </body>
+      </div>
+    </form>
+  </div>
+</body>
+
 </html>
 <?php
 cleanup();
-?>
+?>

+ 274 - 238
www/logicsw.php

@@ -42,7 +42,7 @@ try {
 } catch (PDOException $e) {
     die($e->getMessage());
 }
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Logical Switches');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Logical Switches');
 if ($logger === false) {
     die("Failed to open logfile.\n");
 }
@@ -98,7 +98,7 @@ if (isset($_REQUEST['submit_top']) || isset($_REQUEST['submit_bottom'])) {
             }
             if (count($errors) == 0) {
                 $made_change = true;
-                @unlink(PORT_TMPL_DIR.'/devices/'."{$sname}-ports.tmpl");
+                @unlink(PORT_TMPL_DIR . '/devices/' . "{$sname}-ports.tmpl");
             }
             continue;
         }
@@ -164,9 +164,9 @@ if (isset($_REQUEST['submit_top']) || isset($_REQUEST['submit_bottom'])) {
             $made_change = true;
             if ($pexp[$sname] != $exp[$sname]) {
                 if ($exp[$sname] != '__BOGUS__') {
-                    @symlink(PORT_PROFILE_DIR.'/'.$exp[$sname], PORT_TMPL_DIR.'/devices/'."{$sname}-ports.tmpl");
+                    @symlink(PORT_PROFILE_DIR . '/' . $exp[$sname], PORT_TMPL_DIR . '/devices/' . "{$sname}-ports.tmpl");
                 } else {
-                    @unlink(PORT_TMPL_DIR.'/devices/'."{$sname}-ports.tmpl");
+                    @unlink(PORT_TMPL_DIR . '/devices/' . "{$sname}-ports.tmpl");
                 }
             }
         }
@@ -188,29 +188,29 @@ if (isset($_REQUEST['submit_top']) || isset($_REQUEST['submit_bottom'])) {
 $wc = '';
 if (isset($_REQUEST['filter'])) {
     switch ($_REQUEST['filter']) {
-    case 'a':
-        $wc = '';
-        break;
-    case 'u':
-        $wc = ' WHERE ip_address IS NULL';
-        break;
-    default:
-        if (preg_match("/^pid:([\w\d-]+)/", $_REQUEST['filter'], $match)) {
-            if (array_search($match[1], $ZTP_PIDS) === false) {
-                $wc = '';
+        case 'a':
+            $wc = '';
+            break;
+        case 'u':
+            $wc = ' WHERE ip_address IS NULL';
+            break;
+        default:
+            if (preg_match("/^pid:([\w\d-]+)/", $_REQUEST['filter'], $match)) {
+                if (array_search($match[1], $ZTP_PIDS) === false) {
+                    $wc = '';
+                } else {
+                    $wc = " WHERE pid = '{$match[1]}'";
+                }
+            } elseif (preg_match("/^mdf:([\w\d-_]+)/", $_REQUEST['filter'], $match)) {
+                if (array_search($match[1], $MDFS) === false) {
+                    $wc = '';
+                } else {
+                    $wc = ", ADDRESSES WHERE SWITCHES.ip_address = ADDRESSES.address AND ADDRESSES.location = '{$match[1]}'";
+                }
             } else {
-                $wc = " WHERE pid = '{$match[1]}'";
-            }
-        } elseif (preg_match("/^mdf:([\w\d-_]+)/", $_REQUEST['filter'], $match)) {
-            if (array_search($match[1], $MDFS) === false) {
                 $wc = '';
-            } else {
-                $wc = ", ADDRESSES WHERE SWITCHES.ip_address = ADDRESSES.address AND ADDRESSES.location = '{$match[1]}'";
             }
-        } else {
-            $wc = '';
-        }
-        break;
+            break;
     }
 }
 
@@ -225,7 +225,7 @@ if (isset($_REQUEST['switch_name'])) {
         exit(1);
     }
 } else {
-    $sql = 'SELECT SWITCHES.* FROM SWITCHES '.$wc.' ORDER BY name';
+    $sql = 'SELECT SWITCHES.* FROM SWITCHES ' . $wc . ' ORDER BY name';
     try {
         $res = $dbh->query($sql);
     } catch (PDOException $e) {
@@ -270,231 +270,267 @@ if (isset($_REQUEST['filter'])) {
     $filter = $_REQUEST['filter'];
 }
 
-print_header(TOOL_NAME.': Logical Switches');
+print_header(TOOL_NAME . ': Logical Switches');
 ?>
-  <body class="flex">
-  <script language="javascript">
-var deletes = 0;
 
-var prop_list = ['location', 'ip_address', 'is_idf', 'pid', 'exception'];
+<body class="flex">
+    <script language="javascript">
+        var deletes = 0;
 
-function refresh() {
-  $.ajax({
-    url: '<?=$base?>/get_logicsw_details.php',
-    dataType: 'json',
-    success: function(data) {
-      $.each(data.response, function(k, v) {
-        $.each(prop_list, function(pi, p) {
-          if (v[p] != $('#prev_' + p + '_' + k).val()) {
-            if ($('#' + p + '_' + k).val() != $('#prev_' + p + '_' + k).val()) {
-              $('#' + p + '_' + k).css({
-                'border-style': 'solid',
-                'border-color': 'red'
-              });
-              $('input').prop('disabled', true);
-              $('select').prop('disabled', true);
-              $('#err_div').html('<p class="error">Conflicting change detected; reload page to continue.</p>');
-              return;
-            } else {
-              $('#prev_' + p + '_' + k).val(v[p]);
-              if ($('#' + p + '_' + k).attr('type') == 'checkbox') {
-                $('#' + p + '_' + k).prop('checked', (v[p] == 1));
-              } else if ($('#' + p + '_' + k).attr('type') == 'select' && v[p] == '') {
-                $('#' + p + '_' + k).val('__BOGUS__');
-              } else {
-                $('#' + p + '_' + k).val(v[p]);
-              }
-            }
-          }
-        });
-      });
-    },
-    complete: function(xhr, message) {
-      setTimeout(refresh, 5000);
-    }
-  });
-}
+        var prop_list = ['location', 'ip_address', 'is_idf', 'pid', 'exception'];
 
-if ( window.history.replaceState ) {
-    window.history.replaceState( null, null, window.location.href );
-}
+        function refresh() {
+            $.ajax({
+                url: '<?= $base ?>/get_logicsw_details.php',
+                dataType: 'json',
+                success: function (data) {
+                    $.each(data.response, function (k, v) {
+                        $.each(prop_list, function (pi, p) {
+                            if (v[p] != $('#prev_' + p + '_' + k).val()) {
+                                if ($('#' + p + '_' + k).val() != $('#prev_' + p + '_' + k).val()) {
+                                    $('#' + p + '_' + k).css({
+                                        'border-style': 'solid',
+                                        'border-color': 'red'
+                                    });
+                                    $('input').prop('disabled', true);
+                                    $('select').prop('disabled', true);
+                                    $('#err_div').html('<p class="error">Conflicting change detected; reload page to continue.</p>');
+                                    return;
+                                } else {
+                                    $('#prev_' + p + '_' + k).val(v[p]);
+                                    if ($('#' + p + '_' + k).attr('type') == 'checkbox') {
+                                        $('#' + p + '_' + k).prop('checked', (v[p] == 1));
+                                    } else if ($('#' + p + '_' + k).attr('type') == 'select' && v[p] == '') {
+                                        $('#' + p + '_' + k).val('__BOGUS__');
+                                    } else {
+                                        $('#' + p + '_' + k).val(v[p]);
+                                    }
+                                }
+                            }
+                        });
+                    });
+                },
+                complete: function (xhr, message) {
+                    setTimeout(refresh, 5000);
+                }
+            });
+        }
+
+        if (window.history.replaceState) {
+            window.history.replaceState(null, null, window.location.href);
+        }
 
-$(document).ready(function() {
-  $('#devtable').DataTable({
-    "scrollY": "400px",
-    "scrollCollapse": true,
-    "paging": false
-  });
-  refresh();
-});
-  </script>
+        $(document).ready(function () {
+            $('#devtable').DataTable({
+                "scrollY": "400px",
+                "scrollCollapse": true,
+                "paging": false
+            });
+            refresh();
+        });
+    </script>
     <div id="headswreg">
-      <div class="apage">
-        <div id="header">
-          <h1><?=TOOL_NAME?>: Logical Switches</h1>
+        <div class="apage">
+            <div id="header">
+                <h1>
+                    <?= TOOL_NAME ?>: Logical Switches
+                </h1>
+            </div>
+            <br />
         </div>
-        <br/>
-      </div>
     </div>
     <div class="apage">
-       <form method="POST" name="search_form" action="<?=$_SERVER['PHP_SELF']?>">
-       <table class="noborder" summary="Filter Table">
-         <tr>
-           <td class="left_act">Show Only Switches In:
-             <select name="filter" onChange="MM_jumpMenu('parent', this, 0)">
-               <option value="<?=$_SERVER['PHP_SELF']?>?filter=a" <?=($filter == 'a') ? 'selected' : ''?>>All</option>
-<?php
-foreach ($MDFS as $m) {
-    ?>
-               <option value="<?=$_SERVER['PHP_SELF']?>?filter=<?=$m?>" <?=($filter == $m) ? 'selected' : ''?>><?=$m?></option>
-<?php
-}
-?>
-               <option value="<?=$_SERVER['PHP_SELF']?>?filter=u" <?=($filter == 'u') ? 'selected' : ''?>>No IP Assigned</option>
-<?php
-foreach ($ZTP_PIDS as $spid) {
-    $selected = ($filter == "pid:$spid") ? 'selected' : ''; ?>
-               <option value="<?=$_SERVER['PHP_SELF']?>?filter=pid:<?=$spid?>" <?=$selected?>><?=$spid?></option>
-<?php
-}
-?>
-           </select></td>
-             <td class="right">Switch Search:
-               <input type="text" size="16" name="switch_name" value="<?=(isset($_REQUEST['switch_name'])) ? $_REQUEST['switch_name'] : ''?>">
-               <input type="image" value="Submit" name="search" src="/images/submit_button.png">
-             </td>
-        </tr>
-      </table>
-      </form>
-      <br/>
-      <table class="noborder" summary="Control Table">
-        <tr>
-          <td class="left"><a href="<?=$base?>/add_logic.php">Add Logical Switch</a> |
-            <a href="<?=$base?>/index.php">Physical Switches</a> |
-            <a href="<?=$base?>/port_profiles.php">Port Profiles</a></td>
-        </tr>
-      </table>
-      <form name="mod_logic_switch_form" method="POST" action="<?=$_SERVER['PHP_SELF']?>" onSubmit='if (deletes > 0) { return confirm("Are you sure you want to delete these " + deletes + " logical switch(es)?"); }'>
-<?php
-    foreach (array_merge($_GET, $_POST) as $name => $value) {
-        if (!is_array($value)) {
-            ?>
-          <input type="hidden" name="<?=$name?>" value="<?=$value?>">
-<?php
-        }
-    }
-?>
-        <div class="fbtable">
-        <table summary="Button Table" width="100%" cellspacing="0">
-          <tr>
-            <td><input type="reset" value="Reset" name="reset">
-            <input type="submit" value="Submit" id="submit_top" name="submit_top"></td>
-          </tr>
+        <form method="POST" name="search_form" action="<?= $_SERVER['PHP_SELF'] ?>">
+            <table class="noborder" summary="Filter Table">
+                <tr>
+                    <td class="left_act">Show Only Switches In:
+                        <select name="filter" onChange="MM_jumpMenu('parent', this, 0)">
+                            <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=a" <?= ($filter == 'a') ? 'selected' : '' ?>>All
+                            </option>
+                            <?php
+                            foreach ($MDFS as $m) {
+                                ?>
+                                <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=<?= $m ?>" <?= ($filter == $m) ? 'selected' : '' ?>><?= $m ?></option>
+                                <?php
+                            }
+                            ?>
+                            <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=u" <?= ($filter == 'u') ? 'selected' : '' ?>>No
+                                IP Assigned</option>
+                            <?php
+                            foreach ($ZTP_PIDS as $spid) {
+                                $selected = ($filter == "pid:$spid") ? 'selected' : ''; ?>
+                                <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=pid:<?= $spid ?>" <?= $selected ?>><?= $spid ?>
+                                </option>
+                                <?php
+                            }
+                            ?>
+                        </select>
+                    </td>
+                    <td class="right">Switch Search:
+                        <input type="text" size="16" name="switch_name"
+                            value="<?= (isset($_REQUEST['switch_name'])) ? $_REQUEST['switch_name'] : '' ?>">
+                        <input type="image" value="Submit" name="search" src="/images/submit_button.png">
+                    </td>
+                </tr>
+            </table>
+        </form>
+        <br />
+        <table class="noborder" summary="Control Table">
+            <tr>
+                <td class="left"><a href="<?= $base ?>/add_logic.php">Add Logical Switch</a> |
+                    <a href="<?= $base ?>/index.php">Physical Switches</a> |
+                    <a href="<?= $base ?>/port_profiles.php">Port Profiles</a>
+                </td>
+            </tr>
         </table>
-        </div>
-        <br/>
-        <div id="err_div" align="center">
-<?php
-foreach ($errors as $error) {
-    ?>
-          <p class="error"><?=$error?></p>
-<?php
-}
-?>
-        </div>
-        <div class="fulltable">
-        <table id="devtable" class="display compact" width="100%" cellspacing="0" summary="Logical Switch Table">
-          <thead>
-          <tr>
-            <th class="headlink">Row No.</th>
-            <th class="headlink">Delete?</th>
-            <th class="headlink">Name</th>
-            <th class="headlink">Is IDF?</th>
-            <th class="headlink">IP Address</th>
-            <th class="headlink">Product ID</th>
-            <th class="headlink">SNMP Location</th>
-            <!--<th class="headlink">Ports Required</th>-->
-            <th class="headlink">Port Profile</th>
-          </tr>
-          </thead>
-          <tbody>
-<?php
-$i = 0;
-foreach ($switches as $row) {
-    $name = $row['name']; ?>
-          <tr>
-            <td><?=$i + 1?>.</td>
-            <td><input type="checkbox" name="delete[<?=$name?>]" value="1" onClick="if (this.checked == true) { deletes++; } else { deletes--; }"></td>
-            <td><?=$name?></td>
-            <td><input type="hidden" id="prev_is_idf_<?=$name?>" name="prev_is_idf[<?=$name?>]" value="<?=$row['is_idf']?>">
-                <input type="checkbox" id="is_idf_<?=$name?>" name="is_idf[<?=$name?>]" value="1" <?=($row['is_idf'] == 1) ? 'checked' : ''?>></td>
-            <td><input type="hidden" id="prev_ip_address_<?=$name?>" name="prev_ip_address[<?=$name?>]" value="<?=$row['ip_address']?>">
-                <input type="text" id="ip_address_<?=$name?>" name="address[<?=$name?>]" size="16" value="<?=$row['ip_address']?>"></td>
-            <td><input type="hidden" id="prev_pid_<?=$name?>" name="prev_pid[<?=$name?>]" value="<?=$row['pid']?>">
-                <select id="pid_<?=$name?>" name="pid[<?=$name?>]">
-<?php
-    $pidarr = array_merge($ZTP_PIDS, array('__BOGUS__'));
-    foreach ($ZTP_PIDS as $p) {
-        $selected = ($row['pid'] == $p) ? 'selected' : '';
-        if ($p == '__BOGUS__') {
-            ?>
-              <option value="__BOGUS__" <?=$selected?>>--Please Select--</option>
-<?php
-        } else {
-            ?>
-              <option value="<?=$p?>" <?=$selected?>><?=$p?></option>
-<?php
-        }
-    } ?>
-            </select></td>
-            <td><input type="hidden" id="prev_location_<?=$name?>" name="prev_location[<?=$name?>]" value="<?=$row['location']?>">
-                <input id="location_<?=$name?>" type="text" name="location[<?=$name?>]" size="32" value="<?=$row['location']?>"></td>
-            <!--<td><?=$row['ports_required']?></td>-->
+        <form name="mod_logic_switch_form" method="POST" action="<?= $_SERVER['PHP_SELF'] ?>"
+            onSubmit='if (deletes > 0) { return confirm("Are you sure you want to delete these " + deletes + " logical switch(es)?"); }'>
             <?php
-            $tbase = '';
-    if (file_exists(PORT_TMPL_DIR.'/devices/'."{$name}-ports.tmpl")) {
-        $targ = readlink(PORT_TMPL_DIR.'/devices/'."{$name}-ports.tmpl");
-        $tbase = basename($targ);
-    } ?>
-            <td><input type="hidden" id="prev_exception_<?=$name?>" name="prev_exception_<?=$name?>" value="<?=$tbase?>">
-              <select id="exception_<?=$name?>" name="exception[<?=$name?>]">
-              <option value="__BOGUS__">--Please Select--</option>
-<?php
-    foreach ($exceptions as $exname => $exarr) {
-        $path = $exarr[1];
-        $expid = $exarr[0];
-        $selected = '';
-        if ($path == $tbase) {
-            $selected = 'selected';
-        }
-        if ($selected == '' && $expid != $row['pid'] && $expid != '__ANY__') {
-            continue;
-        } ?>
-              <option value="<?=$path?>" <?=$selected?>><?=$exname?></option>
-<?php
-    } ?>
-        </select>&nbsp;<a href="#" onClick='var pp = document.getElementById("exception_<?=$name?>"); if (pp.value == "__BOGUS__") { alert("There is no port profile associated to this logical switch."); return false; } else { window.open("<?=$base?>/show_config.php?type=profile&cfg=" + pp.value + "&dname=<?=$name?>", "Config for profile " + pp.value, "height=650,width=980"); return false; }'><img src="/images/mag.gif" border="0" title="View port profile"></td>
-          </tr>
-<?php
-    ++$i;
-}
-?>
-        </tbody>
-        </table>
-        </div>
-        <br/>
-        <div class="fbtable">
-        <table summary="Button Table" width="100%" cellspacing="0">
-          <tr>
-            <td><input type="reset" value="Reset" name="reset">
-            <input id="submit_bottom" type="submit" value="Submit" name="submit_bottom"></td>
-          </tr>
-        </table>
-        </div>
-      </form>
+            foreach (array_merge($_GET, $_POST) as $name => $value) {
+                if (!is_array($value)) {
+                    ?>
+                    <input type="hidden" name="<?= $name ?>" value="<?= $value ?>">
+                    <?php
+                }
+            }
+            ?>
+            <div class="fbtable">
+                <table summary="Button Table" width="100%" cellspacing="0">
+                    <tr>
+                        <td><input type="reset" value="Reset" name="reset">
+                            <input type="submit" value="Submit" id="submit_top" name="submit_top">
+                        </td>
+                    </tr>
+                </table>
+            </div>
+            <br />
+            <div id="err_div" align="center">
+                <?php
+                foreach ($errors as $error) {
+                    ?>
+                    <p class="error">
+                        <?= $error ?>
+                    </p>
+                    <?php
+                }
+                ?>
+            </div>
+            <div class="fulltable">
+                <table id="devtable" class="display compact" width="100%" cellspacing="0"
+                    summary="Logical Switch Table">
+                    <thead>
+                        <tr>
+                            <th class="headlink">Row No.</th>
+                            <th class="headlink">Delete?</th>
+                            <th class="headlink">Name</th>
+                            <th class="headlink">Is IDF?</th>
+                            <th class="headlink">IP Address</th>
+                            <th class="headlink">Product ID</th>
+                            <th class="headlink">SNMP Location</th>
+                            <!--<th class="headlink">Ports Required</th>-->
+                            <th class="headlink">Port Profile</th>
+                        </tr>
+                    </thead>
+                    <tbody>
+                        <?php
+                        $i = 0;
+                        foreach ($switches as $row) {
+                            $name = $row['name']; ?>
+                            <tr>
+                                <td>
+                                    <?= $i + 1 ?>.
+                                </td>
+                                <td><input type="checkbox" name="delete[<?= $name ?>]" value="1"
+                                        onClick="if (this.checked == true) { deletes++; } else { deletes--; }"></td>
+                                <td>
+                                    <?= $name ?>
+                                </td>
+                                <td><input type="hidden" id="prev_is_idf_<?= $name ?>" name="prev_is_idf[<?= $name ?>]"
+                                        value="<?= $row['is_idf'] ?>">
+                                    <input type="checkbox" id="is_idf_<?= $name ?>" name="is_idf[<?= $name ?>]" value="1"
+                                        <?= ($row['is_idf'] == 1) ? 'checked' : '' ?>>
+                                </td>
+                                <td><input type="hidden" id="prev_ip_address_<?= $name ?>" name="prev_ip_address[<?= $name ?>]"
+                                        value="<?= $row['ip_address'] ?>">
+                                    <input type="text" id="ip_address_<?= $name ?>" name="address[<?= $name ?>]" size="16"
+                                        value="<?= $row['ip_address'] ?>">
+                                </td>
+                                <td><input type="hidden" id="prev_pid_<?= $name ?>" name="prev_pid[<?= $name ?>]"
+                                        value="<?= $row['pid'] ?>">
+                                    <select id="pid_<?= $name ?>" name="pid[<?= $name ?>]">
+                                        <?php
+                                        $pidarr = array_merge($ZTP_PIDS, array('__BOGUS__'));
+                                        foreach ($ZTP_PIDS as $p) {
+                                            $selected = ($row['pid'] == $p) ? 'selected' : '';
+                                            if ($p == '__BOGUS__') {
+                                                ?>
+                                                <option value="__BOGUS__" <?= $selected ?>>--Please Select--</option>
+                                                <?php
+                                            } else {
+                                                ?>
+                                                <option value="<?= $p ?>" <?= $selected ?>><?= $p ?></option>
+                                                <?php
+                                            }
+                                        } ?>
+                                    </select>
+                                </td>
+                                <td><input type="hidden" id="prev_location_<?= $name ?>" name="prev_location[<?= $name ?>]"
+                                        value="<?= $row['location'] ?>">
+                                    <input id="location_<?= $name ?>" type="text" name="location[<?= $name ?>]" size="32"
+                                        value="<?= $row['location'] ?>">
+                                </td>
+                                <!--<td><?= $row['ports_required'] ?></td>-->
+                                <?php
+                                $tbase = '';
+                                if (file_exists(PORT_TMPL_DIR . '/devices/' . "{$name}-ports.tmpl")) {
+                                    $targ = readlink(PORT_TMPL_DIR . '/devices/' . "{$name}-ports.tmpl");
+                                    $tbase = basename($targ);
+                                } ?>
+                                <td><input type="hidden" id="prev_exception_<?= $name ?>" name="prev_exception_<?= $name ?>"
+                                        value="<?= $tbase ?>">
+                                    <select id="exception_<?= $name ?>" name="exception[<?= $name ?>]">
+                                        <option value="__BOGUS__">--Please Select--</option>
+                                        <?php
+                                        foreach ($exceptions as $exname => $exarr) {
+                                            $path = $exarr[1];
+                                            $expid = $exarr[0];
+                                            $selected = '';
+                                            if ($path == $tbase) {
+                                                $selected = 'selected';
+                                            }
+                                            if ($selected == '' && $expid != $row['pid'] && $expid != '__ANY__') {
+                                                continue;
+                                            } ?>
+                                            <option value="<?= $path ?>" <?= $selected ?>><?= $exname ?></option>
+                                            <?php
+                                        } ?>
+                                    </select>&nbsp;<a href="#"
+                                        onClick='var pp = document.getElementById("exception_<?= $name ?>"); if (pp.value == "__BOGUS__") { alert("There is no port profile associated to this logical switch."); return false; } else { window.open("<?= $base ?>/show_config.php?type=profile&cfg=" + pp.value + "&dname=<?= $name ?>", "Config for profile " + pp.value, "height=650,width=980"); return false; }'><img
+                                            src="/images/mag.gif" border="0" title="View port profile">
+                                </td>
+                            </tr>
+                            <?php
+                            ++$i;
+                        }
+                        ?>
+                    </tbody>
+                </table>
+            </div>
+            <br />
+            <div class="fbtable">
+                <table summary="Button Table" width="100%" cellspacing="0">
+                    <tr>
+                        <td><input type="reset" value="Reset" name="reset">
+                            <input id="submit_bottom" type="submit" value="Submit" name="submit_bottom">
+                        </td>
+                    </tr>
+                </table>
+            </div>
+        </form>
     </div>
-  </body>
+</body>
+
 </html>
 <?php
 cleanup();
-?>
+?>

+ 158 - 135
www/port_profiles.php

@@ -32,20 +32,20 @@ require_once 'functions.php';
 $dsn = "$db_driver:host=$db_host;dbname=$db_name";
 
 $options = [
-    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
-    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
-    PDO::ATTR_EMULATE_PREPARES => false,
+  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
+  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
+  PDO::ATTR_EMULATE_PREPARES => false,
 ];
 
 try {
-    $dbh = new PDO($dsn, $db_user, $db_pass, $options);
+  $dbh = new PDO($dsn, $db_user, $db_pass, $options);
 } catch (PDOException $e) {
-    die($e->getMessage());
+  die($e->getMessage());
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Port Profiles');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Port Profiles');
 if ($logger === false) {
-    die("Failed to open logfile.\n");
+  die("Failed to open logfile.\n");
 }
 $mask = Log::UPTO(LOG_LEVEL);
 $logger->setMask($mask);
@@ -53,190 +53,213 @@ $logger->setMask($mask);
 $base = get_base($_SERVER['SCRIPT_NAME']);
 $ruser = '<AUTHENTICATION NOT ENABLED>';
 if (isset($_SERVER['REMOTE_USER'])) {
-    $ruser = $_SERVER['REMOTE_USER'];
+  $ruser = $_SERVER['REMOTE_USER'];
 }
 
 $errors = array();
 if (isset($_REQUEST['submit'])) {
-    $d = $_REQUEST['delete'];
-    foreach ($d as $profile => $value) {
-        if ($value == 1) {
-            $sql = "DELETE FROM EXCEPTIONS WHERE name=:name";
-            try {
-                $sth = $dbh->prepare($sql);
-                $sth->execute(['name' => $profile]);
-                $sth->closeCursor();
-                unlink(PORT_PROFILE_DIR."/{$profile}.tmpl");
-                $logger->info("User {$ruser} deleted port profile {$profile}");
-            } catch (PDOException $e) {
-                array_push($errors, "Failed to delete {$profile}: {$e->getMessage()}");
-            }
-        }
+  $d = $_REQUEST['delete'];
+  foreach ($d as $profile => $value) {
+    if ($value == 1) {
+      $sql = "DELETE FROM EXCEPTIONS WHERE name=:name";
+      try {
+        $sth = $dbh->prepare($sql);
+        $sth->execute(['name' => $profile]);
+        $sth->closeCursor();
+        unlink(PORT_PROFILE_DIR . "/{$profile}.tmpl");
+        $logger->info("User {$ruser} deleted port profile {$profile}");
+      } catch (PDOException $e) {
+        array_push($errors, "Failed to delete {$profile}: {$e->getMessage()}");
+      }
     }
+  }
 }
 
 $wc = '';
 $params = null;
 if (isset($_REQUEST['filter'])) {
-    if ($_REQUEST['filter'] != 'All') {
-        $wc = " WHERE pid = :pid";
-        $params = ['pid' => $_REQUEST['filter']];
-    }
+  if ($_REQUEST['filter'] != 'All') {
+    $wc = " WHERE pid = :pid";
+    $params = ['pid' => $_REQUEST['filter']];
+  }
 }
 
-$sql = 'SELECT EXCEPTIONS.* FROM EXCEPTIONS '.$wc.' ORDER BY name';
+$sql = 'SELECT EXCEPTIONS.* FROM EXCEPTIONS ' . $wc . ' ORDER BY name';
 if (isset($_REQUEST['profile_name'])) {
-    $sql = "SELECT * FROM EXCEPTIONS WHERE name LIKE :name ORDER BY name";
-    $params = ['name' => "%{$_REQUEST['profile_name']}%"];
+  $sql = "SELECT * FROM EXCEPTIONS WHERE name LIKE :name ORDER BY name";
+  $params = ['name' => "%{$_REQUEST['profile_name']}%"];
 }
 
 $res = null;
 try {
-    $res = $dbh->prepare($sql);
-    $res->execute($params);
+  $res = $dbh->prepare($sql);
+  $res->execute($params);
 } catch (PDOException $e) {
-    echo "<p><font color=\"red\">Error querying for port profiles: {$e->getMessage()}</font></p>\r\n";
-    exit(1);
+  echo "<p><font color=\"red\">Error querying for port profiles: {$e->getMessage()}</font></p>\r\n";
+  exit(1);
 }
 
 $profiles = array();
 while ($row = $res->fetch()) {
-    array_push($profiles, $row);
+  array_push($profiles, $row);
 }
 
 $filter = '';
 if (isset($_REQUEST['filter'])) {
-    $filter = $_REQUEST['filter'];
+  $filter = $_REQUEST['filter'];
 }
 
-print_header(TOOL_NAME.': Port Profiles');
+print_header(TOOL_NAME . ': Port Profiles');
 ?>
-  <body class="flex">
+
+<body class="flex">
   <script language="javascript">
-var deletes = 0;
-$(document).ready(function() {
-	$('#devtable').DataTable( {
-		"scrollY": "400px",
-		"scrollCollapse": true,
-		"paging":false
-	} );
-} );
+    var deletes = 0;
+    $(document).ready(function () {
+      $('#devtable').DataTable({
+        "scrollY": "400px",
+        "scrollCollapse": true,
+        "paging": false
+      });
+    });
   </script>
-    <div id="headswreg">
-      <div class="apage">
-        <div id="header">
-	  <h1><?=TOOL_NAME?>: Port Profiles</h1>
-        </div>
-        <br/>
+  <div id="headswreg">
+    <div class="apage">
+      <div id="header">
+        <h1>
+          <?= TOOL_NAME ?>: Port Profiles
+        </h1>
       </div>
+      <br />
     </div>
-    <div class="apage">
-       <form method="POST" name="search_form" action="<?=$_SERVER['PHP_SELF']?>">
-       <table class="noborder" summary="Filter Table">
-         <tr>
-           <td class="left_act">Show Only Port Profiles For:
-             <select name="filter" onChange="MM_jumpMenu('parent', this, 0)">
-	     <option value="<?=$_SERVER['PHP_SELF']?>?filter=All" <?=($filter == 'All') ? 'selected' : ''?>>All</option>
-	     <option value="<?=$_SERVER['PHP_SELF']?>?filter=__ANY__" <?=($filter == '__ANY__') ? 'selected' : ''?>>Any Switch</option>
-<?php
-foreach ($ZTP_PIDS as $spid) {
-    $selected = ($filter == "$spid") ? 'selected' : ''; ?>
-               <option value="<?=$_SERVER['PHP_SELF']?>?filter=<?=$spid?>" <?=$selected?>><?=$spid?></option>
-<?php
-
-}
-?>
-             </select>
-           </td>
-             <td class="right">Profile Search:
-	       <input type="text" size="16" name="profile_name" value="<?=(isset($_REQUEST['profile_name'])) ? $_REQUEST['profile_name'] : ''?>">
-               <input type="image" value="Submit" name="search" src="/images/submit_button.png">
-             </td>
-        </tr>
-      </table>
-      </form>
-      <br/>
-      <table class="noborder" summary="Control Table">
+  </div>
+  <div class="apage">
+    <form method="POST" name="search_form" action="<?= $_SERVER['PHP_SELF'] ?>">
+      <table class="noborder" summary="Filter Table">
         <tr>
-	  <td class="left"><a href="<?=$base?>/add_port_profile.php">Add Port Profile</a> |
-	    <a href="<?=$base?>/logicsw.php">Logical Switches</a></td>
+          <td class="left_act">Show Only Port Profiles For:
+            <select name="filter" onChange="MM_jumpMenu('parent', this, 0)">
+              <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=All" <?= ($filter == 'All') ? 'selected' : '' ?>>All</option>
+              <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=__ANY__" <?= ($filter == '__ANY__') ? 'selected' : '' ?>>Any
+                Switch</option>
+              <?php
+              foreach ($ZTP_PIDS as $spid) {
+                $selected = ($filter == "$spid") ? 'selected' : ''; ?>
+                <option value="<?= $_SERVER['PHP_SELF'] ?>?filter=<?= $spid ?>" <?= $selected ?>><?= $spid ?></option>
+                <?php
+
+              }
+              ?>
+            </select>
+          </td>
+          <td class="right">Profile Search:
+            <input type="text" size="16" name="profile_name"
+              value="<?= (isset($_REQUEST['profile_name'])) ? $_REQUEST['profile_name'] : '' ?>">
+            <input type="image" value="Submit" name="search" src="/images/submit_button.png">
+          </td>
         </tr>
       </table>
-      <form name="mod_port_profile_form" method="POST" action="<?=$_SERVER['PHP_SELF']?>" onSubmit='if (deletes > 0) { return confirm("Are you sure you want to delete these port profiles?"); }'>
-<?php
-    foreach (array_merge($_GET, $_POST) as $name => $value) {
+    </form>
+    <br />
+    <table class="noborder" summary="Control Table">
+      <tr>
+        <td class="left"><a href="<?= $base ?>/add_port_profile.php">Add Port Profile</a> |
+          <a href="<?= $base ?>/logicsw.php">Logical Switches</a>
+        </td>
+      </tr>
+    </table>
+    <form name="mod_port_profile_form" method="POST" action="<?= $_SERVER['PHP_SELF'] ?>"
+      onSubmit='if (deletes > 0) { return confirm("Are you sure you want to delete these port profiles?"); }'>
+      <?php
+      foreach (array_merge($_GET, $_POST) as $name => $value) {
         ?>
-          <input type="hidden" name="<?=$name?>" value="<?=$value?>">
-<?php
+        <input type="hidden" name="<?= $name ?>" value="<?= $value ?>">
+        <?php
 
-    }
-?>
+      }
+      ?>
 
-        <div class="fbtable">
+      <div class="fbtable">
         <table summary="Button Table" width="100%" cellspacing="0">
           <tr>
             <td><input type="reset" value="Reset" name="reset">
-            <input type="submit" value="Submit" name="submit"></td>
+              <input type="submit" value="Submit" name="submit">
+            </td>
           </tr>
         </table>
-        </div>
-        <br/>
-        <div align="center">
-<?php
-foreach ($errors as $error) {
-    ?>
-          <p class="error"><?=$error?></p>
-<?php
+      </div>
+      <br />
+      <div align="center">
+        <?php
+        foreach ($errors as $error) {
+          ?>
+          <p class="error">
+            <?= $error ?>
+          </p>
+          <?php
 
-}
-?>
-        </div>
-        <div class="fulltable">
+        }
+        ?>
+      </div>
+      <div class="fulltable">
         <table id="devtable" class="display compact" width="100%" cellspacing="0" summary="Port Profile Table">
           <thead>
-          <tr>
-            <th class="headlink">Row No.</th>
-            <th class="headlink">Delete?</th>
-	          <th class="headlink">Name</th>
-            <th class="headlink">Product ID</th>
-            <th class="headlink">File Name</th>
-            <th class="headlink">View</th>
-          </tr>
+            <tr>
+              <th class="headlink">Row No.</th>
+              <th class="headlink">Delete?</th>
+              <th class="headlink">Name</th>
+              <th class="headlink">Product ID</th>
+              <th class="headlink">File Name</th>
+              <th class="headlink">View</th>
+            </tr>
           </thead>
           <tbody>
-<?php
+            <?php
 
-$i = 0;
-foreach ($profiles as $row) {
-    $name = $row['name']; ?>
-          <tr>
-            <td><?=$i + 1?>.</td>
-            <td><input type="checkbox" name="delete[<?=$name?>]" value="1" onClick="if (this.checked == true) { deletes++; } else { deletes--; }"></td>
-            <td><?=$name?></td>
-	    <td><?=$row['pid']?></td>
-	    <td><?=$row['path']?></td>
-            <td><a href="#" onClick='window.open("<?=$base?>/show_config.php?type=profile&cfg=<?=$row['path']?>&dname=<?=$row['name']?>", "Config for profile <?=$row['name']?>", "height=650,width=980"); return false;'>View</a></td>
-          </tr>
-<?php
-    ++$i;
-}
-?>
-        </tbody>
+            $i = 0;
+            foreach ($profiles as $row) {
+              $name = $row['name']; ?>
+              <tr>
+                <td>
+                  <?= $i + 1 ?>.
+                </td>
+                <td><input type="checkbox" name="delete[<?= $name ?>]" value="1"
+                    onClick="if (this.checked == true) { deletes++; } else { deletes--; }"></td>
+                <td>
+                  <?= $name ?>
+                </td>
+                <td>
+                  <?= $row['pid'] ?>
+                </td>
+                <td>
+                  <?= $row['path'] ?>
+                </td>
+                <td><a href="#"
+                    onClick='window.open("<?= $base ?>/show_config.php?type=profile&cfg=<?= $row['path'] ?>&dname=<?= $row['name'] ?>", "Config for profile <?= $row['name'] ?>", "height=650,width=980"); return false;'>View</a>
+                </td>
+              </tr>
+              <?php
+              ++$i;
+            }
+            ?>
+          </tbody>
         </table>
-        </div>
-        <br/>
-        <div class="fbtable">
+      </div>
+      <br />
+      <div class="fbtable">
         <table width="100%" cellspacing="0" summary="Button Table">
           <tr>
             <td><input type="reset" value="Reset" name="reset">
-            <input type="submit" value="Submit" name="submit"></td>
+              <input type="submit" value="Submit" name="submit">
+            </td>
           </tr>
         </table>
-        </div>
-      </form>
-    </div>
-  </body>
+      </div>
+    </form>
+  </div>
+</body>
+
 </html>
 <?php
 cleanup();
-?>
+?>

+ 35 - 28
www/profile_preview.php

@@ -29,7 +29,7 @@ include_once 'swreg/swreg.inc.php';
 require_once 'Log.php';
 require_once 'functions.php';
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Port Profile Preview');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Port Profile Preview');
 if ($logger === false) {
     die("Failed to open logfile.\n");
 }
@@ -133,43 +133,50 @@ $profile = preg_replace("/\n/", '\\\\n', $profile);
 ?>
 <!DOCTYPE html>
 <html>
-  <head>
-    <title>Port Profile Preview :: <?=$pname?></title>
+
+<head>
+    <title>Port Profile Preview ::
+        <?= $pname ?>
+    </title>
     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
     <script src="codemirror.js"></script>
     <link rel="stylesheet" href="codemirror.css" />
     <link rel="stylesheet" href="midnight.css" />
     <script src="cisco-config.js"></script>
-  </head>
-  <body>
-    <hr/>
-<?php
-if (count($errors) > 0) {
-    foreach ($errors as $error) {
+</head>
+
+<body>
+    <hr />
+    <?php
+    if (count($errors) > 0) {
+        foreach ($errors as $error) {
+            ?>
+            <p style="color: red">
+                <?= $error ?>
+            </p>
+            <?php
+
+        }
+    } else {
         ?>
-    <p style="color: red"><?=$error?></p>
-<?php
+        <script language="Javascript">
+            var profileViewer = CodeMirror(document.body, {
+                value: "<?= $profile ?>",
+                mode: "cisco-config",
+                lineNumbers: true,
+                theme: "midnight",
+                readOnly: true
+            });
+            profileViewer.setSize(null, 600);
+        </script>
+        <?php
 
     }
-} else {
     ?>
-    <script language="Javascript">
-var profileViewer = CodeMirror(document.body, {
-	value       : "<?=$profile?>",
-	mode        : "cisco-config",
-	lineNumbers : true,
-	theme       : "midnight",
-	readOnly    : true
-});
-profileViewer.setSize(null, 600);
-    </script>
-<?php
+    <hr />
+</body>
 
-}
-?>
-    <hr/>
-  </body>
 </html>
 <?php
 cleanup();
-?>
+?>

+ 34 - 29
www/show_config.php

@@ -30,26 +30,26 @@ $cfg = $_GET['cfg'];
 $dname = $_GET['dname'];
 $type = '';
 if (isset($_GET['type'])) {
-    $type = $_GET['type'];
+  $type = $_GET['type'];
 }
 if (!isset($cfg) || !isset($dname)) {
-    die("Error: Configuration file not specified via the cfg parameter or device name not specified with the dname parameter\r\n");
+  die("Error: Configuration file not specified via the cfg parameter or device name not specified with the dname parameter\r\n");
 }
 
 $path = DEVICE_CONFIG_DIR;
 $ext = 'txt';
 if ($type == 'profile') {
-    $path = PORT_PROFILE_DIR;
-    $ext = 'tmpl';
+  $path = PORT_PROFILE_DIR;
+  $ext = 'tmpl';
 }
 
 $basename = basename($cfg);
 if (!preg_match("/\.$ext$/", $basename)) {
-    die("Error: Incorrect file type, $cfg\r\n");
+  die("Error: Incorrect file type, $cfg\r\n");
 }
 $contents = file_get_contents("$path/$basename");
 if (!$contents) {
-    die("Failed to open $path/$basename for reading\r\n");
+  die("Failed to open $path/$basename for reading\r\n");
 }
 
 $contents = preg_replace('/"/', '\\"', $contents);
@@ -59,27 +59,32 @@ $contents = preg_replace("/\n/", '\\\\n', $contents);
 ?>
 <!DOCTYPE html>
 <html>
-  <head>
-    <title>Configuration for <?=$dname?></title>
-    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
-    <script src="codemirror.js"></script>
-    <link rel="stylesheet" href="codemirror.css" />
-    <link rel="stylesheet" href="midnight.css" />
-    <script src="cisco-config.js"></script>
-  </head>
-  <body>
-    <hr/>
-    <script language="Javascript">
-var cfgViewer = CodeMirror(document.body, {
-	value       : "<?=$contents?>",
-	mode        : "cisco-config",
-	lineNumbers : true,
-	theme       : "midnight",
-	readOnly    : true
 
-});
-cfgViewer.setSize(null, 600);
-    </script>
-    <hr/>
-  </body>
-</html>
+<head>
+  <title>Configuration for
+    <?= $dname ?>
+  </title>
+  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
+  <script src="codemirror.js"></script>
+  <link rel="stylesheet" href="codemirror.css" />
+  <link rel="stylesheet" href="midnight.css" />
+  <script src="cisco-config.js"></script>
+</head>
+
+<body>
+  <hr />
+  <script language="Javascript">
+    var cfgViewer = CodeMirror(document.body, {
+      value: "<?= $contents ?>",
+      mode: "cisco-config",
+      lineNumbers: true,
+      theme: "midnight",
+      readOnly: true
+
+    });
+    cfgViewer.setSize(null, 600);
+  </script>
+  <hr />
+</body>
+
+</html>

+ 4 - 4
www/swreg/callhome.php

@@ -44,7 +44,7 @@ try {
     die($e->getMessage());
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Switch Callhome Endpoint');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Switch Callhome Endpoint');
 if ($logger === false) {
     die("Failed to open logfile.\n");
 }
@@ -61,8 +61,8 @@ try {
     $res = $sth->execute(array($sn));
 } catch (PDOException $e) {
     header('Content-type: text/plain');
-    echo "! ERROR: Failed to get switch for SN {$sn}: ".$e->getMessage()."\r\n";
-    $logger->crit("Failed to get switch for SN {$sn}: ".$e->getMessage());
+    echo "! ERROR: Failed to get switch for SN {$sn}: " . $e->getMessage() . "\r\n";
+    $logger->crit("Failed to get switch for SN {$sn}: " . $e->getMessage());
     exit(1);
 }
 
@@ -98,4 +98,4 @@ if ($row['should_re_ztp'] == 2) {
 
 // Send a 404 to prevent unnecessarily writing to flash
 http_response_code(404);
-exit(0);
+exit(0);

+ 2 - 2
www/swreg/pinger.php

@@ -43,7 +43,7 @@ try {
     die($e->getMessage());
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Pinger');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Pinger');
 if ($logger === false) {
     die("Failed to open logfile.\n");
 }
@@ -91,4 +91,4 @@ $sth->closeCursor();
 
 $logger->close();
 
-?>
+?>

+ 12 - 12
www/swreg/swreg.inc.php

@@ -1,27 +1,27 @@
 <?php
 
 //# DO NOT MODIFY
-define('PROVISION_UNKNOWN',     -2);
+define('PROVISION_UNKNOWN', -2);
 define('PROVISION_IN_PROGRESS', -1);
-define('PROVISION_FAIL',         0);
-define('PROVISION_SUCCESS',      1);
+define('PROVISION_FAIL', 0);
+define('PROVISION_SUCCESS', 1);
 
 define('REACHABILITY_NEVER_REACHABLE', 0);
 define('REACHABILITY_NOW_UNREACHABLE', 1);
-define('REACHABILITY_REACHABLE',       2);
+define('REACHABILITY_REACHABLE', 2);
 //# END DO NOT MODIFY
 
 // Globals
 define('LOGFILE', '/var/log/swreg.log');
 define('LOG_LEVEL', 7);
 define('TFTPBOOT', '/tftpboot');
-define('PORT_TMPL_DIR', TFTPBOOT.'/port-templates');
-define('VLAN_TMPL_DIR', TFTPBOOT.'/vlan-templates');
-define('DEVICE_TMPL_DIR', TFTPBOOT.'/device-templates');
-define('DEVICE_CONFIG_DIR', TFTPBOOT.'/device-configs');
-define('DEVICE_TMP_DIR', TFTPBOOT.'/device-tmp');
-define('PORT_PROFILE_DIR', TFTPBOOT.'/port-profiles');
-define('EEM_TMPL_DIR', TFTPBOOT.'/eem-templates');
+define('PORT_TMPL_DIR', TFTPBOOT . '/port-templates');
+define('VLAN_TMPL_DIR', TFTPBOOT . '/vlan-templates');
+define('DEVICE_TMPL_DIR', TFTPBOOT . '/device-templates');
+define('DEVICE_CONFIG_DIR', TFTPBOOT . '/device-configs');
+define('DEVICE_TMP_DIR', TFTPBOOT . '/device-tmp');
+define('PORT_PROFILE_DIR', TFTPBOOT . '/port-profiles');
+define('EEM_TMPL_DIR', TFTPBOOT . '/eem-templates');
 define('FPING_PROGRAM', '/usr/local/sbin/fping');
 define('USE_PNP', true);
 define('EXPORT_PRIME', true);
@@ -233,4 +233,4 @@ $HOOKS = array(
         'UNKNOWN' => '',
         'ERROR' => '',
     ),
-);
+);

+ 44 - 44
www/swreg/swreg.php

@@ -73,7 +73,7 @@ try {
     die($e->getMessage());
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Switch Registrar');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Switch Registrar');
 if ($logger === false) {
     die("Failed to open logfile.\n");
 }
@@ -90,7 +90,7 @@ header('Content-type: text/plain');
 
 if (!isset($pid) || !isset($sn) || !isset($version) || !isset($num_ports)) {
     echo "ERROR: Invalid request!\r\n";
-    $logger->emerg('Invalid request from '.$_SERVER['REMOTE_ADDR']." pid = '$pid', sn = '$sn', version = '$version', num_ports = '$num_ports'");
+    $logger->emerg('Invalid request from ' . $_SERVER['REMOTE_ADDR'] . " pid = '$pid', sn = '$sn', version = '$version', num_ports = '$num_ports'");
     exit(1);
 }
 
@@ -161,9 +161,9 @@ try {
     $sth = $dbh->prepare($sql);
     $res = $sth->execute(array($sn));
 } catch (PDOException $e) {
-    echo 'ERROR: Failed to get switch list: '.$e->getMessage()."\r\n";
-    call_hook('REQUEST:ERROR', array($_SERVER['REMOTE_ADDR'], $sn, $pid, 'Failed to get switch list: '.$e->getMessage()));
-    $logger->crit('Failed to get switch list: '.$e->getMessage());
+    echo 'ERROR: Failed to get switch list: ' . $e->getMessage() . "\r\n";
+    call_hook('REQUEST:ERROR', array($_SERVER['REMOTE_ADDR'], $sn, $pid, 'Failed to get switch list: ' . $e->getMessage()));
+    $logger->crit('Failed to get switch list: ' . $e->getMessage());
     exit(1);
 }
 
@@ -189,19 +189,19 @@ try {
     $sth = $dbh->prepare($sql);
     $res = $sth->execute(array($row['assigned_switch']));
 } catch (PDOException $e) {
-    echo 'ERROR: Failed to get logical switch details: '.$e->getMessage()."\r\n";
-    call_hook('REQUEST:ERROR', array($_SERVER['REMOTE_ADDR'], $sn, $pid, 'Failed to get logical switch details: '.$e->getMessage()));
-    $logger->crit('Failed to get logical switch details: '.$e->getMessage());
+    echo 'ERROR: Failed to get logical switch details: ' . $e->getMessage() . "\r\n";
+    call_hook('REQUEST:ERROR', array($_SERVER['REMOTE_ADDR'], $sn, $pid, 'Failed to get logical switch details: ' . $e->getMessage()));
+    $logger->crit('Failed to get logical switch details: ' . $e->getMessage());
     exit(1);
 }
 
 $row = $sth->fetch();
 $sth->closeCursor();
 call_hook('REQUEST:NEW', array($_SERVER['REMOTE_ADDR'], $row['hostname'], $sn, $pid, $version, $num_ports, $imagef));
-if ($image !== null && !file_exists(TFTPBOOT.'/'.$image)) {
-    echo "ERROR: Image file {$image} does not exist in ".TFTPBOOT."\r\n";
-    call_hook('REQUEST:ERROR', array($_SERVER['REMOTE_ADDR'], $sn, $pid, "Image file {$image} does not exist in ".TFTPBOOT));
-    $logger->crit("Image file {$image} for {$sn}, {$pid} does not exist in ".TFTPBOOT);
+if ($image !== null && !file_exists(TFTPBOOT . '/' . $image)) {
+    echo "ERROR: Image file {$image} does not exist in " . TFTPBOOT . "\r\n";
+    call_hook('REQUEST:ERROR', array($_SERVER['REMOTE_ADDR'], $sn, $pid, "Image file {$image} does not exist in " . TFTPBOOT));
+    $logger->crit("Image file {$image} for {$sn}, {$pid} does not exist in " . TFTPBOOT);
     exit(1);
 }
 $sql = 'UPDATE DEVICE_MAP SET provisioned_status = ? WHERE serial_number = ?';
@@ -218,26 +218,26 @@ try {
 }
 
 $port_contents = "interface range {$port_type}{$start_port} - $max_ports\n";
-if (file_exists(PORT_TMPL_DIR.'/devices/'.$row['hostname'].'-ports.tmpl')) {
-    $port_contents = file_get_contents(PORT_TMPL_DIR.'/devices/'.$row['hostname'].'-ports.tmpl');
-    if (file_exists(PORT_TMPL_DIR.'/device-overrides/'.$row['hostname'].'-ports.tmpl')) {
-        $port_contents .= file_get_contents(PORT_TMPL_DIR.'/device-overrides/'.$row['hostname'].'-ports.tmpl');
+if (file_exists(PORT_TMPL_DIR . '/devices/' . $row['hostname'] . '-ports.tmpl')) {
+    $port_contents = file_get_contents(PORT_TMPL_DIR . '/devices/' . $row['hostname'] . '-ports.tmpl');
+    if (file_exists(PORT_TMPL_DIR . '/device-overrides/' . $row['hostname'] . '-ports.tmpl')) {
+        $port_contents .= file_get_contents(PORT_TMPL_DIR . '/device-overrides/' . $row['hostname'] . '-ports.tmpl');
     }
 } else {
-    if (file_exists(PORT_TMPL_DIR.'/ports.tmpl')) {
-        $port_contents .= file_get_contents(PORT_TMPL_DIR.'/ports.tmpl');
+    if (file_exists(PORT_TMPL_DIR . '/ports.tmpl')) {
+        $port_contents .= file_get_contents(PORT_TMPL_DIR . '/ports.tmpl');
     }
-    if (file_exists(PORT_TMPL_DIR.'/'.$found_pid.'/ports.tmpl')) {
-        $port_contents .= file_get_contents(PORT_TMPL_DIR.'/'.$found_pid.'/ports.tmpl');
+    if (file_exists(PORT_TMPL_DIR . '/' . $found_pid . '/ports.tmpl')) {
+        $port_contents .= file_get_contents(PORT_TMPL_DIR . '/' . $found_pid . '/ports.tmpl');
     }
-    if (file_exists(PORT_TMPL_DIR.'/DYNAMIC/ports.tmpl')) {
-        $port_contents .= file_get_contents(PORT_TMPL_DIR.'/DYNAMIC/ports.tmpl');
+    if (file_exists(PORT_TMPL_DIR . '/DYNAMIC/ports.tmpl')) {
+        $port_contents .= file_get_contents(PORT_TMPL_DIR . '/DYNAMIC/ports.tmpl');
     }
-    if (file_exists(PORT_TMPL_DIR.'/DYNAMIC/'.$found_pid.'/ports.tmpl')) {
-        $port_contents .= file_get_contents(PORT_TMPL_DIR.'/DYNAMIC/'.$found_pid.'/ports.tmpl');
+    if (file_exists(PORT_TMPL_DIR . '/DYNAMIC/' . $found_pid . '/ports.tmpl')) {
+        $port_contents .= file_get_contents(PORT_TMPL_DIR . '/DYNAMIC/' . $found_pid . '/ports.tmpl');
     }
-    if (file_exists(PORT_TMPL_DIR.'/device-overrides/'.$row['hostname'].'-ports.tmpl')) {
-        $port_contents .= file_get_contents(PORT_TMPL_DIR.'/device-overrides/'.$row['hostname'].'-ports.tmpl');
+    if (file_exists(PORT_TMPL_DIR . '/device-overrides/' . $row['hostname'] . '-ports.tmpl')) {
+        $port_contents .= file_get_contents(PORT_TMPL_DIR . '/device-overrides/' . $row['hostname'] . '-ports.tmpl');
     }
 }
 
@@ -254,30 +254,30 @@ if ($row['is_idf'] == 1) {
 }
 
 $contents = '';
-if (file_exists(DEVICE_TMPL_DIR.'/device.tmpl')) {
-    $contents .= file_get_contents(DEVICE_TMPL_DIR.'/device.tmpl');
+if (file_exists(DEVICE_TMPL_DIR . '/device.tmpl')) {
+    $contents .= file_get_contents(DEVICE_TMPL_DIR . '/device.tmpl');
 }
-if (file_exists(DEVICE_TMPL_DIR.'/'.$found_pid.'/device.tmpl')) {
-    $contents .= file_get_contents(DEVICE_TMPL_DIR.'/'.$found_pid.'/device.tmpl');
+if (file_exists(DEVICE_TMPL_DIR . '/' . $found_pid . '/device.tmpl')) {
+    $contents .= file_get_contents(DEVICE_TMPL_DIR . '/' . $found_pid . '/device.tmpl');
 }
-if (file_exists(DEVICE_TMPL_DIR.'/device-overrides/'.$row['hostname'].'-device.tmpl')) {
-    $contents .= file_get_contents(DEVICE_TMPL_DIR.'/device-overrides/'.$row['hostname'].'-device.tmpl');
+if (file_exists(DEVICE_TMPL_DIR . '/device-overrides/' . $row['hostname'] . '-device.tmpl')) {
+    $contents .= file_get_contents(DEVICE_TMPL_DIR . '/device-overrides/' . $row['hostname'] . '-device.tmpl');
 }
 $contents .= "end\n";
 
 $eem_contents = '';
-if (file_exists(EEM_TMPL_DIR.'/eem.tmpl')) {
-    $eem_contents = file_get_contents(EEM_TMPL_DIR.'/eem.tmpl');
+if (file_exists(EEM_TMPL_DIR . '/eem.tmpl')) {
+    $eem_contents = file_get_contents(EEM_TMPL_DIR . '/eem.tmpl');
 }
-if (file_exists(EEM_TMPL_DIR.'/'.$found_pid.'/eem.tmpl')) {
-    $eem_contents .= file_get_contents(EEM_TMPL_DIR.'/'.$found_pid.'/eem.tmpl');
+if (file_exists(EEM_TMPL_DIR . '/' . $found_pid . '/eem.tmpl')) {
+    $eem_contents .= file_get_contents(EEM_TMPL_DIR . '/' . $found_pid . '/eem.tmpl');
 }
-if (file_exists(EEM_TMPL_DIR.'/device-overrides/'.$row['hostname'].'-eem.tmpl')) {
-    $eem_contents .= file_get_contents(EEM_TMPL_DIR.'/device-overrides/'.$row['hostname'].'-eem.tmpl');
+if (file_exists(EEM_TMPL_DIR . '/device-overrides/' . $row['hostname'] . '-eem.tmpl')) {
+    $eem_contents .= file_get_contents(EEM_TMPL_DIR . '/device-overrides/' . $row['hostname'] . '-eem.tmpl');
 }
 $contents = str_replace('%%EEM_CONFIG%%', $eem_contents, $contents);
 
-$vlan_contents = file_get_contents(VLAN_TMPL_DIR.'/'.strtolower($row['location']).'-vlan.tmpl');
+$vlan_contents = file_get_contents(VLAN_TMPL_DIR . '/' . strtolower($row['location']) . '-vlan.tmpl');
 
 $contents = str_replace('%%VLAN_TMPL%%', $vlan_contents, $contents);
 
@@ -315,7 +315,7 @@ if (isset($VLAN_OVERRIDES) && isset($VLAN_OVERRIDES[$row['location']])) {
 foreach ($VLANS as $vn => $vi) {
     $vname = strtoupper($vn);
     $vname = str_replace(' ', '_', $vname);
-    $macro = '%%'.$vname.'_VLAN%%';
+    $macro = '%%' . $vname . '_VLAN%%';
     $contents = str_replace($macro, $vi, $contents);
 }
 
@@ -336,13 +336,13 @@ foreach ($custom_macros as $macro => $mv) {
 }
 
 umask(0022);
-$fd = @fopen(DEVICE_CONFIG_DIR.'/'.$row['hostname'].'-config.txt', 'w');
+$fd = @fopen(DEVICE_CONFIG_DIR . '/' . $row['hostname'] . '-config.txt', 'w');
 fwrite($fd, $contents);
 fclose($fd);
 
-$fd = @fopen(DEVICE_TMP_DIR.'/'.$row['hostname'].'-config.txt', 'w');
+$fd = @fopen(DEVICE_TMP_DIR . '/' . $row['hostname'] . '-config.txt', 'w');
 fclose($fd);
-chmod(DEVICE_TMP_DIR.'/'.$row['hostname'].'-config.txt', 0666);
+chmod(DEVICE_TMP_DIR . '/' . $row['hostname'] . '-config.txt', 0666);
 
 if ($use_pnp) {
     $error = '';
@@ -379,4 +379,4 @@ if ($use_pnp) {
     $logger->info("Successfully provisioned switch $sn ($pid) {$row['hostname']}");
 }
 
-$logger->close();
+$logger->close();

+ 10 - 10
www/swreg/verify.php

@@ -43,7 +43,7 @@ try {
     die($e->getMessage());
 }
 
-$logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Verify Config');
+$logger = Log::singleton('file', LOGFILE, TOOL_NAME . ' : Verify Config');
 if ($logger === false) {
     die("Failed to open logfile.\n");
 }
@@ -59,7 +59,7 @@ header('Content-type: text/plain');
 
 if (!isset($sn)) {
     echo "Invalid request!\r\n";
-    $logger->emerg('Invalid request from '.$_SERVER['REMOTE_ADDR']." config = $config, sn = $sn, md5 = $md5, image = $image");
+    $logger->emerg('Invalid request from ' . $_SERVER['REMOTE_ADDR'] . " config = $config, sn = $sn, md5 = $md5, image = $image");
     exit(1);
 }
 
@@ -70,24 +70,24 @@ $good_config = true;
 $good_image = true;
 
 if (isset($config) && $config != '') {
-    $cmd = escapeshellcmd('/usr/bin/diff '.DEVICE_CONFIG_DIR.'/'.$config.' '.DEVICE_TMP_DIR.'/'.$config);
+    $cmd = escapeshellcmd('/usr/bin/diff ' . DEVICE_CONFIG_DIR . '/' . $config . ' ' . DEVICE_TMP_DIR . '/' . $config);
 
     exec($cmd, $output, $return_var);
 
     if (count($output) > 0 || $return_var != 0) {
         echo "ERROR: Config validation failed\r\n";
-	$out_str = implode("\n", $output);
-	$logger->emerg("Failed to verify config $config for $sn ({$_SERVER['REMOTE_ADDR']}) '$out_str' ($return_var)");
+        $out_str = implode("\n", $output);
+        $logger->emerg("Failed to verify config $config for $sn ({$_SERVER['REMOTE_ADDR']}) '$out_str' ($return_var)");
         call_hook('VERIFY:FAIL', array('config', $_SERVER['REMOTE_ADDR'], $config, $sn, $md5, $image));
         $good_config = false;
     } else {
         $logger->debug("Verified config $config for $sn ({$_SERVER['REMOTE_ADDR']})");
-        @unlink(DEVICE_TMP_DIR.'/'.$config);
+        @unlink(DEVICE_TMP_DIR . '/' . $config);
     }
 }
 
 if (isset($md5) && $md5 != '' && isset($image) && $image != '') {
-    $good_md5 = strtolower(md5_file(TFTPBOOT.'/'.$image));
+    $good_md5 = strtolower(md5_file(TFTPBOOT . '/' . $image));
     $md5 = strtolower($md5);
     if ($md5 != $good_md5) {
         echo "ERROR: Image verification failed\r\n";
@@ -111,9 +111,9 @@ try {
     $sth->execute(array($status, 0, $sn));
     $sth->closeCursor();
 } catch (PDOException $e) {
-    echo 'ERROR: Failed to update switch status: '.$e->getMessage()."\r\n";
-    $logger->crit('Failed to update switch status: '.$e->getMessage());
+    echo 'ERROR: Failed to update switch status: ' . $e->getMessage() . "\r\n";
+    $logger->crit('Failed to update switch status: ' . $e->getMessage());
     exit(1);
 }
 
-$logger->close();
+$logger->close();

+ 1 - 1
www/swreg_creds.inc.php

@@ -12,4 +12,4 @@ define('DNS_PASS', '');
 define('DNS_USER', '');
 define('ZTP_USER', '');
 define('APIC_USER', '');
-define('APIC_PASS', '');
+define('APIC_PASS', '');