Location: PHPKode > projects > PhpProjectMaster > www/php/users.php
<?php
/* 
 Users management
 (c) 2004-2007 by "Oleg Savchuk" <hide@address.com>

 part of phpProjectMaster project
 http://phpprojmaster.sourceforge.net

 The contents of this file are subject to the GNU GENERAL PUBLIC LICENSE
 http://www.gnu.org/copyleft/gpl.html

*/

 session_start();
 require_once "../inc/sitelib.php" ;
 require_once "../inc/form_utils.php" ;
 require_once "../inc/user.php" ;

 check_access(100);
 global_init();

//********* variables
 $this_tpl_dir  = '/admin/users';

//********* action!
 $CGI_ACTIONS=array(
  ''           => 'show_item_list',
  'AddNew'     => 'show_one_item',
  'Edit'       => 'show_one_item',
  'SaveRec'    => 'save_one_item',
  'DelRec'     => 'delete_item',

  'SendPwd'    => 'send_password',
  'Export'     => 'export_csv',
  'ShowBroadcast'   => 'show_broadcast',
  'SaveBroadcast'   => 'save_broadcast',
  'PreviewBroadcast'=> 'preview_broadcast',
  'SendBroadcast'   => 'send_broadcast',

  'Import'     => 'show_import',
  'DoImport'   => 'do_import',
 );

 go_action();

 exit;

//***************************
function show_item_list(){
 global $green_msg, $err_msg, $rowcolor, $root_url, $MAX_PAGE_ITEMS, $this_tpl_dir;
 $page=$_REQUEST['page']+0;
 $search_str=$_REQUEST['s'];

 $where=" status<>127 ";
 if ($search_str){
    $where.=" and (fname like '%$search_str%' 
            or lname like '%$search_str%' 
            or email like '%$search_str%' 
    )";
 }

 $sql="select count(*) ctr from users where $where";
 $sth=db_query($sql);
 $row=mysql_fetch_assoc($sth);
 $total_items=$row['ctr'];

 $page_offset=$page*$MAX_PAGE_ITEMS;
 $total_pages=(int)($total_items/$MAX_PAGE_ITEMS+0.999999);

 //get list of items
 $cdr=array();
 $sql="select * 
  from users 
 where $where 
 order by fname, lname
 LIMIT $page_offset, $MAX_PAGE_ITEMS 
 ";
 $sth=db_query($sql);
 while($row=mysql_fetch_assoc($sth)){
    $rowcolor=array_reverse($rowcolor);

    $cdr[]=array_merge($row,array(
        'bgcolor' => $rowcolor[0],
      ));
 }

 $list_nav='';
 if ($total_items>$MAX_PAGE_ITEMS){
    $list_nav=make_List_Navigation($page, $total_items, $MAX_PAGE_ITEMS, "$root_url/php/users.php?s=".urlencode($search_str)."&page=", '', 'showall');
 }

 $ps=array(
   'item_datarow' => $cdr,
   'list_navigation' => $list_nav,
   'search_str'      => $search_str,
 );
 $ps=array_merge($ps, get_userinfo());
 parse_page("$this_tpl_dir/list", $GLOBALS['PAGE_TPL_ADMIN'], $ps);
}

//***************************
//if $forceform=1 - redisplay values from FORM, not DB
function show_one_item($forceform=0){
 global $green_msg, $err_msg, $this_tpl_dir;
 $hITEMDB=array();

 $hITEM=$_REQUEST['item'];
 if (!$hITEM){  //if not set - this is initial form call - we can make here initializations

 }

 $item_id=$_REQUEST['id']+0;
 $hITEM['u_id']=$item_id;
 if ($item_id){ #edit mode
    $hITEMDB=get_user($item_id);
 }

 if ($forceform){
    $hITEM=array_merge($hITEMDB,$hITEM); //if redisplay from the FORM - merge with DB record, so read-only fields will be displayed too
 }else{
    if ($item_id){//only if Edit mode
       $hITEM=&$hITEMDB;  //making $hITEM same as $hITEMDB (no array copy)
    }
 }

 $ps=array(
   'access_level_select' => get_select_accesslevel($hITEM['access_level']),
 );
 $ps=array_merge($ps, $hITEM);
 $ps=array_merge($ps, get_userinfo());
 parse_page("$this_tpl_dir/edit", $GLOBALS['PAGE_TPL_ADMIN'], $ps);
}

//*************************** save item info
function save_one_item(){
 global $green_msg, $err_msg;
 $item_id=$_REQUEST['id']+0;

 if (validate_item($item_id, $_REQUEST['item'])){
    $hITEM=get_user($item_id);

    //make some adjustments
    $IFORM=form2dbhash($_REQUEST['item'], 'fname lname email pwd access_level status');

    if ($item_id){  //id exists - update record
       if (!$IFORM['pwd']) unset($IFORM['pwd']);

       $sql="update users set ".get_sqlupdate_set($IFORM)." where u_id=$item_id";
//       logger($sql);
       db_query($sql);
   
       $green_msg="Member [".$IFORM['email']."] has been modified";
    } else {     //id not exits - insert record

       $sql="insert into users ".get_sqlinsert_set($IFORM,', add_time',', now()');
//       logger($sql);
       $sth=db_query($sql);
       $item_id=get_identity();
   
       $green_msg="New Member [".$IFORM['email']."] has been added";
    }
    $_REQUEST['id']=$item_id;

    show_one_item();
 } else {
    if ($item_id){
       show_one_item(1);
    } else {
       show_one_item();
    }
 }

}

