<?php
#-------------------------------------------------------------------------
# Module: Newsletter Made Simple
#        (c) to 2008 by Paul Lempkepf
#        (c) 2008 and on by Robert Campbell (calguy1000@cmsmadesimple.org)
#
#  An addon module for CMS Made Simple to provide a flexible
#  mailing list solution.
#
#-------------------------------------------------------------------------
# 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( !isset($gCms) ) exit;
if( !$this->CheckPermission('Manage NMS Users') ) return;
$this->SetCurrentTab('users');

// get fielddefs
$fielddefs = nms_fielddef::load_all();

// get lists
$lists = $this->GetListsAsArray(array('dynamic'=>0));
if( !is_array($lists) || count($lists) == 0 ) {
  $this->SetError($this->Lang('error_nolists'));
  $this->RedirectToTab();
}

// build a column list
$cols = array('email','username');
if( is_array($fielddefs) && count($fielddefs) ) {
  foreach( $fielddefs as $field ) {
    $cols[] = 'f::'.$field['name'];
  }
}
foreach( $lists as $listid => $name ) {
  $cols[] = 'l::'.$name;
}

$offset = 0;
$batchsize = 500;
set_time_limit(9999);
$handlers = ob_list_handlers();
for ($cnt = 0; $cnt < sizeof($handlers); $cnt++) { ob_end_clean(); }
$bn = 'nms.csv';
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=\"$bn\"" );
header('Content-Transfer-Encoding: binary');

// a header line
echo '# '.implode(',',$cols)."\n\n";

$uquery = 'SELECT userid,email,username,disabled,confirmed,dateadded,dateconfirmed FROM '.NMS_USERS_TABLE.' ORDER BY userid';
$fquery = 'SELECT userid,fieldid,value FROM '.NMS_USER_DATA_TABLE.' WHERE userid IN %s ORDER BY userid ASC,fieldid ASC';
$lquery = 'SELECT userid,listid FROM '.NMS_LISTUSER_TABLE.' WHERE active = 1 AND userid IN %s ORDER BY userid ASC,listid ASC';
while( 1 ) {
  $u_dbr = $db->SelectLimit($uquery,$batchsize,$offset);
  if( !$u_dbr || $u_dbr->RecordCount() == 0 ) break;

  // get a list of userids
  $userlist = array();
  while( !$u_dbr->EOF ) {
    $userlist[] = $u_dbr->fields['userid'];
    $u_dbr->MoveNext();
  }
  $u_dbr->MoveFirst();

  // get the fields for these users
  $fieldinfo = array();
  {
    $tmp_fieldinfo = $db->GetArray(sprintf($fquery,'('.implode(',',$userlist).')'));
    if( is_array($tmp_fieldinfo) ) {
      foreach( $tmp_fieldinfo as $row ) {
	if( !isset($fieldinfo[$row['userid']]) ) $fieldinfo[$row['userid']] = array();
	$fieldinfo[$row['userid']][$row['fieldid']] = nms_utils::collapse_fielddata($row['value']);
      }
    }
  }

  // get the lists for these users
  $listinfo = array();
  {
    $tmp_listinfo = $db->GetArray(sprintf($lquery,'('.implode(',',$userlist).')'));
    if( is_array($tmp_listinfo) ) {
      foreach( $tmp_listinfo as $row ) {
	if( !isset($listinfo[$row['userid']]) ) $listinfo[$row['userid']] = array();
	$listinfo[$row['userid']][] = $row;
      }
    }
  }

  // export everything
  while( !$u_dbr->EOF ) {
    $row = $u_dbr->fields;
    $uid = $row['userid'];
    $fields = array();
    $fields[] = $row['email'];
    $fields[] = $row['username'];

    if( is_array($fielddefs) && count($fielddefs) ) {
      foreach( $fielddefs as $field ) {
	$val = '';
	if( isset($fieldinfo[$uid][$field['id']]) ) {
	  // find the info for this field.
	  // todo: clean up the value (replace newlines etc)
	  $val = $fieldinfo[$uid][$field['id']];
	}
	$fields[] = $val;
      }
    }

    if( is_array($lists) && count($lists) ) {
      foreach( $lists as $listid => $lname ) {
	$val = '';
	if( isset($listinfo[$uid]) ) {
	  foreach( $listinfo[$uid] as $row ) {
	    if( $listid == $row['listid'] ) {
	      $val = '1';
	      break;
	    }
	  }
	}
	$fields[] = $val;
      }
    }

    echo cge_array::implode_quoted($fields)."\n";
    $u_dbr->MoveNext();
  }

  // ready for the next batch
  $offset += $batchsize;
}

audit('','NMS','Users exportedd to CSV');
exit();

#
# EOF
#
?>
