<?php
  /**
   * Controller
   *
   * @package Digital Downloads Pro
   * @author wojoscripts.com
   * @copyright 2010
   * @version $Id: controller.php, v2.00 2011-07-10 10:12:05 gewa Exp $
   */
  define("_VALID_PHP", true);
  
  require_once("../init.php");
  if (!$user->is_Admin())
   redirect_to("../login.php");
?>
<?php
  /* == Load Menus == */
  if (isset($_POST['getmenus']))
      : $content->getMenuList();
  endif;

  /* == Proccess Menus == */
  if (isset($_POST['processMenu']))
      : if (intval($_POST['processMenu']) == 0 || empty($_POST['processMenu']))
      : redirect_to("index.php?do=menus");
  endif;
  $core->id = (isset($_POST['id'])) ? $_POST['id'] : 0; 
  $content->processMenu();
  endif;
  
  /* == Sort Menus == */
  if (isset($_POST['sortmenuitems']))
      : $i = 0;
	foreach ($_POST['list'] as $k => $v)
		: $i++;
	$data['position'] = intval($i);
	$db->update("menus", $data, "id='" . (int)$k . "'");
	endforeach;
	print ($db->affected()) ? $core->msgOk('<span>!موفقیت</span>!منوها با موفقیت مرتب شدند') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');
  endif;  

  /* == Delete Menu == */
  if (isset($_POST['deleteMenu']))
      : if (intval($_POST['deleteMenu']) == 0 || empty($_POST['deleteMenu']))
      : redirect_to("index.php?do=menus");
  endif;
  
  $id = intval($_POST['deleteMenu']);
  
  $action = $db->delete("menus", "id='" . $id . "'");
  
  $title = sanitize($_POST['title']);
  print ($action) ? $core->msgOk('<span>!موفقیت</span>Menu <strong>'.$title.'</strong> !حذف با موفقیت انجام شد ') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');   
  endif;
?>
<?php
  /* Get Content Type */
  if (isset($_GET['contenttype']))
      : $type = sanitize($_GET['contenttype']);
  $display = "";
  switch ($type)
      : case "page":
      $sql = "SELECT id, title FROM pages WHERE active = '1' ORDER BY title ASC";
  $result = $db->fetch_all($sql);
  
  $display .= "<select name=\"page_id\" class=\"select\" style=\"width:250px\">";
  if ($result)
      : foreach ($result as $row)
      : $display .= "<option value=\"" . $row['id'] . "\">page.&nbsp;&nbsp;" . $row['title'] . "</option>\n";
  endforeach;
  endif;
  $display .= "</select>\n";
  break;
      
  default:
      $display .= "<input name=\"web\" type=\"text\" class=\"inputbox required\" 
	  value=\"" . post('web') . "\" size=\"45\" />
	  &nbsp;".tooltip("Enter full url starting with http://")."
	  <select name=\"target\" style=\"width:100px\">
          <option value=\"\">--- Target</option>
		  <option value=\"_blank\">_Blank</option>
		  <option value=\"_self\">_Self</option>
        </select>
	  <input name=\"page_id\" type=\"hidden\" value=\"0\" />";
      
      endswitch;
      
      print $display;
      endif;
?>
<?php
  /* == Load Categories == */
  if (isset($_POST['getcategories']))
      : $content->getSortCatList();
  endif;

  /* == Proccess Category == */
  if (isset($_POST['processCategory']))
      : if (intval($_POST['processCategory']) == 0 || empty($_POST['processCategory']))
      : redirect_to("index.php?do=categories");
  endif;
  $core->id = (isset($_POST['id'])) ? $_POST['id'] : 0; 
  $content->processCategory();
  endif;
  
  /* == Sort Category == */
  if (isset($_POST['sortcatitems']))
      : $i = 0;
	foreach ($_POST['list'] as $k => $v)
		: $i++;
	$data['parent_id'] = intval($v);
	$data['position'] = intval($i);
	$db->update("categories", $data, "id='" . (int)$k . "'");
	endforeach;
	print ($db->affected()) ? $core->msgOk('<span>!موفقیت</span>!دسته بندی ها با موفقیت مرتب شدند') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');
  endif;  

  /* == Delete Category == */
  if (isset($_POST['deleteCategory']))
      : if (intval($_POST['deleteCategory']) == 0 || empty($_POST['deleteCategory']))
      : redirect_to("index.php?do=categories");
  endif;
  
  $id = intval($_POST['deleteCategory']);
  
  $action = $db->delete("categories", "id='" . $id . "'");
  $db->delete("categories", "parent_id='" . $id . "'");
  
  $title = sanitize($_POST['title']);
  print ($action) ? $core->msgOk('<span>!موفقیت</span> دسته بندی <strong>'.$title.'</strong> !حذف با موفقیت انجام شد ') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');   
  endif;
