<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  @licence GPL 2005-2010  The osCSS developers - osCSS Open Source E-commerce
  @portion code Copyright (c) 2002 osCommerce
  @package osCSS-2 <www http://www.oscss.org>
  @version 2.0.9
  @date  30/08/10, 10:32
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class adminUsers
*/


class adminUsers
  implements ExtModPage, InterfaceModule {

  /**
    Configuration
  */
  const FILENAME = FILENAME_ADMINUSERS;

  /**
    @param obj
  */
  public static  $mInfo;
  /**
    @param string
  */
  public static $code;
  /**
    @param string
  */
  public static $action;
  /**
    @param array
  */
  public static $list=array();
  /**
    @param string/false
  */
  public static $url_redirect=self::FILENAME;

  /**
    class constructor
  */
  public function __construct() {
    self::$code=__CLASS__;

    include_once(DIR_WS_FUNCTIONS.'password_funcs.php');
  }

  public function check_action($actions){
    global $messageStack,$language;

    self::$action=$actions;
    if(isset($_GET['mID'])) self::$mInfo=self::load_db_values((int)$_GET['mID']);

    switch(self::$action){
    case 'member_new':
        $check_email_query = tep_db_query("select admin_email_address from " . TABLE_ADMIN . "");
        while ($check_email = tep_db_fetch_array($check_email_query)) {
          $stored_email[] = $check_email['admin_email_address'];
        }

        if (in_array($_POST['admin_email_address'], $stored_email)) {
          tep_redirect(tep_href_link(self::FILENAME, 'error=email&action=new_member'));
        } else {

          $makePassword = self::randomize();

          $sql_data_array = array('admin_groups_id' => tep_db_prepare_input($_POST['admin_groups_id']),
                                  'admin_firstname' => tep_db_prepare_input($_POST['admin_firstname']),
                                  'admin_lastname' => tep_db_prepare_input($_POST['admin_lastname']),
                                  'admin_email_address' => tep_db_prepare_input($_POST['admin_email_address']),
                                  'admin_password' => tep_encrypt_password($makePassword),
                                  'admin_created' => 'now()');

          tep_db_perform(TABLE_ADMIN, $sql_data_array);

          $myarray = array(
                           'email_use_html'=>_cst_bool('EMAIL_USE_HTML'),
                          'links'=>HTTP_SERVER . DIR_WS_ADMIN,
                          'admin_firstname'=>$_POST['admin_firstname'],
                          'admin_email_address'=>$_POST['admin_email_address'],
                          'hiddenPassword'=>$makePassword,
                          'message'=>''
                          );
          $message_final=tep_post_prepare_email('admin_members_new.tpl',$language,$myarray);

	  //! envoi a l'user
          tep_mail($_POST['admin_firstname'] , $_POST['admin_email_address'],__('email text subject create account'), $message_final, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
	  //! copy au porp mag
          tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS,__('creat new compte for admin'), $message_final);

          tep_redirect(tep_href_link(self::FILENAME));
        }
        break;
      case 'member_edit':
        $admin_id = tep_db_prepare_input($_POST['admin_id']);
        $hiddenPassword = '-hidden-';
        $stored_email[] = 'NONE';

        $check_email_query = tep_db_query("select admin_email_address from " . TABLE_ADMIN . " where admin_id <> " . $admin_id . "");
        while ($check_email = tep_db_fetch_array($check_email_query)) {
          $stored_email[] = $check_email['admin_email_address'];
        }

        if (in_array($_POST['admin_email_address'], $stored_email)) {
          tep_redirect(tep_href_link(self::FILENAME, 'page=' . $page . 'mID=' . $_GET['mID'] . '&error=email&action=edit_member'));
        } else {
          $sql_data_array = array('admin_groups_id' => tep_db_prepare_input($_POST['admin_groups_id']),
                                  'admin_firstname' => tep_db_prepare_input($_POST['admin_firstname']),
                                  'admin_lastname' => tep_db_prepare_input($_POST['admin_lastname']),
                                  'admin_email_address' => tep_db_prepare_input($_POST['admin_email_address']),
				  'url_openid' => tep_db_prepare_input($_POST['url_openid']),
                                  'admin_modified' => 'now()');

          tep_db_perform(TABLE_ADMIN, $sql_data_array, 'update', 'admin_id = \'' . $admin_id . '\'');

          $myarray = array(
                          'email_use_html'=>_cst_bool('EMAIL_USE_HTML'),
                          'links'=>HTTP_SERVER . DIR_WS_ADMIN,
                          'admin_firstname'=>$_POST['admin_firstname'],
                          'admin_email_address'=>$_POST['admin_email_address'],
			  'url_openid'=>$_POST['url_openid'],
                          'hiddenPassword'=>$hiddenPassword,
                          'message'=>''
                          );
          $message_final=tep_post_prepare_email('admin_members.tpl',$language,$myarray);
          tep_mail($_POST['admin_firstname'] . ' ' . $_POST['admin_lastname'], $_POST['admin_email_address'],__('email text subject'), $message_final);

	  tep_redirect(tep_href_link(self::$url_redirect, 'mID=' . $admin_id));
        }
        break;
      case 'member_delete':
        $admin_id = tep_db_prepare_input($_POST['admin_id']);
        tep_db_query("delete from " . TABLE_ADMIN . " where admin_id = '" . $admin_id . "'");

        tep_redirect(tep_href_link(self::FILENAME, 'page=' . $page));
        break;

        case 'setflag':

          if($_GET['gPath']==1)  tep_redirect(tep_href_link(self::FILENAME, 'gPath=' . $_GET['gPath'] .'&action=define_group'));
          if(isset($_GET['admin_boxes_id'])) {
            $ID=$_GET['admin_boxes_id'].'.php';
            $key='admin_files_name';
            $where= " and admin_files_is_boxes='1' ";
          } else {
            $ID=$_GET['admin_files_id'];
            $key='admin_files_id';
            $where=" and admin_files_is_boxes='0' ";
          }

            $define_files_query = tep_db_query($sql="select * from " . TABLE_ADMIN_FILES . " where ".$key."='".$ID."' ".$where." LIMIT 1");
            $define_files = tep_db_fetch_array($define_files_query);


        $t=explode(',',$define_files['admin_groups_id']);

        if($_GET['flag'] ==0) {
          foreach($t as $v){
            if($_GET['gPath'] != $v && !empty($v) )$ts[]=$v;
          }
        }
        elseif(!in_array($_GET['gPath'] ,$t)) {
          $ts=$t;
          $ts[]=$_GET['gPath'];
        }else $ts=$t;

        $define_files_query = tep_db_query($sql="update " . TABLE_ADMIN_FILES . " set admin_groups_id = '".implode(',',$ts)."' where admin_files_id='".$define_files['admin_files_id']."'");

          tep_redirect(tep_href_link(self::FILENAME, 'gPath=' . $_GET['gPath'] .'&action=define_group'));
        break;
	default:




    }

  }

  public function get_header(){
    if(in_array(self::$action,array('new','edit','new_member')) ) :
      tep_include_file (DIR_WS_TEMPLATE."jquery.validate.css",true);
      tep_include_file ("includes/javascript/jquery.validate.min.js",true);
    ?>
    <script type="text/javascript">
      $(function(){
	// validate signup form on keyup and submit
	$("#newmember").validate({
	  rules: {
	    admin_firstname: {
	      required: true,
	      minlength: 3
	    },
	    admin_lastname: {
	      required: true,
	      minlength: 3
	    },
	    admin_email_address: {
	      required: true,
	      email: true
	    },
	    admin_groups_id:{
	      required: true,
	      minlength: 1
	    }
	  },
	  messages: {
	    admin_firstname: {
	      required: " <?php echo addslashes(__('js alert firstname')) ?>",
	      minlength: " <?php echo addslashes(__('your firstname must consist of at least 3 characters')) ?>"
	    },
	    admin_lastname: {
	      required: " <?php echo addslashes(__('js alert lastname')) ?>",
	      minlength: " <?php echo addslashes(__('your lastname must consist of at least 3 characters')) ?>"
	    },
	    admin_email_address: " <?php echo addslashes(__('js alert email')) ?>",
	    admin_groups_id: " <?php echo addslashes(__('please enter groupe id')) ?>"
	  },
	  errorElement: "span",
	  errorPlacement: function(error, element) {
	    error.appendTo( element.parent());
	  },
	  onkeyup: true
	});
      });
    </script>
    <?php endif;
  }


  public static function load_db_values($ID){
    $DB=Database::getInstance();
    $db_admin_query_raw = $DB->query($sql="select * from " . TABLE_ADMIN . " a LEFT JOIN " . TABLE_ADMIN_GROUPS . " g ON a.admin_groups_id=g.admin_groups_id where a.admin_id='".$ID."' ");
    return new objectInfo($db_admin_query_raw->fetchAssoc());
  }


  public function display_view(){
    switch(self::$action){
      default:
	self::tep_get_list();
	return tep_get_include_contents(__CLASS__.'.listing');
    }
  }


  public static function get_right_bar(){
    global $language;
      $heading = array();
      $contents = array();
      $DB=Database::getInstance();

      switch (self::$action) {
	case 'new_member':
	$groups_array = array(array('id' => '0', 'text' => __('text none')));
	$groups_query = tep_db_query("select admin_groups_id, admin_groups_name from " . TABLE_ADMIN_GROUPS);
	while ($groups = tep_db_fetch_array($groups_query)) {
	    $groups_array[] = array('id' => $groups['admin_groups_id'],
				    'text' => $groups['admin_groups_name']);
	}

	$heading[] = array('text' => __('text info heading new') );

	$contents = array('form' => tep_draw_form('newmember', self::FILENAME, 'action=member_new', 'post', '', ' name="newmember"'));

	if (isset($_GET['error'])) { $contents[] = array('text' => __('text info error email used')); }

	$contents[] = array('class' => 'block_input','text' => '<label for="admin_firstname">' . __('text info firstname') . '</label>' . tep_draw_input_field('admin_firstname','','','',true));
	$contents[] = array('class' => 'block_input','text' => '<label for="admin_lastname">' . __('text info lastname') . '</label>' . tep_draw_input_field('admin_lastname','','','',true));
	$contents[] = array('class' => 'block_input','text' => '<label for="admin_email_address">' . __('text info email') . '</label>' . tep_draw_input_field('admin_email_address','','','',true));

	$contents[] = array('class' => 'block_input','text' => '<label for="admin_groups_id">' . __('text info group') . '</label>' . tep_draw_pull_down_menu('admin_groups_id', $groups_array, '0'));

	$contents[] = array('class' => 'button_nav','text' => tep_image_submit('button_insert.gif', IMAGE_INSERT) . ' <a class="button"  href="' . tep_href_link(self::FILENAME) . '">' . IMAGE_CANCEL . '</a>');
	break;
      case 'edit_member':
	$heading[] = array('text' => __('text info heading new') );

	$contents = array('form' => tep_draw_form('newmember', self::$url_redirect, 'action=member_edit&amp;mID=' . self::$mInfo->admin_id, 'post', '', ' name="newmember"'));
	if (isset($_GET['error'])) {
	$contents[] = array('text' => __('text info error'));
	}
	$contents[] = array('class' => 'block_input','text' => '<label for="admin_firstname">' . __('text info firstname') . '</label>' . tep_draw_input_field('admin_firstname','', self::$mInfo->admin_firstname) . tep_draw_hidden_field('admin_id', '', self::$mInfo->admin_id));
	$contents[] = array('class' => 'block_input','text' => '<label for="admin_lastname">' . __('text info lastname') . '</label>' . tep_draw_input_field('admin_lastname','', self::$mInfo->admin_lastname));
	$contents[] = array('class' => 'block_input','text' => '<label for="admin_email_address">' . __('text info email') . '</label>' . tep_draw_input_field('admin_email_address','', self::$mInfo->admin_email_address));
	$contents[] = array('class' => 'block_input','text' => '<label for="url_openid">' . __('text info url_openid') . '</label>' . tep_draw_input_field('url_openid','', self::$mInfo->url_openid));
	if (self::$mInfo->admin_id == 1) {
	  $contents[] = array('class' => 'block_input','text' => tep_draw_hidden_field('admin_groups_id', '', self::$mInfo->admin_groups_id));
	} else {
	  $groups_array = array(array('id' => '0','class' => 'block_input', 'text' => __('text none')));
	  $groups_query = tep_db_query("select admin_groups_id, admin_groups_name from " . TABLE_ADMIN_GROUPS);
	  while ($groups = tep_db_fetch_array($groups_query)) {
	    $groups_array[] = array('id' => $groups['admin_groups_id'],'class' => 'block_input','text' => $groups['admin_groups_name']);
	  }
	  $contents[] = array('class' => 'block_input','text' => '<label for="admin_groups_id">' . __('text info group') . '</label>' . tep_draw_pull_down_menu('admin_groups_id', $groups_array, self::$mInfo->admin_groups_id));
	}

	$contents[] = array('class' => 'button_nav','text' => tep_image_submit('button_insert.gif', IMAGE_UPDATE, 'onclick="validateForm();return document.returnValue"') . ' <a  class="button" href="' . tep_href_link(self::$url_redirect, 'mID=' .  self::$mInfo->admin_id) . '">' .  IMAGE_CANCEL . '</a>');
      break;

      case 'del_member':
	$heading[] = array('text' => __('text info heading delete') );
	if (self::$mInfo->admin_id == 1 || self::$mInfo->admin_email_address == STORE_OWNER_EMAIL_ADDRESS) {
	  $contents[] = array('class' => 'button_nav','text' => '<a class="button" href="' . tep_href_link(self::FILENAME, 'mID=' . self::$mInfo->admin_id) . '">' .  IMAGE_BACK . '</a>');
	} else {
	  $contents = array('form' => tep_draw_form('edit', self::FILENAME, 'action=member_delete&amp;mID=' . self::$mInfo->admin_id, 'post', 'enctype="multipart/form-data"'));
	  $contents[] = array('text' => sprintf(__('text info delete intro'), self::$mInfo->admin_firstname . ' ' . self::$mInfo->admin_lastname) . tep_draw_hidden_field('admin_id', '', self::$mInfo->admin_id));
	  $contents[] = array('class' => 'button_nav', 'text' => tep_image_submit('button_delete.gif', IMAGE_DELETE) . ' <a  class="button"  href="' . tep_href_link(self::FILENAME, 'mID=' . self::$mInfo->admin_id) . '">' . IMAGE_CANCEL . '</a>');
	}
	break;

      default:
	if (isset(self::$mInfo) && is_object(self::$mInfo)) {
	  $heading[] = array('text' => __('text info heading default') );
	  $contents[] = array('text' => '<strong>' . __('text info fullname') . '</strong>' . self::$mInfo->admin_firstname . ' ' . self::$mInfo->admin_lastname);
	  $contents[] = array('text' => '<strong>' . __('text info email') . '</strong>' . self::$mInfo->admin_email_address);
	  $contents[] = array('text' => '<strong>' . __('text info group') . '</strong>' . self::$mInfo->admin_groups_name);
	  $contents[] = array('text' => '<strong>' . __('text info created') . '</strong>' . self::$mInfo->admin_created);
	  $contents[] = array('text' => '<strong>' . __('text info modified') . '</strong>' . self::$mInfo->admin_modified);
	  $contents[] = array('text' => '<strong>' . __('text info logdate') . '</strong>' . self::$mInfo->admin_logdate);
	  $contents[] = array('text' => '<strong>' . __('text info lognum') . '</strong>' . self::$mInfo->admin_lognum);
	}
      }

      if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {
	$box = new box;
	return $box->infoBox($heading, $contents);
      }
  }


/** Interne module */



  public static function tep_get_modele(){
    return array( 'admin_groups_name',
// 		  'level',
		);
  }

  public static function tep_get_list($page=1,$rowbyp=10,$sOrder='',$sWhere='',$options=''){
    global $query_numrows;

    $DB=Database::getInstance();

      $_query = "select * from " . TABLE_ADMIN .  " ".$sWhere." order by ".(!empty($sOrder)?" ".$sOrder : "admin_firstname");

      $categories_split = new splitPageResults($page, $rowbyp, $_query,$query_numrows);

      $pq=$DB->query($_query);

      $list=array();
      while ($admin = $pq->fetchAssoc()) {
	if ($admin['admin_groups_id']==0) $admin['admin_groups_id']=1;
	$admin_group_query = $DB->query($sql="select admin_groups_name from " . TABLE_ADMIN_GROUPS . " where admin_groups_id = '" . $admin['admin_groups_id'] . "' " );
	$admin_group = $admin_group_query->fetchAssoc();
	$admin=array_merge($admin, $admin_group);

	self::$list[]=$admin;

      }


    $li=$res=array();
    foreach(self::$list as $item){
      foreach(self::tep_get_modele() as $k) $li[$k]=(string)$item[$k];
      $res[]=$li;
    }

    return $res;
  }

/** Interface module */

  function check() { return false; }
  function install() { return false; }
  function remove() { return false;  }
  function keys() { return false; }



/** Private specific module */
  private static function randomize() {
    $salt = "abchefghjkmnpqrstuvwxyz0123456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass='';
    while ($i <= 7) {
	$num = rand() % 33;
	$tmp = substr($salt, $num, 1);
	$pass = $pass . $tmp;
	$i++;
    }
    return $pass;
  }
}

?>