<?php
#BEGIN_LICENSE
#-------------------------------------------------------------------------
# Module: MAMS (c) 2020-2021 by CMS Made Simple Foundation
#  An add-on module for CMS Made Simple to provide useful functions
#  and commonly used gui capabilities to other modules.
#-------------------------------------------------------------------------
# A fork of:
#
# Module: FrontEndUsers (c) 2008-2014 by Robert Campbell
#         (calguy1000@cmsmadesimple.org)
#
#-------------------------------------------------------------------------
#
# CMSMS - CMS Made Simple is (c) 2006 - 2021 by CMS Made Simple Foundation
# CMSMS - CMS Made Simple is (c) 2005 by Ted Kulp (wishy@cmsmadesimple.org)
# Visit the CMSMS Homepage at: http://www.cmsmadesimple.org
#
#-------------------------------------------------------------------------
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# However, as a special exception to the GPL, this software is distributed
# as an addon module to CMS Made Simple.  You may not use this software
# in any Non GPL version of CMS Made simple, or in any version of CMS
# Made simple that does not indicate clearly and obviously in its admin
# section that the site was built with CMS Made simple.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Or read it online: http://www.gnu.org/licenses/licenses.html#GPL
#
#-------------------------------------------------------------------------
#END_LICENSE
if( !defined('CMS_VERSION') ) { exit; }
if( !$this->_HasSufficientPermissions('users') ) return;

// this tab has merely one mofo list of uses and the ability to edit them,
// see details about them, and then delete them

