<?php
  /**
   * Copyright 2011 Zazavi - http://www.zazavi.com
   * Zazavi is free software released under the terms of the GNU General Public License.
   * You should have received a copy of the license.  If not, see <http://www.gnu.org/licenses/>.
   */
  define("_VALID_PHP", true);
  
  require_once("init.php");
  if (!$user->is_Admin())
    redirect_to("login.php");
?>
<?php
  /* Load Menu */
  if (isset($_POST['getmenus']))
      : $content->getSortMenuList();
  endif;
?>
<?php
  /* Sort Menu */
  if (isset($_POST['sortmenuitems']))
      : $i = 0;
	foreach ($_POST['list'] as $k => $v)
		: $i++;
	$data['parent_id'] = intval($v);
	$data['position'] = intval($i);
	$db->update("menus", $data, "id='" . (int)$k . "'");
	endforeach;
	print ($db->affected()) ? $core->msgOk(_MU_SORTED) : $core->msgAlert(_SYSTEM_PROCCESS);
  endif;  
?>
<?php
  /* Delete Menu */
  if (isset($_POST['deleteMenu']))
      : if (intval($_POST['deleteMenu']) == 0 || empty($_POST['deleteMenu']))
      : redirect_to("loader.php?do=menus");
  endif;
  
  $id = intval($_POST['deleteMenu']);
  
  $action = $db->delete("menus", "id='" . $id . "'");
  $db->delete("menus", "parent_id='" . $id . "'");
  
  $title = sanitize($_POST['menutitle']);
  print ($action) ? $zazavisec->writeLog(_MENU .' <strong>'.$title.'</strong> '._DELETED, "", "no", "content") . $core->msgOk(_MENU .' <strong>'.$title.'</strong> '._DELETED) : $core->msgAlert(_SYSTEM_PROCCESS);   
  endif;
?>
<?php
  /* Delete Content Page */
  if (isset($_POST['deletePage']))
      : if (intval($_POST['deletePage']) == 0 || empty($_POST['deletePage']))
      : redirect_to("loader.php?do=pages");
  endif;
  
  $id = intval($_POST['deletePage']);
  $db->delete("pages", "id='" . $id . "'");
  $db->delete("posts", "page_id='" . $id . "'");
  $db->delete("layout", "page_id='" . $id . "'");

  $title = sanitize($_POST['pagetitle']);
  print ($db->affected()) ? $zazavisec->writeLog(_PAGE .' <strong>'.$title.'</strong> '._DELETED, "", "no", "content") . $core->msgOk(_PAGE .' <strong>'.$title.'</strong> '._DELETED) : $core->msgAlert(_SYSTEM_PROCCESS);  
  endif;
?>
<?php
  /* Get Membership List */
  if (isset($_POST['membershiplist'])) :
      if($_POST['membershiplist'] == "Membership"):
	  $memid = getValue("membership_id", "pages", "id='".(int)$_POST['pageid']."'");
	  print $member->getMembersipList($memid);
	  endif; 
  endif;
?>
<?php
  /* Delete Content Post */
  if (isset($_POST['deletePost']))
      : if (intval($_POST['deletePost']) == 0 || empty($_POST['deletePost']))
      : redirect_to("loader.php?do=posts");
  endif;
  
  $id = intval($_POST['deletePost']);
  $db->delete("posts", "id='" . $id . "'");
  $title = sanitize($_POST['posttitle']);
  
  print ($db->affected()) ? $zazavisec->writeLog(_POST .' <strong>'.$title.'</strong> '._DELETED, "", "no", "content") . $core->msgOk(_POST .' <strong>'.$title.'</strong> '._DELETED) : $core->msgAlert(_SYSTEM_PROCCESS);
  endif;
?>
<?php
  /* Delete Module */
  if (isset($_POST['deleteModule']))
      : if (intval($_POST['deleteModule']) == 0 || empty($_POST['deleteModule']))
      : redirect_to("loader.php?do=modules");
  endif;
  
  $id = intval($_POST['deleteModule']);
  $db->delete("modules", "id='" . $id . "'");
  $title = sanitize($_POST['modtitle']);
  
  print ($db->affected()) ? $zazavisec->writeLog(_MODULE .' <strong>'.$title.'</strong> '._DELETED, "", "no", "module") . $core->msgOk(_MODULE .' <strong>'.$title.'</strong> '._DELETED) : $core->msgAlert(_SYSTEM_PROCCESS);  
  endif;