?>
<?php
  /* == Proccess Product == */
  if (isset($_POST['processProduct']))
      : if (intval($_POST['processProduct']) == 0 || empty($_POST['processProduct']))
      : redirect_to("index.php?do=gateways");
  endif;
  $item->pid = (isset($_POST['pid'])) ? $_POST['pid'] : 0; 
  $item->processProduct();
  endif;
  
  /* == Delete Product== */
  if (isset($_POST['deleteProduct']))
      : if (intval($_POST['deleteProduct']) == 0 || empty($_POST['deleteProduct']))
      : redirect_to("../index.php?do=products");
  endif;
  
  $id = intval($_POST['deleteProduct']);
  $thumb = getValue("thumb","products","id = '".$id."'");
  @unlink(PRODIMGPATH . $thumb);
  @unlink(PRODIMGPATH . "thumbs/" . $thumb);
  
  $action = $db->delete("products", "id='" . $id . "'");
  $db->delete("comments", "pid='" . $id . "'");
  
  if($getphotos = $db->fetch_all("SELECT thumb FROM photos WHERE pid = '" . $id . "'")):
	  foreach($getphotos as $prow):
		  @unlink(PRODGALPATH . $prow['thumb']);
		  @unlink(PRODGALPATH . "thumbs/" . $prow['thumb']);
	  endforeach;
  endif;

  $db->delete("photos", "pid='" . $id . "'");
  $title = sanitize($_POST['title']);
  print ($action) ? $core->msgOk('<span>!موفقیت</span> محصول <strong>'.$title.'</strong> !حذف با موفقیت انجام شد ') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');
  endif;

  /* == Search Product== */
  if (isset($_POST['productSearch']))
      : $string = sanitize($_POST['productSearch']);
	  $string = $db->escape($string);
  
  if (strlen($string) > 3)
      : $sql = $db->query("SELECT id, title, thumb, body" 
	  . " \n FROM products WHERE title LIKE '%" . $string . "%'" 
	  . " \n ORDER BY id LIMIT 10");
  $display = '';	  
  $display .=  '<div id="searchres">';
  while ($row = $db->fetch($sql))
      : $display .= '<p><a href="index.php?do=products&amp;action=edit&amp;pid='.$row['id'].'">
        <img src="' . PRODIMGURL . 'thumbs/' . $row['thumb'] . '" alt="" width="45" height="45" class="img-wrap2" />';
  
  $name = $row['title'];
  if (strlen($name) > 65)
      $name = sanitize($name,20);
  $display .= '<span class="searchheading">' . $name . '</span>';
  
  $desc = cleanOut($row['body']);
  $description = sanitize($desc ,80);
  
  $display .= '<span class="searchdesc">' . $description . '</span></a></p>';
  endwhile;
  $display .= '<div />';
  print $display;
  endif;
  endif;
?>
<?php
  /* == Proccess File == */
  if (isset($_POST['processFile']))
      : if (intval($_POST['processFile']) == 0 || empty($_POST['processFile']))
      : redirect_to("index.php?do=simple");
  endif;
  $content->processFile();
  endif;