//
// initialization
//
$this->SetCurrentTab('users');
$admintheme = cms_utils::get_theme_object();
$tpl = $this->CreateSmartyTemplate('userlist.tpl');
if( $this->_HasSufficientPermissions('listusers') )
{
    $filter = $bare_filter = array('group'=>'','regex'=>'','loggedinonly'=>0,'limit'=>50,
                                   'viewprops'=>[],'propsel'=>'','propval'=>'','sortby'=>'username asc',
                                   'disabledstatus'=>'');
    $tmp = cms_userprefs::get('mams_filter');
    if( $tmp ) $filter = unserialize($tmp);

    // bulk action stuff
  if(isset($params['dobulk']))
  {
    if(isset($params['selected']) && is_array($params['selected']))
    {
      $sel = base64_encode(serialize($params['selected']));
      $this->myRedirect(
        $id, 'admin_bulkactions', $returnid,
        ['job' => \xt_param::get_string($params, 'bulk_action', 'delete'), 'uids' => $sel]
      );
    }
  }

    // filtering stuff
  if(isset($params['filter_reset']))
  {
    cms_userprefs::remove('mams_filter');
    $this->session_clear('cur_page');
    $filter = $bare_filter;
  }
  else if(isset($params['filter']))
  {
    $filter['group']        = get_parameter_value($params, 'filter_group');
    $filter['regex']        = trim(get_parameter_value($params, 'filter_regex'));
    $filter['loggedinonly'] = (int)get_parameter_value($params, 'filter_loggedinonly');
    $filter['limit']        = (int)get_parameter_value($params, 'filter_limit');
    $filter['sortby']       = trim(get_parameter_value($params, 'filter_sortby'));
    $filter['viewprops']    = get_parameter_value($params, 'filter_viewprops');
    $filter['propsel']      = trim(get_parameter_value($params, 'filter_propertysel'));
    if($filter['propsel'] == 'none') { $filter['propsel'] = ''; }
    
    $filter['propval']        = trim(get_parameter_value($params, 'filter_property'));
    $filter['disabledstatus'] = \xt_param::get_string($params, 'filter_disabled');
    $this->session_clear('cur_page');
    cms_userprefs::set('mams_filter', serialize($filter));
  }

    $tpl->assign('filter',$filter);
    $filterapplied = ($filter != $bare_filter);
    $tpl->assign('filter_applied',$filterapplied);

    // get a group list for the filter
    // it should be ready to go right into the dropdown (cool eh)
    $groups = null;
    $groups1 = $this->GetGroupList();
    if(is_array($groups1) && count($groups1))
    {
      $groups = array_merge([$this->Lang('any') => -1], $groups1);
      $tpl->assign('groups', array_flip($groups));
    }
  
  // a pulldown list for limits
    $limits = array( '10' => 10,
                     '25' => 25,
                     '50' => 50,
                     '100' => 100,
                     '250' => 250,
                     '500' => 500 );
    $tpl->assign('limits',$limits);

    // a pulldown list for property definitions
    $defns1 = $this->GetPropertyDefns();
    $defns = array();
    $defns['None'] = 'none';
    $alldefns = array();
  if(is_array($defns1))
  {
    foreach($defns1 as $def)
    {
      if($def['prompt'] == '' || $def['name'] == '') { continue; }
      if($def['encrypt']) { continue; } // you can't view encrypted properties in this list.
      
      $defns[$def['prompt']]  = $def['name'];
      $alldefns[$def['name']] = $def['prompt'];
    }
  }
    
  $tpl->assign('defnlist',array_flip($defns));

  // a pulldown list for sorting
  $sorts = [
              $this->Lang('sortby_username_asc')  => 'username asc',
              $this->Lang('sortby_username_desc') => 'username desc',
              $this->Lang('sortby_create_asc')    => 'createdate asc',
              $this->Lang('sortby_create_desc')   => 'createdate desc',
              $this->Lang('sortby_expires_asc')   => 'expires asc',
              $this->Lang('sortby_expires_desc')  => 'expires desc'
            ];
  
  $tpl->assign('sortlist',array_flip($sorts));

  // now setup the template fields
  $tpl->assign( 'prompt_sort', $this->Lang('sort'));
  $tpl->assign( 'startform', $this->XTCreateFormStart( $id, 'defaultadmin', $returnid, array('xt_activetab'=>'users')));
  $tpl->assign( 'perm_removeusers', $this->_HasSufficientPermissions('removeusers')?1:0);
  $tpl->assign( 'usersfound', $this->Lang('usersfound'));
  $tpl->assign( 'alldefns',$alldefns);
  $tpl->assign( 'viewprops',$filter['viewprops']);
  $tpl->assign( 'endform', $this->CreateFormEnd ());

  // now get our users
  $users = null;
  $curpage = $this->session_get('cur_page',1);
  $nmatches = 0;
  
  if(isset($params['page']))
  {
    $curpage = (int)$params['page'];
    $this->session_put('cur_page', $curpage);
  }
  
  $offset = ($curpage - 1) * $filter['limit'];
  try
  {
    $users = mams_utils::get_users_from_filter( $filter, $offset, $nmatches );
  }
  catch( Exception $e )
  {
      $this->_DisplayErrorPage ($id, $params, $returnid, $e->GetMessage() );
  }
  
  if(!is_array($users))
  {
    // an error occurred
    $this->_DisplayErrorPage($id, $params, $returnid, $db->ErrorMsg());
  }

    // calculate pages and page links.
    $numusers = $nmatches;
    $npages = (int)($nmatches / $filter['limit']);
    if( $nmatches % $filter['limit'] != 0 ) $npages++;
    $curpage = max(0,min($curpage,$npages));

    $nav = array();
    $nav['npages'] = $npages;
    $nav['curpage'] = $curpage;
    if( $curpage > 1 ) {
        $nav['firstpage_url'] = $this->create_url($id,'defaultadmin','', array('xt_activetab'=>'users','page'=>1));
        $nav['prevpage_url'] = $this->create_url($id,'defaultadmin','', array('xt_activetab'=>'users','page'=>$curpage-1));
    }
    if( $curpage < $npages ) {
        $nav['nextpage_url'] = $this->create_url($id,'defaultadmin','', array('xt_activetab'=>'users','page'=>$curpage+1));
        $nav['lastpage_url'] = $this->create_url($id,'defaultadmin','', array('xt_activetab'=>'users','page'=>$npages));
    }
    $tpl->assign('navigation',$nav);

    // get the total number of users

    // get the selected properties.
    if( is_array($filter['viewprops']) && count($filter['viewprops']) ) {
        if( is_array($users) && count($users) ) {
            $uids = array();
            foreach( $users as $row ) {
                $uids[] = $row['id'];
            }

            $query = "SELECT A.id,";
            $flds = array();
            $conds = array();
            $count_view_props = count($filter['viewprops']);
            for( $i = 0; $i < $count_view_props; $i++ )
            {
                $prop = $filter['viewprops'][$i];
                $nm = 'j'.$i;
                $flds[]  = "$nm.data as $prop";
                $conds[] = cms_db_prefix()."module_mams_properties AS $nm ON A.id = $nm.userid AND ($nm.title = '$prop')";
            }
            $query .= implode(',',$flds).' FROM '.cms_db_prefix().'module_mams_users A';
            $query .= ' LEFT JOIN '.implode(' LEFT JOIN ',$conds);
            $query .= ' WHERE A.id IN ('.implode(',',$uids).')';
            $dbr = $db->Execute('SET sql_big_selects = 1');
            $tmp = $db->GetArray($query);
            $extraprops = xt_array::to_hash($tmp,'id');
        }
    }

    // build the user list.
    $rowarray = array();
    $tpl->assign('numusers', $numusers );
    $consumer = mams_utils::get_auth_consumer();
    if( $this->GetPreference('username_is_email') && get_class($consumer) == 'mams_std_consumer' ) {
        $tpl->assign('usernametext', $this->Lang('prompt_email'));
    }
    else {
        $tpl->assign('usernametext', $this->Lang('username'));
    }
    $tpl->assign('emailtext', $this->Lang('email'));
    $tpl->assign('statustext', $this->Lang('status'));
    $tpl->assign('createdtext', $this->Lang('created'));
    $tpl->assign('expirestext', $this->Lang('expires'));
    if( is_array($users) ) {
        foreach( $users as $row ) {
            $onerow = new StdClass();
            $onerow->id = $row['id'];
            $onerow->disabled = (bool) $row['disabled'];
            $onerow->must_validate = (bool) (isset($row['must_validate'])) ? $row['must_validate'] : false;
            $onerow->created  = $row['createdate'];
            $onerow->username = $this->CreateLink($id, 'admin_edituser', $returnid, $row['username'], array('user_id' => $row['id']));
            $onerow->expires  = $row['expires'];
            $onerow->unsafepassword = strlen($row['password']) == 32;

            if( $this->_HasSufficientPermissions('listusers') ) {
                $onerow->historylink =
                    $this->CreateLink ($id, 'userhistory', $returnid,
                                       $admintheme->DisplayImage('icons/system/info.gif',$this->Lang('history'),'','','systemicon'),
                                       array('user_id'=>$row['id']));
            }

            if( $this->_HasSufficientPermissions('editusers') ) {
                $onerow->editlink =
                    $this->CreateLink ($id, 'admin_edituser', $returnid,
                                       $admintheme->DisplayImage('icons/system/edit.gif', $this->Lang ('edit'), '', '', 'systemicon'),
                                       array ('user_id' => $row['id'] ));
                if( $row['loggedin'] ) {
                    $onerow->logoutlink =
                        $this->CreateLink ($id,'admin_logout',$returnid,
                                           $admintheme->DisplayImage('icons/system/back.gif', $this->Lang('prompt_logout'),'','','systemicon'),
                                           array('user_id'=>$row['id']));
                }
            }

            if( $this->_HasSufficientPermissions('removeusers') ) {
                $onerow->deletelink =
                    $this->CreateLink ($id,'do_deleteuser',$returnid,
                                       $admintheme->DisplayImage('icons/system/delete.gif',$this->Lang ('delete'), '', '', 'systemicon'),
                                       array ('user_id' => $row['id']),
                                       $this->Lang ('areyousure_delete',$row['username']));
            }

            if( is_array($filter['viewprops']) && count($filter['viewprops']) ) {
                $onerow->extra = [];
                foreach( $filter['viewprops'] as $one ) {
                    if( isset($extraprops[$onerow->id][$one]) ) {
                        $ob = new \StdClass;
                        $ob->val = $extraprops[$onerow->id][$one];
                        $ob->defn = $defns1[$one];
                        $onerow->extra[$one] = $ob;
                    }
                }
            }

            $rowarray[] = $onerow;
        }
    }

    $tpl->assign('itemcount',count($rowarray));
    $tpl->assign('items',$rowarray);
    $bulk_actions = [];
    if( $this->_HasSufficientPermissions('editusers') )
    {
        $bulk_actions['disable'] = $this->Lang('bulk_disable');
        $bulk_actions['enable'] = $this->Lang('bulk_enable');
        $bulk_actions['forcechpw'] = $this->Lang('bulk_forcechpw');
        $bulk_actions['forcechsettings'] = $this->Lang('bulk_forcechsettings');
        $bulk_actions['setpassword'] = $this->Lang('bulk_setpassword');
        $bulk_actions['setexpiry'] = $this->Lang('bulk_setexpiry');
    }

    if( $this->_HasSufficientPermissions('removeusers') ) {
        $bulk_actions['delete'] = $this->Lang('bulk_delete');
    }
    
    if( count($bulk_actions) ) $tpl->assign('bulk_actions',$bulk_actions);
} // listusers permission

if($this->_HasSufficientPermissions('adduser'))
{
//  if($this->GetPreference('require_onegroup') == 0 || count($groups1) > 0)
//  {
//    $tpl->assign('add_url', $this->create_url($id, 'admin_edituser', $returnid));
//  }
  
  $tpl->assign('add_url', $this->create_url($id, 'admin_edituser', $returnid));
}

if( $this->_HasSufficientPermissions('users') ) {
    if( !empty($groups) ) $tpl->assign('import_url',$this->create_url($id,'admin_import_users',$returnid));
    if( !empty($rowarray) ) $tpl->assign('export_url',$this->create_url($id,'admin_export_users',$returnid));
}

$tpl->display();