?>
<?php
  /* Delete Membership */
  if (isset($_POST['deleteMembership']))
      : if (intval($_POST['deleteMembership']) == 0 || empty($_POST['deleteMembership']))
      : redirect_to("loader.php?do=memberships");
  endif;
  
  $id = intval($_POST['deleteMembership']);
  $db->delete("memberships", "id='" . $id . "'");
  $title = sanitize($_POST['posttitle']);
  
  print ($db->affected()) ? $zazavisec->writeLog(_MEMBERSHIP .' <strong>'.$title.'</strong> '._DELETED, "", "no", "content") . $core->msgOk(_MEMBERSHIP .' <strong>'.$title.'</strong> '._DELETED) : $core->msgAlert(_SYSTEM_PROCCESS);
  endif;
?>
<?php
  /* Delete Transaction */
  if (isset($_POST['deleteTransaction']))
      : if (intval($_POST['deleteTransaction']) == 0 || empty($_POST['deleteTransaction']))
      : redirect_to("loader.php?do=transactions");
  endif;
  
  $id = intval($_POST['deleteTransaction']);
  $db->delete("payments", "id='" . $id . "'");
  $title = sanitize($_POST['posttitle']);
  
  print ($db->affected()) ? $zazavisec->writeLog(_TRANSACTION .' <strong>'.$title.'</strong> '._DELETED, "", "no", "content") . $core->msgOk(_TRANSACTION .' <strong>'.$title.'</strong> '._DELETED) : $core->msgAlert(_SYSTEM_PROCCESS);
  endif;
?>
<?php
  /* Export Transactions */
  if (isset($_GET['exportTransactions'])) {
      $sql = "SELECT * FROM payments";
      $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();
  }
?>
<?php
  /* Delete User */
  if (isset($_POST['deleteUser']))
      : if (intval($_POST['deleteUser']) == 0 || empty($_POST['deleteUser']))
      : redirect_to("loader.php?do=users");
  endif;
  
  $id = intval($_POST['deleteUser']);
	if($id == 1):
	$core->msgError(_UR_ADMIN_E);
	else:
	$db->delete("users", "id='" . $id . "'");
	
	$username = sanitize($_POST['username']);
	
	print ($db->affected()) ? $zazavisec->writeLog(_USER .' <strong>'.$title.'</strong> '._DELETED, "", "no", "content") . $core->msgOk(_USER .' <strong>'.$username.'</strong> '._DELETED) : $core->msgAlert(_SYSTEM_PROCCESS);  
  endif;
  endif;
?>
<?php
  /* 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 = 'loader.php?do=users&amp;action=edit&amp;uid=' . (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;
?>
<?php
  /* 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;
?>
<?php
  /* Update Post Order */
  if (isset($_GET['sortposts']) && $_GET['sortposts'] == 1) :
      foreach ($_GET['pid'] as $k => $v) :
          $p = $k + 1;
          
          $data['position'] = $p;
          
          $db->update("posts", $data, "id='" . intval($v) . "'");
      endforeach;
 endif;
?>
<?php
  /* Update Sidebar Order */
  if (isset($_GET['sortbars']) && $_GET['sortbars'] == 1) :
      foreach ($_GET['barid'] as $k => $v) :
          $p = $k + 1;
          
          $data['position'] = $p;
          
          $db->update("sidebars", $data, "id='" . intval($v) . "'");
      endforeach;
 endif;
?>
<?php
  /* Get Content Type */
  if (isset($_GET['contenttype']))
      : $type = sanitize($_GET['contenttype']);
  $display = "";
  switch ($type)
      : case "page":
      $sql = "SELECT id, title{$core->dblang} FROM pages WHERE active = '1' ORDER BY title{$core->dblang} ASC";
  $result = $db->fetch_all($sql);
  
  $display .= "<select name=\"page_id\" class=\"select\">";
  if ($result)
      : foreach ($result as $row)
      : $display .= "<option value=\"" . $row['id'] . "\">page.&nbsp;&nbsp;" . $row['title'.$core->dblang] . "</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(_MU_LINK_T)."
	  <select name=\"target\" style=\"width:100px\">
          <option value=\"\">"._MU_TARGET."</option>
		  <option value=\"_blank\">"._MU_TARGET_B."</option>
		  <option value=\"_self\">"._MU_TARGET_S."</option>
        </select>
	  <input name=\"page_id\" type=\"hidden\" value=\"0\" />";
      
      endswitch;
      
      print $display;
      endif;
