<?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

final class nms_utils
{
  private static $_preload_customfields;
  private function __construct() {}

  public static function text_to_options($text,$lowercase_keys = FALSE)
  {
    $text = trim($text);
    if( !$text ) return;
    $lines = explode("\n",$text);

    $out = array();
    foreach( $lines as $line ) {
      $line = trim($line);
      if( !$line ) continue;

      $key = $value = null;
      if( strpos($line,'=') === FAlSE ) {
          $key = $value = $line;
      }
      else {
          list($key,$value) = explode('=',$line,2);
          $key = trim($key);
          $value = trim($value);
      }

      if( !$key ) $key = $value;
      if( !$value ) $value = $key;
      if( $lowercase_keys ) $key = strtolower($key);
      $out[$key] = $value;
    }

    if( count($out) > 0 ) return $out;
  }

  public static function get_userinfo($data = null)
  {
    $user = array();
    $user['userid'] = '';
    $user['uniqueid'] = '';
    $user['email'] = '';
    $user['username'] = '';
    $user['disabled'] = 0;
    $user['confirmed'] = 0;
    $user['dateconfirmed'] = null;
    $user['htmlemail'] = 1;
    $user['error_count'] = 0;
    $user['bounce_count'] = 0;
    $user['fields'] = array();
    $user['lists'] = array();

    $loaded = FALSE;
    $db = cmsms()->GetDb();
    $mod = cms_utils::get_module('NMS');
    if( is_int($data) && $data > 0 ) $data = array('userid'=>(int)$data);
    if( isset($data['userid']) && $data['userid'] > 0 ) {
      $query = 'SELECT * FROM '.NMS_USERS_TABLE.' WHERE userid = ?';
      $user = $db->GetRow($query,array((int)$data['userid']));
      if( !is_array($user) || count($user) == 0 ) throw new CmsException($mod->Lang('error_usernotfound'));
      $loaded = TRUE;
    }
    else if( isset($data['email']) && strlen($data['email']) ) {
      $query = 'SELECT * FROM '.NMS_USERS_TABLE.' WHERE email = ?';
      $user = $db->GetRow($query,array(trim($data['email'])));
      if( !is_array($user) || count($user) == 0 ) throw new CmsException($mod->Lang('error_usernotfound'));
      $loaded = TRUE;
    }
    else if( isset($data['uniqueid']) && strlen($data['uniqueid']) ) {
      $query = 'SELECT * FROM '.NMS_USERS_TABLE.' WHERE uniqueid = ?';
      $user = $db->GetRow($query,array(trim($data['uniqueid'])));
      if( !is_array($user) || count($user) == 0 ) throw new CmsException($mod->Lang('error_usernotfound'));
      $loaded = TRUE;
    }

    if( $loaded ) {
      $fielddefs = nms_fielddef::load_all(TRUE);
      if( is_array($fielddefs) && count($fielddefs) ) {
	$query = 'SELECT * FROM '.NMS_USER_DATA_TABLE.' WHERE userid = ?';
	$tmp = $db->GetArray($query,array($user['userid']));
	$user['fields'] = array();
	if( is_array($tmp) && count($tmp) ) {
	  foreach( $tmp as $row ) {
	    if( isset($fielddefs[$row['fieldid']]) ) {
	      $name = $fielddefs[$row['fieldid']]['name'];
	      $user['fields'][$row['fieldid']] = $row['value'];
	    }
	  }
	}
      }

      $query = 'SELECT listid FROM '.NMS_LISTUSER_TABLE.' WHERE userid = ? AND active = 1';
      $user['lists'] = $db->GetCol($query,array($user['userid']));
    }

    return $user;
  }

  public static function user_adderror($data)
  {
    $db = cmsms()->GetDb();
    if( (int)$data > 0 ) $data['userid'] = (int)$data;
    if( isset($data['userid']) && $data['userid'] > 0 ) {
      $query = 'UPDATE '.NMS_USERS_TABLE.' SET error_count = COALESCE(error_count,0) + 1 WHERE userid = ?';
      $dbr = $db->Execute($query,$data['userid']);
    }
    else if( isset($data['email']) ) {
      $query = 'UPDATE '.NMS_USERS_TABLE.' SET error_count = COALESCE(error_count,0) + 1 WHERE email = ?';
      $dbr = $db->Execute($query,$data['email']);
    }
    else if( isset($data['uniqueid']) ) {
      $query = 'UPDATE '.NMS_USERS_TABLE.' SET error_count = COALESCE(error_count,0) + 1 WHERE uniqueid = ?';
      $dbr = $db->Execute($query,$data['email']);
    }
  }

  public static function preload_customfields($list,$keyfield = 'userid')
  {
    if( !is_array($list) || count($list) == 0 ) return;
    $list = array_unique($list);
    if( !is_array($list) || count($list) == 0 ) return;
    $fielddefs = nms_fielddef::load_all(TRUE);
    if( !is_array($fielddefs) || count($fielddefs) == 0 ) return;

    switch( $keyfield ) {
    case 'userid':
      break;

    case 'uniqueid':
    case 'email':
      $query = 'SELECT DISTINCT userid FROM '.NMS_USERS_TABLE." WHERE $keyfield IN (".implode(',',$list).')';
      $list = $db->GetArray($query);
      break;

    default:
      throw new CmsException('Invalid key field '.$keyfield.' in preload_customfields');
    }

    $db = cmsms()->GetDb();
    $query = 'SELECT userid,fieldid,value FROM '.NMS_USER_DATA_TABLE.' WHERE userid IN ('.implode(',',$list).') ORDER BY userid,fieldid';
    $dbr = $db->GetArray($query);
    self::$_preload_customfields = null;
    if( is_array($dbr) && count($dbr) ) {
      $preload = array();
      foreach( $dbr as $row ) {
	if( !isset($preload[$row['userid']]) ) $preload[$row['userid']] = array();
	if( !isset($fielddefs[$row['fieldid']]) ) continue;
	$obj = $fielddefs[$row['fieldid']];

	$preload[$row['userid']][$obj['name']] = $row['value'];
      }
      self::$_preload_customfields = $preload;
    }
  }

  static public function get_userfields($userid)
  {
    $userid = (int)$userid;
    if( $userid < 1 ) return;
    if( isset(self::$_preload_customfields[$userid]) ) return self::$_preload_customfields[$userid];
  }

  static public function collapse_fielddata($val)
  {
    $orig = $val;
    $val = str_replace("\r\n","\n",$val); // convert DOS to unix newlines
    $val = str_replace("\r","\n",$val);  // convert MAC to unix newlines (too bad for you guys)
    $val = str_replace("\n","|NL|",$val); // encode newlines
    $val = str_replace("\t","|TAB|",$val);
    $val = str_replace('#','|HASH|',$val);
    $val = addslashes($val);
    return $val;
  }

  static public function expand_fielddata($val)
  {
    $orig = $val;
    $val = stripslashes($val);
    $val = str_replace('|HASH|','#',$val);
    $val = str_replace('|TAB|',"\t",$val);
    $val = str_replace("|NL|","\n",$val);
    return $val;
  }
} // end of class

?>