?>
<?php
  /* == Proccess Image == */
  if (isset($_POST['imageUpload']))
      : if (intval($_POST['imageUpload']) == 0 || empty($_POST['imageUpload']))
      : redirect_to("index.php?do=products");
  endif;
  $item->pid = (isset($_POST['pid'])) ? $_POST['pid'] : 0; 
  $item->processGalleryImage();
  endif;

  /* == Load Gallery == */
  if (isset($_POST['loadGallery']))
      : if (intval($_POST['loadGallery']) == 0 || empty($_POST['loadGallery']))
      : redirect_to("index.php?do=products");
  endif;
  $item->pid = (isset($_POST['pid'])) ? $_POST['pid'] : 0; 
  $item->loadGallery();
  endif;
  
  /* == Delete Gallery Image == */
  if (isset($_POST['deleteImage']))
      : if (intval($_POST['deleteImage']) == 0 || empty($_POST['deleteImage']))
      : redirect_to("index.php?do=products");
  endif;
  
  $id = intval($_POST['deleteImage']);
  $thumb = getValue("thumb","photos","id = '".$id."'");
  @unlink(PRODGALPATH . $thumb);
  @unlink(PRODGALPATH . "thumbs/" . $thumb);

  $db->delete("photos", "id='" . $id . "'");
  $title = sanitize($_POST['title']);
  print ($db->affected()) ? $core->msgOk('<span>!موفقیت</span> تصویر <strong>'.$title.'</strong> !حذف با موفقیت انجام شد ') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');
  endif;
  
  /* == Rename Gallery Image == */
  if (isset($_POST['renameImage']))
      : if (intval($_POST['renameImage']) == 0 || empty($_POST['renameImage']))
      : redirect_to("index.php?do=products");
  endif;
  
  $core->id = intval($_POST['renameImage']);
  $item->renameGalleryImage();

  endif;
?>
<?php
  /* == Proccess Configuration == */
  if (isset($_POST['processConfig']))
      : if (isset($_POST['processLogo']))
      : if (!empty($_FILES['logo']['name']))
      : move_uploaded_file($_FILES["logo"]["tmp_name"], UPLOADS . $_FILES["logo"]["name"]);
  print $_FILES['logo']['name'];
  endif;
  elseif (isset($_POST['doconfig']))
      : $core->processConfig();
  endif;
  endif;
?>
<?php
  /* == Proccess Gateway == */
  if (isset($_POST['processGateway']))
      : if (intval($_POST['processGateway']) == 0 || empty($_POST['processGateway']))
      : redirect_to("index.php?do=gateways");
  endif;
  $core->id = (isset($_POST['id'])) ? $_POST['id'] : 0; 
  $content->processGateway();
  endif;
?>
<?php
  /* == Delete SQL Backup == */
  if (isset($_POST['deleteBackup'])) :
  $action = @unlink(BASEPATH . 'admin/backups/'.sanitize($_POST['deleteBackup']));
  
  print ($action) ? $core->msgOk('<span>!موفقیت</span>!نسخه پشتیبان با موفقیت حذف شد') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');
  endif;
?>
<?php
  /* == Proccess Page == */
  if (isset($_POST['processPage']))
      : if (intval($_POST['processPage']) == 0 || empty($_POST['processPage']))
      : redirect_to("index.php?do=pages");
  endif;
  $core->id = (isset($_POST['id'])) ? $_POST['id'] : 0; 
  $content->processPage();
  endif;

  /* == Delete Page == */
  if (isset($_POST['deletePage']))
      : if (intval($_POST['deletePage']) == 0 || empty($_POST['deletePage']))
      : redirect_to("index.php?do=pages");
  endif;
  
  $id = intval($_POST['deletePage']);
  $db->delete("pages", "id='" . $id . "'");
  $title = sanitize($_POST['title']);
  
  print ($db->affected()) ? $core->msgOk('<span>!موفقیت</span>Page <strong>'.$title.'</strong> !حذف با موفقیت انجام شد ') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');
  endif;
