<?php
/* Include Files ***************************/
require_once('../../db-config.php');
	if(  defined('LTDVERSION') && !isset($_POST['q'] ) )
		die('0|DEMO VERSION!');
require_once('../../inc/lib-compat-class.php');
require_once('../../inc/lib-db-class.php');
require_once('../../inc/lib-login-class.php');
require_once('../../JSON/jsonwrapper_inner.php');
/*******************************************/
global $rSdb;

$user	= new userManagement();
if(  !$user->_logged_in  )
	die(__('Access denied.','recipeshelf'));

if( ! check_ajax_referer('get-user', false) )
	die('0|'.__('Security Alert: Direct access not permitted!','recipeshelf'));


### URL
$rsurl  = curPageURL();

### Clean Up
$q = esc_sql( trim( str_replace('*','',_rem_magic_quote($_POST['q'])) ) );
$u = trim( str_replace('*','',_rem_magic_quote($_POST['u'])) );

### New User Email
$eol	= "\n";
$header = 	'From: '. getGenericFROM() .$eol.
			'MIME-Version: 1.0' .$eol.
			'Content-type: text/plain; charset="utf-8"'.$eol;
$msg 	=	__('A recipeShelf guest account has been created for you @ ','recipeshelf') . $rsurl .$eol.$eol.
            __('Your user name:','recipeshelf') . ' ' . $u . $eol.
            __('Your password:','recipeshelf') . '  ';


### Add or search user
if( $_POST['action'] == 'add' ){

	if(  $user->_readonly  )
		die('|0'.__('Restricted for READ ONLY users.','recipeshelf'));

	$p      = $user->generatePassword(8,4);
    $res	= $user->addNewUser( $u, md5($p),'readonly' );

	if ( $rSdb->affected_rows() > 0 ){

		### Store email
		$useroptions['rS_email'] = sanitize($_POST['e'],false,true);
		$rSdb->update_option( $u."_options",$useroptions );

		### Send PW
		$msg .= $p.$eol;
	    $r = @mail( unsanitize($useroptions['rS_email'], true), __('recipeShelf login information','recipeshelf'), $msg, $header );

		echo '1|'.$useroptions['rS_email'].$r.'|'.__('User added, password is sent by email!','recipeshelf');
		
	} else
		echo '0||'.__('User not added.','recipeshelf');

}else{

	### type: 1=ing, 2=info, 3=unit, 4=email, 5=thought, 6=user
	$sql =  "SELECT object,id FROM {$rSdb->DBobjects} WHERE setting='readonly' AND object LIKE '%{$q}%' GROUP BY object ORDER BY object LIMIT 0,300";
	$entries = $rSdb->fetchArr($sql);

	if ($entries) :
		$arrJSON = array();
		$i=0;
		foreach( $entries as $r ){
			$arrJSON[$i][txt]  = $r->object;
			$arrJSON[$i++][id] = $r->id;
		}

		echo json_encode($arrJSON);
	endif;
	
}
?>