//################# Validate item form values in IFORM
function validate_item($item_id=0, $IFORM){
 global $err_msg;

 $REQFLD=array(
//'nick'    => array('Nick'),
'email'   => array('Email'),
);

 if (!$item_id) $REQFLD['pwd']=array('Password');

 //VALIDATE REQUIRED FIELDS
 if (!$err_msg) { $err_msg=validate_form($IFORM, $REQFLD); }

 //VALIDATE if field unique
 if (!$err_msg && is_dbrecord_exists2('users', 'email', $IFORM['email'], " and status<>127 and u_id<>$item_id") ){
    $err_msg="Such Email already exists. Please, select another name.";
 }
// if (!$err_msg && is_dbrecord_exists2('users', 'nick', $IFORM['nick'], " and u_id<>$item_id") ){
//    $err_msg="Such Nickname already registered. Please, login as a member or select another Nickname.";
// }

 if ($err_msg) { return 0 ;}
 return 1;
}

//************************
function delete_item(){
 $item_id=$_REQUEST['id']+0;

 delete_user($item_id);

 show_item_list();
}

//************************
function send_password(){
 global $green_msg, $root_domain;

 $item_id=$_REQUEST['id']+0;

 $IFORM=get_user($item_id);
 $IFORM['ROOT_DOMAIN']=$root_domain;
 $msg_body=parse_page("/emails", 'email_pwd.txt', $IFORM, 'v');
 list($msg_subj, $msg_body)=email2subj_body($msg_body);

 send_email($IFORM['email'], $msg_subj, $msg_body);

 $green_msg="Password was sent successfully";

 show_one_item();
}

//************************
function export_csv(){

 $csv_data="First Name,Last Name,Email,Registered\n";
 $sql="select * 
  from users 
 where status=0 
 order by fname, lname
 ";
 $sth=db_query($sql);
 while($row=mysql_fetch_assoc($sth)){

    $csv_data.=to_csv_row( array($row['fname'], $row['lname'], $row['email'], $row['add_time']) );
 }

 header('Content-type: text/csv');
 header("Content-Disposition: attachment; filename=\"members.csv\"");

 echo $csv_data;
}

######
function to_csv_row($adata){
 $result='';

 foreach ($adata as $a){
   $result.=(($result)?",":"").quotestr($a);
 }

 return $result."\n";
}


#######
function quotestr($str){
 $str=n2br($str);
 $str=str_replace('"','""',$str);

 return '"'.$str.'"';
}

//****************************************************
//**************************************************** BROADCAST
//****************************************************
//***************************
//if $forceform=1 - redisplay values from FORM, not DB
function show_broadcast($forceform=0){
 global $green_msg, $err_msg, $this_tpl_dir;

 $hITEM=$_REQUEST['item'];
 list($msg_subj, $msg_body)=email2subj_body( get_lockfile( $GLOBALS['BEMAIL_FILE'] ) );

 $hITEMDB=array(
   'msg_subj' => $msg_subj, 
   'msg_body' => $msg_body,
 );

 if (!$forceform){
    $hITEM=&$hITEMDB;  //making $hITEM same as $hITEMDB (no array copy)
 }

 $ps=array(
 );
 $ps=array_merge($ps, $hITEM);
 $ps=array_merge($ps, get_userinfo());
 parse_page("$this_tpl_dir/edit_broadcast", $GLOBALS['PAGE_TPL_ADMIN'], $ps);
}

//*************************** 
function preview_broadcast(){
 global $green_msg, $err_msg, $site_templ, $this_tpl_dir;

 //read demo values from first user
 $sql="select * from users
   where status=0
   order by access_level, fname, lname
   limit 1
 ";
 $sth=db_query($sql);
 $row=mysql_fetch_assoc($sth);

 $msg_body=parse_page('/emails', 'email_broadcast.txt', $row, 'v');
 list($msg_subj, $msg_body)=email2subj_body( $msg_body );

 $ps=array(
   'msg_subj' => $msg_subj, 
   'msg_body' => $msg_body,
 );
 $ps=array_merge($ps, $hITEM);
 $ps=array_merge($ps, get_userinfo());
 parse_page("$this_tpl_dir/preview", $GLOBALS['PAGE_TPL_ADMIN'], $ps);
}