?>
<?php
  /* == Proccess F.A.Q == */
  if (isset($_POST['processFaq']))
      : if (intval($_POST['processFaq']) == 0 || empty($_POST['processFaq']))
      : redirect_to("index.php?do=faq");
  endif;
  $core->id = (isset($_POST['id'])) ? $_POST['id'] : 0; 
  $content->processFaq();
  endif;

  /* == Delete F.A.Q == */
  if (isset($_POST['deleteFaq']))
      : if (intval($_POST['deleteFaq']) == 0 || empty($_POST['deleteFaq']))
      : redirect_to("index.php?do=faq");
  endif;
  
  $id = intval($_POST['deleteFaq']);
  $db->delete("faq", "id='" . $id . "'");
  
  print ($db->affected()) ? $core->msgOk('<span>!موفقیت</span>! با موفقیت حذف شد F.A.Q. ') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');
  endif;
  
  /* == Update faq order == */
  if (isset($_GET['sortfaq'])) :

      foreach ($_POST['node'] as $k => $v) :
          $p = $k + 1;
          $data['position'] = $p;
          
          $db->update("faq", $data, "id='" . intval($v) . "'");
      endforeach;
   print ($db->affected()) ? $core->msgOk('<span>!موفقیت</span> !با موفقیت بروز شد F.A.Q. '):  $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');
 endif;
?>
<?php
  /* == Proccess Newsletter == */
  if (isset($_POST['processNewsletter']))
      : if (intval($_POST['processNewsletter']) == 0 || empty($_POST['processNewsletter']))
      : redirect_to("index.php?do=newsletter");
  endif;
  $content->processNewsletter();
  endif;
?>
<?php
  /* == Proccess Email Template == */
  if (isset($_POST['processEmailTemplate']))
      : if (intval($_POST['processEmailTemplate']) == 0 || empty($_POST['processEmailTemplate']))
      : redirect_to("index.php?do=newsletter");
  endif;
  $core->id = (isset($_POST['id'])) ? $_POST['id'] : 0; 
  $content->processEmailTemplate();
  endif;
?>
<?php
  /* == Proccess News == */
  if (isset($_POST['processNews']))
      : if (intval($_POST['processNews']) == 0 || empty($_POST['processNews']))
      : redirect_to("index.php?do=news");
  endif;
  $core->id = (isset($_POST['id'])) ? $_POST['id'] : 0; 
  $content->processNews();
  endif;

  /* == Delete News == */
  if (isset($_POST['deleteNews']))
      : if (intval($_POST['deleteNews']) == 0 || empty($_POST['deleteNews']))
      : redirect_to("index.php?do=news");
  endif;
  
  $id = intval($_POST['deleteNews']);
  $db->delete("news", "id='" . $id . "'");
  $title = sanitize($_POST['title']);
  
  print ($db->affected()) ? $core->msgOk('<span>!موفقیت</span> اخبار <strong>'.$title.'</strong> !حذف با موفقیت انجام شد ') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');
  endif;
?>
<?php
  /* == Proccess Comment Configuration == */
  if (isset($_POST['processCommentConfig'])):
	$content->processCommentConfig();
  endif;

  /* == Proccess Comments == */
  if (isset($_POST['comproccess']) && intval($_POST['comproccess']) == 1) :
  $action = '';
  if (empty($_POST['comid']))
      : $core->msgAlert('<span>Alert!</span>Please select comment(s) to process!');
  endif;

  if (!empty($_POST['comid']))
      : foreach ($_POST['comid'] as $val)
      : $id = intval($val);
	  
  if (isset($_POST['action']) && $_POST['action'] == "disapprove")
      : $data['active'] = 0;
	  $action = '<span>!موفقیت</span>.نظرات انتخاب شده مورد تائید قرار نگرفته است';
  elseif (isset($_POST['action']) && $_POST['action'] == "approve")
      : $data['active'] = 1;
	  $action = '<span>!موفقیت</span>.نظرات انتخاب شده مورد تایید قرار گرفته است';
  endif;
  
  if (isset($_POST['action']) && $_POST['action'] == "delete")
      : $db->delete("comments", "id='".$id."'");
	  $action = '<span>!موفقیت</span>.نظرات انتحاب شده حذف شده اند';
  else
      : $db->update("comments", $data, "id='".$id."'");
  endif;
  
  endforeach;
  
  ($db->affected()) ? $core->msgOk($action) : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');

  endif;

  endif;