?>
<?php
  /* Update Layout */
  if (isset($_GET['layout']))
      : $sort = sanitize($_GET['layout']);

  @$sorted = str_replace("list-", "", $_POST[$sort]);
  if ($sorted)
      : foreach ($sorted as $module_id)
      : list($order, $module_id) = explode("|", $module_id);
  $stylename = explode("-", $sort);
  $page_id = $stylename[1];
  if ($stylename[0] == "default")
      //continue;
	  $db->delete("layout", "module_id='" . (int)$module_id . "' AND page_id = '" . (int)$page_id . "'");
  
  $data = array(
		  'module_id' => $module_id, 
		  'page_id' => $page_id, 
		  'place' => $stylename[0], 
		  'position' => $order
  );
  
  if ($stylename[0] != "default") :
  $db->delete("layout", "module_id='" . (int)$module_id . "' AND page_id = '" . (int)$page_id . "'");
  $db->insert("layout", $data);
  endif;
  endforeach;
  endif;
 
  endif;
?>
<?php
  /* Remote Links */
  if (isset($_GET['linktype']) && $_GET['linktype'] == "internal"): 
  $display = "";
  $display .= "<select name=\"content_id\" class=\"inpSel\" id=\"content_id\"onChange=\"updateChooser(this.value);\">";
  $display .= "<option value=\"NA\">"._RL_SELECT."</option>\n";
  
  $sql = $db->query("SELECT id, title{$core->dblang}" 
  . "\n FROM pages" 
  . "\n ORDER BY title{$core->dblang} ASC");
  
  while ($row = $db->fetch($sql))
      : $id = intval($row['id']);
  $title = $row['title'.$core->dblang];
  
  $link = str_replace('http://', '', createPageLink($id));
  $display .= "<option value=\"" . $link . "\">".$title."</option>\n";
  endwhile;
  $display .= "</select>\n";
  echo $display;
  endif;
?>
<?php
  /* Delete Language */
  if (isset($_POST['deleteLanguage'])): 
  $flag_id = sanitize($_POST['deleteLanguage'],2);
  set_time_limit(120);
  $core->deleteLanguage($flag_id);
  endif;
?>
<?php
  /* Delete Statistics */
  if (isset($_POST['deleteStats'])): 
  $action = $db->query("TRUNCATE TABLE stats");
  print ($action) ? $zazavisec->writeLog(_MN_STATS_EMPTY, "", "no", "content") . $core->msgOk(_MN_STATS_EMPTY) : $core->msgAlert(_SYSTEM_PROCCESS);
  endif;
?>
<?php
  /* Delete SQL Backup */
  if (isset($_POST['deleteBackup'])) :
  $action = @unlink(ZAZAVILITE . 'admin/backups/'.sanitize($_POST['deleteBackup']));
  
  print ($action) ? $zazavisec->writeLog(_BK_DELETE_OK, "", "no", "database") . $core->msgOk(_BK_DELETE_OK) : $core->msgAlert(_SYSTEM_PROCCESS);
  endif;
?>
<?php
  /* Delete Logs */
  if (isset($_POST['deleteLogs'])): 
  $action = $db->query("TRUNCATE TABLE log");
  print ($action) ? $zazavisec->writeLog(_LG_STATS_EMPTY, "", "no", "content") . $core->msgOk(_LG_STATS_EMPTY) : $core->msgAlert(_SYSTEM_PROCCESS);
  endif;
?>
<?php
  /* Delete Form*/
  if (isset($_POST['deleteForm']))
      : if (intval($_POST['deleteForm']) == 0 || empty($_POST['deleteForm']))
      : redirect_to("loader.php?do=forms");
  endif;
  
  $id = intval($_POST['deleteForm']);
  $db->delete("forms", "id='" . $id . "'");
  $db->delete("flds", "form_id='" . $id . "'");

  $title = sanitize($_POST['formtitle']);
  print ($db->affected()) ? $core->msgOk('Form <strong>'.$title.'</strong> '._DELETED) : $core->msgAlert(_SYSTEM_PROCCESS);  
  endif;
?>
<?php
  /* Update Field Order */
  if (isset($_GET['sortfields']) && $_GET['sortfields'] == 1) :
      foreach ($_GET['fid'] as $k => $v) :
          $p = $k + 1;
          
          $data['position'] = $p;
          
          $db->update("flds", $data, "id='" . intval($v) . "'");
      endforeach;
 endif;
?>