<?php
//*********************************
//ccs 23. Do -export? 220 lines
//*********************************
$doexport = false;
$export_errormsg = '';

if (isset($_REQUEST[ 'export' ]))
  if (is_array($_REQUEST[ 'export' ]))
   if (isset($_REQUEST[ 'export' ][ 'doit' ]) && isset($_REQUEST[ 'export' ][ 'format' ]) && isset($_REQUEST[ 'export' ][ 'limit' ]))
     $doexport = true;

if ($doexport)
  { // Do the export
   // Exporting may take a while
   set_time_limit(0);

   // Initialize export settings
   $exportlimit = abs(intval($_REQUEST[ 'export' ][ 'limit' ]));
   $_SESSION[ 'exportformat' ] = $_REQUEST[ 'export' ][ 'format' ];

   if (! isset($exportformats[ $_SESSION[ 'exportformat' ] ]))
     $_SESSION[ 'exportformat' ] = 'xml';

   // Send Content-type header
   header(sprintf(
            'Content-Type: %s; name="dbexport.%s"'
          , $exportformats[ $_SESSION[ 'exportformat' ] ][ 1 ]
          , $_SESSION[ 'exportformat' ]
                 )
   ) ;
   header(sprintf(
           'Content-disposition: attachment; filename="dbexport.%s"'
         , $_SESSION[ 'exportformat' ]
                 )
   );

   //---------------------------------
   //ccs 23.1 Loop through results
   //---------------------------------
   $ok = false;
   //$cursor = $this->pof_ opencursor($main_sql);
   //if ($cursor) if (ocistatementtype($cursor) == 'SELECT') $ok = true;
   //$res = $db->all($sql, "Get EName", array(array(":id", $empid, -1)));
   if ($cursor = $db->all($sql, "Get main_sql")) $ok = true;   
   if ($ok)
     { // Get column list
      $columns = array();
      $numcols = ocinumcols($cursor);

      for ($j = 1; $j <= $numcols; $j++)
        if (ocicolumnname($cursor, $j) != 'ROWID_')
         $columns[ (ocicolumnname($cursor, $j)) ] = array(
            'type' => ocicolumntype($cursor, $j),
            'size' => ocicolumnsize($cursor, $j)
            );

      //css 23.2 Header
      if ($_SESSION[ 'exportformat' ] == 'xml')
        { echo sprintf('<' . '?xml version="1.0" encoding="%s"?' . '>', $charset) . "\n";
         //echo "<!-- Generated by Oracle Editor.php (http://oracle editor.sourceforge.net/) -->\n";

         $userstr = $_SESSION['cncts'][ 'username' ];
         if ($_SESSION['cncts'][ 'service' ] != '')
           $userstr .= '@' . $_SESSION['cncts'][ 'service' ];

         echo sprintf('<rowset exported="%s" user="%s" server="%s">', 
           date('Y-m-d\TH:i:s'), $userstr, $_SERVER[ 'SERVER_NAME' ]) . "\n";
         echo sprintf("\t<sql>%s</sql>\n", htmlspecialchars($main_sql));

         // Column aliases: We can use column names as tag names only if
         // they're valid XML names - <count(MYFIELD)> won't work.

         $i = 0;
         foreach ($columns as $name => $column)
           { $i++;

            if (preg_match('/^[a-zA-Z][a-zA-Z0-9_-]*$/', $name) == 0)
              $columns[ $name ][ 'alias' ] = 'ALIAS' . $i;
           }

         echo "\t<columns>\n";
         foreach ($columns as $name => $column)
           echo sprintf("\t\t" . '<column name="%s" type="%s" size="%s"%s/>' . "\n",
            htmlspecialchars($name),
            $column[ 'type' ],
            $column[ 'size' ],
            (isset($column[ 'alias' ]) ? ' alias="' . $column[ 'alias' ] . '"' : '')
            );
         echo "\t</columns>\n";
        }
      // css 23.3
      elseif ($_SESSION[ 'exportformat' ] == 'csv')
        { $first = true;

         foreach ($columns as $name => $column)
           if ($name != 'ROWID_')
            { if (! $first) echo ', ';
              echo sprintf('"%s"', str_replace('"', '""', $name));
              $first = false;
            }

         echo "\n";
        }
      // css 23.4
      elseif ($_SESSION[ 'exportformat' ] == 'html')
        { 
?>
         <html>
         <head>
         <meta http-equiv="content-type" content="text/html; charset=<?php echo $charset; ?>">
         <meta name="date" content="<?php echo date('Y-m-d\TH:i:s'); ?>">
         <meta name="generator" content="Oracle tables oop edit based on Tim Strehle's (https://github.com/tistre/oracleeditor/)">
         <title>Editor Oracle tablica - Export tablica</title>
         </head>
         <body>

         <h1>Exported Oracle data</h1>

         <?php
         $userstr = $_SESSION['cncts'][ 'username' ];
         if ($_SESSION['cncts'][ 'service' ] != '')
           $userstr .= '@' . $_SESSION['cncts'][ 'service' ];
         ?>

         <p>Oracle korisnik <em><?php echo htmlspecialchars($userstr); ?></em> 
           exported this data on <em><?php echo date('r'); ?></em>
           by running the following SQL statesment in 
           <a href="http://<?php echo $_SERVER[ 'HTTP_HOST' ]; ?>
                <?php echo $_SERVER[ 'PHP_SELF' ]; ?>">
           a local copy of o raedoop.php</a> on 
             <em><?php echo $_SERVER[ 'SERVER_NAME' ]; ?></em>:<br />
         <pre><?php echo htmlspecialchars($main_sql); ?></pre></p>

         <table border="1">
         <tr>

         <?php

         foreach ($columns as $name => $column)
           echo sprintf('<th>%s<br />(%s, %s)</th>' . "\n",
            htmlspecialchars($name),
            $column[ 'type' ],
            $column[ 'size' ]
            );

         ?>

         </tr>

         <?php
        }

      // Rows

      $i = 1;
      while (true)
        { if (! ocifetchinto($cursor, $row, OCI_ASSOC | OCI_RETURN_LOBS))
           break;
      // css 23.5
         if ($_SESSION[ 'exportformat' ] == 'xml')
           { echo sprintf("\t<row%s>\n", 
            (isset($row[ 'ROWID_' ]) ? (' id="' . htmlspecialchars($row[ 'ROWID_' ]) . '"') : ''));

            foreach ($row as $fieldname => $value)
              if ($fieldname != 'ROWID_')
               echo sprintf("\t\t<%1\$s>%2\$s</%1\$s>\n",
                  (isset($columns[ $fieldname ][ 'alias' ]) 
                 ? $columns[ $fieldname ][ 'alias' ] : $fieldname ),
                  htmlspecialchars($value));
            echo "\t</row>\n";
           }
      // css 23.6
         elseif ($_SESSION[ 'exportformat' ] == 'csv')
           { $first = true;

            foreach ($columns as $fieldname => $column)
              if ($fieldname != 'ROWID_')
               { if (! $first) echo ', ';
                 if (isset($row[ $fieldname ]))
                  echo sprintf('"%s"', str_replace('"', '""', $row[ $fieldname ]));
                 else
                  echo '""';
                 $first = false;
               }

            echo "\n";
           }
      // css 23.7
         elseif ($_SESSION[ 'exportformat' ] == 'html')
           { echo "<tr>\n";

            foreach ($columns as $fieldname => $column)
              if ($fieldname != 'ROWID_')
               { echo "\t<td>";
                 if (isset($row[ $fieldname ]))
                  echo htmlspecialchars($row[ $fieldname ]);
                 echo "</td>\n";
               }

            echo "</tr>\n";
           }

         if (($exportlimit > 0) && ($exportlimit <= ++$i))
           break;
        }

      // Footer
      // css 23.8
      if ($_SESSION[ 'exportformat' ] == 'xml')
        { echo "</rowset>\n";
        }
      elseif ($_SESSION[ 'exportformat' ] == 'html')
        { ?>

         </table>
         <p>HTML generated by <a href="https://github.com/slavkoss/fwphp/tree/master/fwphp/glomodul/oraed">Oracle tables oop edit</a>
           <?php echo $this->pp1->module_version; ?> &copy; 2006 by <a href="https://github.com/slavkoss/fwphp/tree/master/fwphp/glomodul/oraed/">phporacle (Slavko Srakočić)</a>
           &lt;<a href="mailto:tim@strehle.de">slavkoss22@gmail.com</a>&gt;
         </p>
         </body>
         </html>

         <?php
        }

      //$this->pof_closecursor($cursor);

      session_write_close();
      exit;
     }
   else
     $export_errormsg = 'Unable to export';
}
//*********************************
// END-export 220 lines
//*********************************