?> 
<?php
  /* == Proccess Coupons == */
  if (isset($_POST['processDiscount']))
      : if (intval($_POST['processDiscount']) == 0 || empty($_POST['processDiscount']))
      : redirect_to("index.php?do=coupons");
  endif;
  $core->id = (isset($_POST['id'])) ? $_POST['id'] : 0; 
  $content->processDiscount();
  endif;

  /* == Delete Coupon == */
  if (isset($_POST['deleteNews']))
      : if (intval($_POST['deleteNews']) == 0 || empty($_POST['deleteNews']))
      : redirect_to("index.php?do=news");
  endif;
  
  $id = intval($_POST['deleteDiscount']);
  $db->delete("coupons", "id='" . $id . "'");
  $title = sanitize($_POST['title']);
  
  print ($db->affected()) ? $core->msgOk('<span>!موفقیت</span> کوپن <strong>'.$title.'</strong> !حذف با موفقیت انجام شد ') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');
  endif;
?>
<?php
  /* == Proccess User == */
  if (isset($_POST['processUser']))
      : if (intval($_POST['processUser']) == 0 || empty($_POST['processUser']))
      : redirect_to("index.php?do=users");
  endif;
  $user->userid = (isset($_POST['userid'])) ? $_POST['userid'] : 0; 
  $user->processUser();
  endif;

  /* == Delete User == */
  if (isset($_POST['deleteUser']))
      : if (intval($_POST['deleteUser']) == 0 || empty($_POST['deleteUser']))
      : redirect_to("index.php?do=users");
  endif;
  
  $id = intval($_POST['deleteUser']);
	if($id == 1):
	$core->msgError("<span>!خطـا</span>!شما نمی توانید حساب مدیـر اصلـی را حذف نمائید");
	else:
	$db->delete("users", "id='" . $id . "'");
	
	$username = sanitize($_POST['username']);
	
	print ($db->affected()) ? $core->msgOk('<span>!موفقیت</span> کاربر <strong>'.$username.'</strong> !حذف با موفقیت انجام شد ') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');  
  endif;
  endif;

  /* == User Search == */
  if (isset($_POST['userSearch']))
      : $string = sanitize($_POST['userSearch'],15);
  
  if (strlen($string) > 3)
      : $sql = "SELECT id, username, email, CONCAT(fname,' ',lname) as name" 
	  . "\n FROM users"
	  . "\n WHERE MATCH (username) AGAINST ('" . $db->escape($string) . "*' IN BOOLEAN MODE)"
	  . "\n ORDER BY username LIMIT 10";
  $display = '';
  if($result = $db->fetch_all($sql)):
  $display .= '<ul id="searchresults">';
	foreach($result as $row):
	  $link = 'index.php?do=users&amp;action=edit&amp;userid=' . (int)$row['id'];
	  $display .= '<li><a href="'.$link.'">'.$row['username'].'<small>'.$row['name'].' - '.$row['email'].'</small></a></li>';
	endforeach;
  $display .= '</ul>';
  print $display;
  endif;
  endif;
  endif;

  /* == Check Username == */
  if (isset($_POST['checkUsername'])): 
  
  $username = trim(strtolower($_POST['checkUsername']));
  $username = $db->escape($username);
  
  $sql = "SELECT username FROM users WHERE username = '".$username."' LIMIT 1";
  $result = $db->query($sql);
  $num = $db->numrows($result);
  
  echo $num;
  
  endif;
  
  /* == Get Username == */
  if (isset($_POST["getusername"])): 
   $result = '';
  
  $username = trim($_POST["getusername"]);
  $username = str_replace("%", '', $username);
  $username = sanitize($username, 20);
  $username = $db->escape($username);
  
  $sql = "SELECT id, username, email, CONCAT(fname,' ',lname) as name FROM users WHERE username LIKE '%" . $username . "%' ORDER BY username LIMIT 0,10";
  $userrow = $db->fetch_all($sql);
  
  if (!$userrow): 
  $result = '<p class=\"user-response\"> هیچ نتیجه ایی یافت نشد (<strong>' . $username . '</strong>) !لطفا دوباره سعی کنید .</p>';
  else: 
  foreach ($userrow as $row): 
      $userinfo = $row["id"] . ":" . htmlspecialchars($row["name"].' <strong>('.$row["username"].')</strong> == '.$row["email"]);
	  $result .= "<p class=\"user-response-ok\"><a href=\"javascript:void(0)\" onclick=\"getAccount('$userinfo')\">";
	  $result .= $row["name"].' <strong>('.$row["username"].')</strong> == '.$row["email"];
	  $result .= "</a></p>";
  endforeach;
  endif;
  print cleanOut($result);
  endif;