//*************************** save_broadcast
function save_broadcast(){
 global $green_msg, $err_msg;
 $item_id=$_REQUEST['id']+0;

 if (validate_item_br($item_id, $_REQUEST['item'])){

    //make some adjustments
    $IFORM=form2dbhash($_REQUEST['item'], 'msg_subj msg_body');

    add_lockfile($GLOBALS['BEMAIL_FILE'], $IFORM['msg_subj']."\n".$IFORM['msg_body'], 'replace');

    $green_msg="Email has been modified";

    preview_broadcast();
 } else {
    show_one_item(1);
 }

}

//################# Validate item form values in IFORM
function validate_item_br($item_id=0, $IFORM){
 global $err_msg;

 $REQFLD=array(
'msg_subj'   => array('Subject'),
'msg_body'   => array('Body'),
);

 //VALIDATE REQUIRED FIELDS
 if (!$err_msg) { $err_msg=validate_form($IFORM, $REQFLD); }

 if ($err_msg) { return 0 ;}
 return 1;
}


//********************
function send_broadcast(){

 echo "Sending emails...<br>\n";

 $sql="select * 
    from users
   where status=0
     and access_level=0
   order by email
 ";
 $sth=db_query($sql);
 while( $row=mysql_fetch_assoc($sth) ){

    $msg_body=parse_page('/emails', 'email_broadcast.txt', $row, 'v');
    list($msg_subj, $msg_body)=email2subj_body( $msg_body );
    echo "<b>$row[email]</b> - $row[fname] $row[lname]<br>\n";
    flush();

    send_email($row['email'], $msg_subj, $msg_body);
 }

 echo "finished<br>\n";
 echo "<a href='menu.php'>Click here to return to Main Menu</a><br>\n";
}


//**************************** IMPORT
function show_import(){
 global $green_msg, $err_msg, $this_tpl_dir;

 $ps=array(
 );
 $ps=array_merge($ps, $hITEM);
 $ps=array_merge($ps, get_userinfo());
 parse_page("$this_tpl_dir/import", $GLOBALS['PAGE_TPL_ADMIN'], $ps);
}

//********** import from uploaded CSV
function do_import(){
 global $green_msg, $err_msg, $this_tpl_dir;

 set_time_limit(5000);

 $field_name='file1';
 if (!($_FILES[$field_name] && $_FILES[$field_name]['name']>'')){
    $err_msg=lng("Please select file to upload");
    show_import();
    return;
 }

 $filename=$_FILES[$field_name]['tmp_name'];

 //read file
 $fp=fopen($filename,"r");

 //parsing CSV file
 $row=1;
 $fnames=array();
 while ($fields = fgetcsv ($fp, 4096)) {
    if ($row==1){
       $fnames=$fields;  //remember field names
    } else {
       //insert fields into db (and move pictures)
       $ir.=import_one_user($fields,$fnames);
    }
    $row++;
 }

 fclose($fp);


 $ps=array(
   'import_results' => $ir,
 );
 $ps=array_merge($ps, $hITEM);
 parse_page("$this_tpl_dir/importlog", $GLOBALS['PAGE_TPL_ADMIN'], $ps);

}

#############
function import_one_user($fields,$fnames){
 global $root_domain;

 $res='';
 $err_msg='';
 $u_id=0;
 
 $IFORM1=array();
 //convert to hash
 for($i=0;$i<count($fields);$i++){
    $IFORM1[ strtolower(trim($fnames[$i])) ]= $fields[$i];
 }

 //First Name,Last Name,Email
 $IFORM=array(
  'fname' => $IFORM1['first name'],
  'lname' => $IFORM1['last name'],
  'email' => $IFORM1['email'],
 );

 //Email
 if (!$err_msg && !$IFORM['email']){
    $err_msg=lng("Email is not defined.");
 }

 //VALIDATE if field unique
 if (!$err_msg && is_dbrecord_exists2('users', 'email', $IFORM['email'], " and status<>127") ){
    $err_msg=lng("Such Email already exists.");
 }

 if (!$err_msg){
    $IFORM['pwd']=get_rand_str(4);

    $sql="insert into users ".get_sqlinsert_set($IFORM,', add_time',', now()');
//    logger($sql);
    $sth=db_query($sql);
    $u_id=get_identity();
 }

 if (!$err_msg && $u_id && $_REQUEST['item']['sendnotify']){
    //send confirmation email
    $IFORM['ROOT_DOMAIN']=$root_domain;

    $msg_body=parse_page('/emails', 'email_confirm.txt', $IFORM, 'v');
    list($msg_subj, $msg_body)=email2subj_body($msg_body);

    #send confirmation email
    send_email($IFORM['email'], $msg_subj, $msg_body);
 }

 $res=$IFORM['fname']." ".$IFORM['lname']." (".$IFORM['email'].")";
 if ($err_msg || !$u_id){
    $res.=" - <b>".lng("error").": $err_msg</b>";
 }else{
    $res.=" - ".lng("imported successfully with Member ID")."=$u_id";
 }

 echo " ";
 flush();

 $res.="<br>";
 return $res;
}

?>
Return current item: PhpProjectMaster