?>
<?php
  /* == Site Maintenance == */
  if (isset($_POST['processMaintenance']))
      : if (intval($_POST['processMaintenance']) == 0 || empty($_POST['processMaintenance']))
      : redirect_to("index.php?do=maintenance");
  endif;

	if(isset($_POST['inactive'])):
	  $now = date('Y-m-d H:i:s');
	  $diff = intval($_POST['days']);
	  $expire = date("Y-m-d H:i:s", strtotime($now . - $diff . " days"));
	  $db->delete("users","lastlogin < '".$expire."' AND active = 'y' AND userlevel !=9");
	  
	  print ($db->affected()) ? $core->msgOk('<span>!موفقیت</span>All ('.$db->affected().') !کاربر / کاربران، غیر فعال با موفقیت حذف شد ') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد'); 
	  
	elseif(isset($_POST['banned'])):
	$db->delete("users","active = 'b'");
	
	print ($db->affected()) ? $core->msgOk('<span>!موفقیت</span>!همه کاربران توقیف شده با موفقیت حذف شدند') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');  
	
	elseif(isset($_POST['recent'])):
	$action = $db->query("TRUNCATE TABLE recent");
	print ($action) ? $core->msgOk('<span>!موفقیت</span>!تمام موارد بازدید شده اخیر با موفقیت حذف شدند') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');

	elseif(isset($_POST['sitemap'])):
	$content->writeSiteMap();
	
  endif;
  endif;
?>
<?php
  /* == Proccess Transaction == */
  if (isset($_POST['processTransaction']))
      : if (intval($_POST['processTransaction']) == 0 || empty($_POST['processTransaction']))
      : redirect_to("index.php?do=transactions");
  endif;
  $core->id = (isset($_POST['id'])) ? $_POST['id'] : 0;
  $item->processTransaction();
  endif;
  
  /* == Delete Transaction == */
  if (isset($_POST['deleteTransaction']))
      : if (intval($_POST['deleteTransaction']) == 0 || empty($_POST['deleteTransaction']))
      : redirect_to("index.php?do=transactions");
  endif;
  
  $id = intval($_POST['deleteTransaction']);
  $db->delete("payments", "id='" . $id . "'");
  $title = sanitize($_POST['posttitle']);
  
  print ($db->affected()) ? $core->msgOk('<span>!موفقیت</span> تراکنش <strong>'.$title.'</strong> !با موفقیت حذف شد ') : $core->msgAlert('<span>!توجه</span>.چیزی برای پردازش وجود ندارد');
  endif;

  /* == Export Transactions == */
  if (isset($_GET['exportTransactions'])) {
      $sql = "SELECT * FROM transactions";
      $result = $db->query($sql);
      
      $type = "vnd.ms-excel";
	  $date = date('m-d-Y H:i');
	  $title = "Exported from the " . $core->site_name . " on $date";

      header("Pragma: public");
      header("Expires: 0");
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
      header("Content-Type: application/force-download");
      header("Content-Type: application/octet-stream");
      header("Content-Type: application/download");
	  header("Content-Type: application/$type");
      header("Content-Disposition: attachment;filename=temp_" . time() . ".xls");
      header("Content-Transfer-Encoding: binary ");
      
      echo("$title\n");
      $sep = "\t";
      
      for ($i = 0; $i < $db->numfields($result); $i++) {
          echo mysql_field_name($result, $i) . "\t";
      }
      print("\n");
      
      while ($row = $db->fetchrow($result)) {
          $schema_insert = "";
          for ($j = 0; $j < $db->numfields($result); $j++) {
              if (!isset($row[$j]))
                  $schema_insert .= "NULL" . $sep;
              elseif ($row[$j] != "")
                  $schema_insert .= "$row[$j]" . $sep;
              else
                  $schema_insert .= "" . $sep;
          }
          $schema_insert = str_replace($sep . "$", "", $schema_insert);
          $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
          $schema_insert .= "\t";
          print(trim($schema_insert));
          print "\n";
      }
	  exit();
  }
?>