<?php
#require_once ('/users/shared/htdocs/tools/bltoolsv2.php');

class NP_PHPList extends NucleusPlugin {
	// name of plugin
	function getName() {
		return 'Frontend PHPList';
	} # end of getName
 
	// author of plugin
	function getAuthor()  {
		return 'Bart Lievers';
	} # end of getAuthor
 
	// an URL to the plugin website
	// can also be of the form mailto:foo@bar.com
	function getURL() {
		return 'http://blog.bartlievers.nl/';
	} # end of getURL
 
	// version of the plugin
	function getVersion() {
		return '0.9.5';
	} # end of getVersion

	// a description to be shown on the installed plugins listing
	function getDescription() {
		return 'A frontend for PHPlist v.2.10.4 from tincan. Use <%PHPlist%> in skin to call frontend.';
	} # end of getDescription
	
	function init() {
 		if (($this->getOption(UpdatePlugin)=="yes") || ($this->getOption(UpdatePlugin)=="")) {
 			$this->install(); # run the install function.
			$this->setOption('UpdatePlugin','no'); # !! leave this line, so Update option is a toggle function
 		}	
	} # end of init

	function updateOption($option,$description,$type,$default) {
	//Update an option. Basicly it saves the value of the option to update, then deletes the options and then creates the option with the saved value. The option will then be at the bottem of the option list in the 'edit option' page of the plugin.
		if ($this->getOption($option)=="") {
			$default_val=$default;
			ACTIONLOG::ADD(INFO,'{NP_PHPList} option :'.$option.' created.');
		 } else {
			$default_val=$this->getOption($option);
			ACTIONLOG::ADD(INFO,'{NP_PHPList} option :'.$option.' updated.');
			$this->deleteOption($option);
		}
		$this->createOption($option,$description,$type,$default_val);
	}	#end of updateOption
	
	function install() {
 
		global $CONF; 
		$this->updateOption('UpdatePlugin',"Update the plugin options on next call of this plugin. This option will reset it self when updated. !!When this option is set to 'yes' new defined options will be added with default values and known options will be updated!!.","yesno","no");	
		//URLLocation
		$this->updateOption("URLLocation", "Location path after base url ".$CONF['IndexURL'],"text",'news/');
		$this->updateOption("PHPlistPath", "Full path to PHPlist  location ","text",dirname(__FILE__));
		//PageNotAvailableMsg
		$this->updateOption("PageNotAvailableMsg", "Under construction / out of order message: (HTML message shown on pages that are not yet implemented bij NP_PHPList)", "textarea", 
					"Not supported<br> Sorry, this page is not (yet) supported by NP_PHPList v. ".$this->getVersion()." Select one of the links at the bottem of this page to continue.");
		$this->updateOption("WelcomeMsgSelectPage", "Welcome message on main page.(Only used when there are 2 or more active subscribepages defined in PHPList)", "textarea", 
					"Welcome,<br> use one of the following links to subscribe.<BR>"); 
		$this->updateOption("textPreferHTMLEmail","Text to display after checkbox for HTML-format","text",
					"I prefer to receive HTML formatted e-mails.");
		$this->updateOption("textPreferPlainEmail","Text to display after checkbox for text-format","text",
					"I prefer to receive PLAIN formatted e-mails.");
		$this->updateOption('UnsubTitle','Welcome text for the unsubscribepage','textarea',
					'Welcome,<br> you are at the unsubscribe page. Use the following field(s) to unsubscribe.');
		$this->updateOption('UnsubEmailLabel','Text to display for unsubscribe e-mail','text','E-mail');
		$this->updateOption('UnsubscribeButton','Text for the unsubscribe button','text','Unsubscribe me');
		$this->updateOption('UnsubLink','Text for unsubscribe link on every page','text','Unsubscribe');
		$this->updateOption('subLink','Text for startpage link on every page','text','Startpage');
		$this->updateOption('BlackListedWarning','Warning message to display when a blacklisted user is subscribing.( Use the [EMAIL] placeholder to display the e-mail address)','textarea',
					"The e-mail address [EMAIL] is blacklisted.<br> Meaning that you have unsubscribed in the past from our newsletter(s).<BR> The only e-mail we are sending you is a request-to-confirm-your-subscription e-mail. Use the link in the e-mail to subscribe.<br>By subscribing you will me automaticly be removed from our blacklist.");
		$this->updateOption('goodbyeMsg','Goodbye message after unsubscribe, use [EMAIL] to place e-mail address','textarea',
					'Your address [EMAIL] is unsubscribed and listed on our blacklist. By adding you to our blacklist we are making that we won\'t send you any e-mails in the future.<br> A confirmation of your removal is send.');
		$this->updateOption('ConfirmedMessage','Thank you message on reaction of user confirmation. (Use the placeholder [EMAIL] to display the confirmed address.)','textarea',
					'Thank you for confirming your subscribtion with address [EMAIL].<br> An e-mail containing your subscribtion details is send. Please keep it save.');
		$this->updateOption('ListingHeader','Announcement of the lists to choose from','textarea','Select the newsletters you want to receive:');
		$this->updateOption('WarnWebmasterMsg','Message to ask user to warn webmaster','textarea','Oops, something didn\'t work out. Please inform the webmaster.<br> (the plugin made a message with more details in the Actionlog)');
		$this->updateOption('IncorrectUID','Message to warn when uid is invalid','textarea','The uid is not known. Check the url link you are using. Maybe it is split over more lines.');
		$this->updateOption('confirmFailed','HTML message to display when confirmation failed. Use [EMAIL] to place e-mail address.','textarea',
			'Subscription of [EMAIL] has failed. Try again to subscribe.');
		$this->updateOption('ReqQuestion','Warning to display when required fields are not filled in.','textarea',
					'The following field(s) are empty');
		$this->updateOption('differentEmails','Warning message when e-mail fields do not contain same address.','textarea',
					'The e-mail address you entered are not the same.');
		$this->updateOption('PrefWelcome','Welcome / intro message for preference page.','textarea',
					'Preference update page<BR> Update your record here ');
		$this->updateOption('AddressChanged','HTML message to display when user changed it\'s e-mail address','textarea',
					'You\'ve changed your e-mail address. A request-to-confirm e-mail has been send to your NEW e-mail adres. Use the link it contains to confirm the new address.');
		$this->updateOption('PrefDone','HTML message to show after preferences are changed.','textarea',
					'Your preferences are updated. An e-mail has been sended as confirmation of the changes.');
		$this->updateOption('SubButton','Text to display on subscribe button.','text','Subscribe me');
		$this->updateOption('PrefButton','Text to display on button of the preference page.','text','Change my preferences');
		$this->updateOption('AdminAddress','E-mail address of administrator to notify.','text','admin@yourdomain.tld');
		$this->updateOption('AlwaysNotifyAdmin','Always notify admin. This overrules all notify admin options set below.','yesno','yes');
		$this->updateOption('NotifyofSubscribe','Notify admin of PHPList subscribtion.','yesno','no');
		$this->updateOption('notifyofconfirm','Notify admin of user subscribe confirmation to PHPList.','yesno','no');
		$this->updateOption('notifyofchanges','Notify admin of user profile changes in PHPList.','yesno','no');
		$this->updateOption('notifyofunsubscribe','Notify admin of user unsubscribtion of PHPList','yesno','no'); 
		$this->updateOption('AddtoNewbiesList','Add new list members to pre-specified list?','yesno','no');
		$this->updateOption('NewbieList','Name of pre-specified list','text','New members');	
    } #end of function install()

 
	function doSkinVar($skinType) {
	global $CONF, $manager,$MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE,$MYSQL_PASSWORD,$ACTIONLOG,$PluginGlobals,$PHPlist;
 
		echo '<br>'; # make sure the first line is blank

 
		// load some main configuration options
		$PHPlistPath=$this->getOption(PHPlistPath);	
		// check if path to PHPlist is valid
		if (!file_exists($PHPlistPath.'/config/config.php')) { #no valid path found.... so let's quit here
    		ACTIONLOG::add(ERROR, '{NP_PHPlist} Failed checking valid path to PHPlist ('.$PHPlistPath.'), please check plugin settings.');
			echo $this->getOption(WarnWebmasterMsg).'<br>';
    		closePage();
    		return;
		}
  		#doDebug($PHPlistPath,'122: PHPlistPath');
		$PHPlist = new phplist($PHPlistPath);
		$PHPListConfig = $PHPlist->loadConfig();
		#doDebug($PHPListConfig,'125: PHPListConfig');
 
		// Get the rest of them		
		$PluginGlobals['PageNotAvailableMsg']=$this->getOption(PageNotAvailableMsg);
 		$PluginGlobals['WelcomeMsgSelectPage']=$this->getOption(WelcomeMsgSelectPage);
 		$PluginGlobals['BaseUrl']=$CONF['IndexURL'].$this->getOption(URLLocation);
 		$PluginGlobals['textPreferHTMLEmail']=$this->getOption(textPreferHTMLEmail);
 		$PluginGlobals['textPreferPlainEmail']=$this->getOption(textPreferPlainEmail);
		$PluginGlobals['UnsubEmailLabel']=$this->getOption(UnsubEmailLabel);
 		$PluginGlobals['UnsubscribeButton']=$this->getOption(UnsubscribeButton);
 		$PluginGlobals['UnsubTitle']=$this->getOption(UnsubTitle);
 		$PluginGlobals['UnsubLink']=$this->getOption(UnsubLink);
 		$PluginGlobals['subLink']=$this->getOption(subLink);
 		$PluginGlobals['goodbyeMsg']=$this->getOption(goodbyeMsg);
		$PluginGlobals['BlackListedWarning']=$this->getOption(BlackListedWarning);
 		$PluginGlobals['ConfirmedMessage']=$this->getOption(ConfirmedMessage);
 		$PluginGlobals['version']=$this->getVersion(); 
 		$PluginGlobals['ListingHeader']=$this->getOption(ListingHeader);
 		$PluginGlobals['WarnWebmasterMsg']=$this->getOption(WarnWebmasterMsg).'<br>';
 		$PluginGlobals['IncorrectUID']=$this->getOption(IncorrectUID);
 		$PluginGlobals['confirmFailed']=$this->getOption(confirmFailed);
 		$PluginGlobals['PHPlistPath']=$this->getOption(PHPlistPath);
		$PluginGlobals['ReqQuestion']=$this->getOption(ReqQuestion);
 		$PluginGlobals['differentEmails']=$this->getOption(differentEmails);
 		$PluginGlobals['PrefWelcome']=$this->getOption(PrefWelcome);
 		$PluginGlobals['AddressChanged']=$this->getOption(AddressChanged);
 		$PluginGlobals['PrefDone']=$this->getOption(PrefDone);
 		$PluginGlobals['SubButton']=$this->getOption(SubButton);
		$PluginGlobals['PrefButton']=$this->getOption(PrefButton);
		$PluginGlobals['AdminAddress']=$this->getOption(AdminAddress);
		$PluginGlobals['NotifyofSubscribe']=$this->getOption(NotifyofSubscribe);
		$PluginGlobals['notifyofconfirm']=$this->getOption(notifyofconfirm);
		$PluginGlobals['notifyofchanges']=$this->getOption(notifyofchanges);
		$PluginGlobals['notifyofunsubscribe']=$this->getOption(notifyofunsubscribe); 
		$PluginGlobals['AlwaysNotifyAdmin']=$this->getOption(AlwaysNotifyAdmin);
		$PluginGlobals['AddtoNewbiesList']=$this->getOption(AddtoNewbiesList);
		$PluginGlobals['NewbieList']=$this->getOption(NewbieList);		
# 		$PluginGlobals['']=$this->getOption();
 #		doDebug($PluginGlobals,'163: pluginGlobals');

 		//Check if the given NewbieList is known
 		if ($PluginGlobals['AddtoNewbiesList']=='yes') {
			$listid = $PHPlist->GetListbyName($PluginGlobals['NewbieList']);
			if (!is_numeric($listid)) { #given list name is not known, so disabling automatic list subscribtion to default list.
				$PluginGlobals['AddtoNewbiesList']='no';
				addLog(ERROR,'Unknown list name given in PHPList plugin options. Default-subscribe-to-list option is disabled.');
				echo 'Incorrect parameter value for plugin, please contact webmaster.<BR><BR>';
			}
		}
		// check if there are parameters in the url and if they are valid
		// On succes it will load the data in an array
		// UID parameter
		if (isset($_GET['uid'])) { # an uid is present
			$uid=$_GET['uid'];
			if ($PHPlist->isKnown($uid,'uniqid')) { #we know the uid
				$uidData=$PHPlist->getUserData($uid,true);
				if ($PHPlist->isKnown($uidData['subscribepage'],'pageID')) {#select the users subscribepage
				$SubscrPageID=$uidData['subscribepage']; 			
				}
			} else { #uid is not known or not valid
				echo $PluginGlobals['IncorrectUID'];
				addLog(ERROR,'Incorrect UID is given in url. URL asked '.$_SERVER['QUERY_STRING']);
				$uidData=false;
				closePage();
				return;
			}
		}
 
		// id parameter (id for subscriptionpage)
		if (isset($_GET['id'])) { # an id is known
			$SubscrPageID = $_GET['id'];
			if (!$PHPlist->isKnown($SubscrPageID,'pageID')) unset($SubscrPageID);
		} 
		if (!isset($SubscrPageID)) {
			$SubscrPageID = $PHPListConfig['defaultsubscribepage'];
			if (isset($_GET['id'])) addLog(ERROR,"requested subscribepage is not valid. URL asked ".$_SERVER['QUERY_STRING']);
		}
		$activeSubscrLists=$PHPlist->getSPages(true); #load index of all active subscribe pages
		if (count($activeSubscrLists)<1) {
			echo $pluginGlobals['WarnWebmasterMsg'];
			addLog(ERROR, "No active subscription page is selected. Please activate the correct page in the admin site of PHPlist.<br>");
			closePage();
			return; #no use of further functioning, so stop here
		}	
		$SubscrPageFound=false;
		foreach ($activeSubscrLists as $ActiveSubscrList) { #check if requested subscription page is active
			if ($ActiveSubscrList['id'] == $SubscrPageID) {
				$SubscrPageFound=true;
				break; #no use of further checking
			}
		}
		if ($SubscrPageFound) { # when a page id is valid, load the page data
			$PageData=$PHPlist->getPageData($SubscrPageID);
			$oneSubscrPage= (count($activeSubscrLists)==1);
		} else {
			echo $pluginGlobals['WarnWebmasterMsg'];
			addLog(ERROR, "No active page is selected.
				Please activate the correct page in the admin site of PHPlist.
				Make also sure if the subscribtion page defined as default is active.");
			closePage();
			return; #no use of further functioning, so stop here
		}
 
		// p parameter. frontend page to display
		// if none is selected, but PHPlist has one subscribepage active. Then the Plugin will select that page
		// and shows the subscribe forms
		if (isset($_GET['p'])) {
			$p = $_GET['p'];
		} else { #no page is selected
			if ($oneSubscrPage && !isset($_GET['uid'])) { #if there is only one active subscriptionpage, then select the subscription page
				$p='subscribe';
			} else {
				$p='';
			}
		}
 
		switch ($p) {
			case "subscribe":
				$PageData['button']=$PluginGlobals['SubButton'];
				echo SubscribePage($PHPlist,$SubscrPageID,$PluginGlobals,$PageData,$uidData);
				break;
			case "preferences":
				$PageData['button']=$PluginGlobals['PrefButton'];
				echo Preferences($PHPlist,$SubscrPageID,$PluginGlobals,$PageData,$uidData);
				break;
			case "forward":
				echo $PluginGlobals['PageNotAvailableMsg']; #todo
				break;
			case "confirm":
				echo Confirm($PHPlist,$uidData,$PageData,$PluginGlobals);
				break;
			case "unsubscribe":  
				echo UnsubscribePage($PHPlist,$PluginGlobals,$PageData,$uidData);
				break;
			default:
				echo MainPage($PHPlist,$PluginGlobals);
		} # end of switch
	
		closePage(); # let's finish the plugin page
     }#  end of doSkinVar   
}# end of class NP_PHPlist
 
// things do to before leaving plugin.
// Like displaying default links, restoring connection to nucleus db and do some cleaning up in variables
function closePage() {
	global $PluginGlobals,$MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE,$MYSQL_PASSWORD,$PHPlist;
 
	// Put the default links at the bottom of the page included in <div id="BasicPHPmailLinks"></div> tag
	echo '<br><br><div id="BasicPHPmailLinks">';
	echo '<a href="'.$PluginGlobals['BaseUrl'].'">'.$PluginGlobals['subLink'].'</a>';
	echo'<br>';
	echo '<a href="'.$PluginGlobals['BaseUrl'].'?p=unsubscribe" >'.$PluginGlobals['UnsubLink'].'</a>';
	echo '</div><br><br>';
 
	//check if PHPlist is using same database as nucleus
	// if not reconnect to nucleus so rest of page can be properly displayed
	if ($MYSQL__DATABASE<>$PHPlist->database_name) { #using different database, let's reconnect for nucleus
   $reconnect = MDB2::factory("mysql://$MYSQL_USER:$MYSQL_PASSWORD@$MYSQL_HOST/$MYSQL_DATABASE");
    if (MDB2::isError($reconnect)) die($reconnect->getMessage());
    }
    //clean up some variables
	unset($PHPlist); 
	if(isset($reconnect)) unset($reconnect);
	unset($PluginGlobals);
} #end of closePage
 
function Preferences($PHPlist,$SubscrPageID,$PluginGlobals,$PageData,$uidData) {
 
	if (isset($_POST["email"]) ) { #subscribe data found
 
		$html = '';
		//
 
		if ($_POST["email"]<>$uidData['email']) { #user changed the e-mail address
			//first unsubscribe user silently (no goodbye E-mail will be send)
			$nill=UnsubscribePage($PHPlist,$PluginGlobals,$PageData,$uidData,true);
 
			// resubscribe user silently ( subscribe function will not send any e-mails)
			$nill=SubscribePage($PHPlist,$SubscrPageID,$PluginGlobals,$PageData,$uidData,true);
			$uidData_old=$uidData;
			$uidData=$PHPlist->getUserData($_POST["email"]);
			$html.= $PluginGlobals['AddressChanged'];
			SendEmail($PHPlist,$PageData,$uidData,$PluginGlobals,'Reconfirm'); # send a reconfirm request to new e-mail adres
			SendEmail($PHPlist,$PageData,$uidData_old,$PluginGlobals,'NoticeOld'); # send a notice to the old one
			return $html;
		}
		if (isset($_POST['htmlemail'])) {
			$htmlemail=$_POST['htmlemail'];
		} else{
			$htmlemail='0';
		}
		$UserData = $uidData; 
 
		// manage list subscription
		$AllLists= $PHPlist->getAllLists();
		$SubscribedLists = $PHPlist->getListsByEmail($uidData['email']);
		$SignupLists = $_POST['list'];
 
		foreach ($_POST['listname'] as $FormListId => $PrefList) { #Let's check all the listed lists in the form
			$ListAction='nothing';
			foreach ($SignupLists as $signuplistid =>$signuplist) { #Let's check if any list is checked for signup
				if (($signuplist =="signup" && $FormListId==$signuplistid)) $ListAction='subscribe'; # found a list to subscribe
			}
			foreach ($SubscribedLists as $ListSubscription) { #let's check with the lists that the user is already subscripted to
				if ($FormListId==$ListSubscription) { # found that user is already subscripted to list
					if ($ListAction=='subscribe') $ListAction='skip';
					if ($ListAction=='nothing') $ListAction='unsubscribe';
				}
			}
 
			switch ($ListAction) {
				case "skip":
					break;
				case "subscribe":
					$PHPlist->subscribe($uidData['email'],$FormListId);
					$SubscriptionChanged=true;				
					break;
				case "unsubscribe":
					$PHPlist->unsubscribe($uidData['email'],$FormListId);
					$SubscriptionChanged=true;
					break;
				default:
			}
		}
 
		$SubscribedLists = $PHPlist->getListsByEmail($uidData['email']);
		if (count($SubscribedLists)==0) { # user isn't subscripted to any list => so we unsubscribe user 
			$html .= " Door de wijziging in je voorkeuren ben je bij geen enkele nieuwsbrief aangemeld.<BR>
				We verwerken het wijzigen van je voorkeuren dan ook als een algemene afmelding.<BR>";
			$html .= UnsubscribePage($PHPlist,$PluginGlobals,$PageData,$uidData);
			return $html;
		}
 
		$attributeID = $_POST['attributeID'];
		if (is_array($attributeID)) {
			foreach ($attributeID as $keyID => $value) {
				$AttributeStr[$value]=$_POST['attribute'.$keyID];
			}
		}
 
		$PHPlist->setAttributes($UserData['email'],$AttributeStr,true);
		SendEmail($PHPlist,$PageData,$UserData,$PluginGlobals,'changed');
		$html.=$PluginGlobals['PrefDone'];
 
	} else { # no email adres found, so build form
		//write the javascript functions
		$html= $PluginGlobals['PrefWelcome'];
		$html .= showForm($PHPlist,$SubscrPageID,$PluginGlobals,$PageData,$uidData);
	}
	return $html;
}
 
// Show the form, either as subscribtion or as update of preference
function showForm($PHPlist,$SubscrPageID,$PluginGlobals,$PageData,$uidData) { 
 
	//write the javascript functions
	$html .='<script language="Javascript" type="text/javascript">
 
		function checkform() {
		  for (i=0;i<fieldstocheck.length;i++) {
			if (eval("document.subscribeform.elements[\'"+fieldstocheck[i]+"\'].value") == "") {
			  alert("'.$PluginGlobals['ReqQuestion'].'"+fieldnames[i]);
			  eval("document.subscribeform.elements[\'"+fieldstocheck[i]+"\'].focus()");
			  return false;
			}
		  }
 
  				if(! compareEmail())
  				{
    				alert("'.$PluginGlobals['differentEmails'].'");
	    			return false;
  				}
  				return true;
			}
 
			var fieldstocheck = new Array();
			var fieldnames = new Array();
 
			function addFieldToCheck(value,name) {
  				fieldstocheck[fieldstocheck.length] = value;
  				fieldnames[fieldnames.length] = name;
			}
 
			function compareEmail()
			{
	  			return (document.subscribeform.elements["email"].value == document.subscribeform.elements["emailconfirm"].value);
			}
			</script>';
 
	$html .= '<form method=post name="subscribeform" action="'.$PluginGlobals['BaseUrl'].'?'.$_SERVER['QUERY_STRING'].'"><table border=0>
			<tr><td><div class="required">E-mail</div></td>
				<td class="attributeinput"><input type=text name=email value="'.$uidData['email'].'" size="40">
					<script language="Javascript" type="text/javascript">addFieldToCheck("email","E-mail");</script></td></tr>';
	$ConfirmEmailField=$PageData['emaildoubleentry'];
		if (($ConfirmEmailField=="yes")) {
	  		$html.='			<tr><td><div class="required">Confirm e-mail</div></td>
  						<td class="attributeinput"><input type=text name=emailconfirm value="" size="40">
  						<script language="Javascript" type="text/javascript">addFieldToCheck("emailconfirm","Bevestig e-mail");</script></td></tr>';		
		} 
 
		$html .='<tr><td colspan=2>';
  		$html .= SubEmailTypeField($PageData,$PluginGlobals,$uidData) ;
 
  		$html .='
 
	      			</td></tr>';
	    // so let's display the attributes  	
	    $Attributes=$PageData['attributes'];
	    if (!empty($Attributes)) {
			$Attributes = sv2array($Attributes,'+'); # find the needed atributes
			$i = 0;
			foreach ($Attributes as $AttributeID) { # make an array of the attributes data from the subscribepage data record
			$pageAttribute[$i]= sv2array( $PageData['attribute'.sprintf("%03d",$AttributeID)],'###');	
				$i = $i + 1;
			}
			$pageAttribute=sortAttribute($pageAttribute); # sort on the third key in the 2D array this is [][2]
			foreach ($pageAttribute as $attrib) { #now show them in order
				if (isset($_GET['p']) && $_GET['p']=='preferences') {
					$defValue=$PHPlist->getAttributeValues($attrib[0],$uidData['id']);
				} else {
					$defValue='';
				}
				$html .= ShowAttribute($attrib[0],$PHPlist,$PageData,$defValue);
			}
		}
 
		$html .='			</table><br>
					<p>'.$PluginGlobals['ListingHeader'].'</p>
					<ul class="list">';
 
		$lists = sv2array( $PageData['lists'],',');
 
		$html .= ShowLists($lists,$PHPlist,$uidData);
		$html .='<br>';
		$html .= '<input type=submit name="subscribe" value="'.$PageData['button'].'" onClick="return checkform();">';
    	$html .='</form>';
	return $html;
}
 
// This plugin can use 2 databases, so it can loose connection to the nucleus db
// This function checks if it is connected to the nucleus db, so it can log the message to the nucleus actionlog
// if it is not connected to nucleus, it will temporarely connect to nucleus and then switch back to PHPlist
function addLog($lvl,$message) {
	global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE,$MYSQL_PASSWORD,$ACTIONLOG,$PluginGlobals;
 
	$PHPlist = new phplist($PluginGlobals['PHPlistPath']);
	if ($MYSQL_DATABASE<>$PHPlist->database_name) { #conected to a different database, need to connect to nucleus
	   $reconnect = DB::connect("mysql://$MYSQL_USER:$MYSQL_PASSWORD@$MYSQL_HOST/$MYSQL_DATABASE");
		if (DB::isError($reconnect)) die($reconnect->getMessage());
	}				
	ACTIONLOG::add($level,'{NP_PHPlist} '.$message); # log message
	if ($MYSQL__DATABASE<>$PHPlist->database_name) { #restore connection for PHPlist  functions
		$PHPlist = new phplist($PluginGlobals['PHPlistPath']);
		unset($reconnect);
	}
	unset($PHPlist);
} # end of addLog function
 
// Function to display the confirm pages (it returns HTML code)
function Confirm($PHPlist,$uidData,$PageData,$PluginGlobals) {
 
	$ListConfig=$PHPlist->loadConfig();
	$subscribeurl=str_replace('[WEBSITE]',$ListConfig['website'],$ListConfig['subscribeurl']);
	if (!is_array($uidData)) {
		$html = ''; /*"Sorry, de gebruiker is niet bij ons bekend. Het bevestigen van uw aanmelding is niet gelukt.<BR>
				Is de url wel volledig ?<br>
				Probeert u het anders nog een keer om aan te melden via deze <a href='".$subscribeurl."'>link</a>"; #todo */
		addLog(ERROR, "Need html message in function confirm");
 
	} else {
		$Confirmed= $PHPlist->ConfirmUser($uidData['uniqid']);
		if ($Confirmed) { # confirmation is succes -> send E-mail to user with details
			SendEmail($PHPlist,$PageData,$uidData,$PluginGlobals,'ConfirmSub');
			$html = str_replace('[EMAIL]',$uidData['email'],$PluginGlobals['ConfirmedMessage']);
			if ($PluginGlobals['AddtoNewbiesList']=='yes') {
				$ListId=$PHPlist->getListbyName($PluginGlobals['NewbieList']);
				$PHPlist->subscribe($uidData['email'],$ListId);	
			}
		} else { #confirmation failed -> add to actionlog, and display warning
			$html=str_replace('[EMAIL]',$uiData['email'],$PluginGlobals['confirmFailed']);
			addLog(INFO,"Confirmation of user `".$uidData['email']."` failed. uid = `".$uidData['uniqid']."`");
		}
	}
	return $html;
} #end of Confirm function
 
// Function to display the mainpage of the plugin, it is a list of active subscribepages from PHPlist
function MainPage($PHPlist,$PluginGlobals) {
 
	$Pages = $PHPlist->getSPages(true); #find active subscribe pages in PHPlist
 
	if (is_array($Pages)) {
		$html =$PluginGlobals['WelcomeMsgSelectPage'].'<br><br>';
		foreach ($Pages as $Page) {
			$html .= '<a href="'.$PluginGlobals['BaseUrl'].'?p=subscribe&id='.$Page['id'].'">'.$Page['title'].'</a><BR>';
		}
	} else
	{
		$html='No pagedata found in PHPList, did you set up any subscribepages and are they active ?<BR>'; #todo
	}	
	return $html;
} # end of MainPage function
 
// function for the subscribe pages
// The subscription form will be displayed if there is no data to subscribe in the $_POST variables
// function will return the page as a HTML string
function SubscribePage($PHPlist,$SubscrPageID,$PluginGlobals,$PageData,$uidData,$silent=false){
 
	if (isset($_POST["email"]) ) { #subscribe data found 
		$html = '';
		$subscribed = false;
		if (isset($_POST['htmlemail'])) {
			$htmlemail=$_POST['htmlemail'];
		} else{
			$htmlemail='0';
		}
		//check if e-mail addres is known
		$userId=$PHPlist->email2id($_POST['email']);
		if ($userId==false) { #user not found => doesn't exist
			$userId=$PHPlist->createUser($_POST["email"],$SubscrPageID,$htmlemail);
		} 
		$UserData = $PHPlist->getUserData($_POST["email"]);
 
		$AllLists= $PHPlist->getAllLists();
		$AvailableLists = $_POST['list'];
		foreach ($AvailableLists as $listid =>$signuplist) {
 
			if (($signuplist == "signup")) {
				$PHPlist->subscribe($UserData['email'],$listid);						
				$subscribed=true; 	
			}		
		}
		$attributeID = $_POST['attributeID'];
		if (is_array($attributeID)) {
			foreach ($attributeID as $keyID => $value) {
				$AttributeStr[$value]=$_POST['attribute'.$keyID];
			}
		}
 
		$PHPlist->setAttributes($UserData['email'],$AttributeStr,true);
		if (!$silent) SendEmail($PHPlist,$PageData,$UserData,$PluginGlobals,'AskConfirm');
 
		if ($subscribed) {
			if($UserData['blacklisted']=='1') {
				$html = str_replace('EMAIL',$Userdata['email'],$PluginGlobals['BlackListedWarning']);
			} else {
				$html =$PageData['thankyoupage'];
			}
		} else {
			addLog(ERROR,'No lists are selected in settings of the subscribepage (PHPlist');
			$html =$PluginGlobals['WarnWebmasterMsg']; 
		} 
 
 
	} else { # no subscribe data found, so build form 
		$uidData['htmlemail']=(($PageData['htmlchoice']=='checkforhtml') || ($PageData['htmlchoice']=='radiohtml'));
		$uidData['email']='';
 
		$html = $PageData['intro'];
 
		$html .= showForm($PHPlist,$SubscrPageID,$PluginGlobals,$PageData,$uidData);		
	}
 
	return $html;		
} # end of SubscribePage
 
 
// E-mail send function, for all the e-mails that the plugin needs to send.
function SendEmail ($PHPlist,$PageData,$uidData,$PluginGlobals,$EmailType) { 
 
	//define some basic info
	$confirmUrl=$PluginGlobals['BaseUrl'].'?p=confirm&uid='.$uidData['uniqid'];
 
	$ListConfig=$PHPlist->loadConfig();
	$subscribedlists = $PHPlist->getListsByEmail($uidData['email']);
	$Lists = '';
	foreach ($subscribedlists as $slist) {
		$Listdata = $PHPlist->getList($slist);
		$Lists .= '
		- '.$Listdata['name'];
	}
	$to= $uidData['email'];
	$from= str_replace('[WEBSITE]',$ListConfig['website'],$ListConfig['message_from_name'])." <". $ListConfig['message_from_address'].">";
	$replyto = $ListConfig['message_replyto_address'];
	$domain = $ListConfig['domain'];
	$website = $ListConfig['website'];
	$preferencesurl=str_replace('[WEBSITE]',$website,$ListConfig['preferencesurl'].'&uid='.$uidData['uniqid']);
	$subscribeUrl=str_replace('[WEBSITE]',$ListConfig['website'],$ListConfig['subscribeurl']);
	$subscribeUrl=str_replace('[WEBSITE]',$ListConfig['website'],$ListConfig['subscribeurl']);
	$unsubscribeurl=str_replace('[WEBSITE]',$ListConfig['website'],$ListConfig['unsubscribeurl'].'&uid='.$uidData['uniqid']);
	$from = str_replace('[DOMAIN]',$domain,$from);
	$envelope_from = str_replace('[DOMAIN]',$domain,$ListConfig['message_from_address']);	
	$replyto = str_replace('[DOMAIN]',$domain,$replyto);	
	$headers = 'From: '.$from ."\r\n";
	$headers .='Reply-To: '. $replyto . "\r\n"; 
	$headers .='X-Mailer: PHP/' . phpversion()."\r\n";
	$headers .='X-NP_PHPMailList_uid: '.$UidData['uniqid']."\r\n";
	$headers .='X-NP_PHPMailList_version: '.$PluginGlobals['version']."\r\n";
	$headers .='X-NP_PHPMailList_admin_address: webmaster@'.$domain."\r\n";	
 
	//e-mail headers for administrator
	$admin_headers='From: '.$from."\r\n";
	$admin_headers .='Reply-To: '. $replyto . "\r\n"; 
	$admin_headers .='X-Mailer: PHP/' . phpversion()."\r\n";
	$admin_headers .='X-NP_PHPMailList_version: '.$PluginGlobals['version']."\r\n";
	$admin_sign="\r\n------------------------------------\r\n";
	$admin_sign.="The admin interface can be found at: ".$PluginGlobals['BaseUrl']."admin/ \r\n";
 
	switch ($EmailType) {
		case 'AskConfirm':
			$subject = $ListConfig['subscribesubject:'.$PageData['id']];
			$body=$ListConfig['subscribemessage:'.$PageData['id']];
			$headers .='X-NP_PHPMailList_Conf_url: '.$confirmUrl."\r\n";
			$headers .='X-NP_PHPMailList_EmailType: '.$EmailType."\r\n";
			$admin_subject="PHPList user subscription \r\n";
			$admin_body="A user has subscribed to PHPList.\r\n";
			$admin_body.="\r\n";
			$admin_body.="The details are:\r\n";
			$admin_body.="	user:  ".$uidData['email']."\r\n";
 
 
			break;
		case 'ConfirmSub';
			$headers .='X-NP_PHPMailList_EmailType: '.$EmailType."\r\n";		
			$subject = $ListConfig['confirmationsubject:'.$PageData['id']];
			$body=$ListConfig['confirmationmessage:'.$PageData['id']];	
			$admin_subject="PHPList user confirmed subscribtion.\r\n";
			$admin_body="A user has confirmed it's subscribtion.\r\n";
			$admin_body.="      e-mail address user:".$uidData['email']."\r\n";
			break;
		case 'GoodBye':
			$headers .='X-NP_PHPMailList_EmailType: '.$EmailType."\r\n";		
			$subject = $ListConfig['unsubscribesubject'];
			$body=$ListConfig['unsubscribemessage']; 
			$admin_subject="PHPList user unsubscribed.\r\n";
			$admin_body="A user has unsubscribed from PHPList mailingsystem.\r\n";
			$admin_body.="      e-mail address user:".$uidData['email']."\r\n";
			break;
		case 'changed':
			$headers .='X-NP_PHPMailList_EmailType: '.$EmailType."\r\n";		
			$subject = $ListConfig['updatesubject'];
			$body=$ListConfig['updatemessage']; 	
			$admin_subject="PHPList user subscription changed.\r\n";
			$admin_body="A user made changes in its profile in  PHPList mailingsystem.\r\n";
			$admin_body.="      e-mail address user:".$uidData['email']."\r\n";
			break;
		case 'Reconfirm':
			$headers .='X-NP_PHPMailList_EmailType: '.$EmailType."\r\n";		
			$subject = $ListConfig['updatesubject'];
			$body=$ListConfig['emailchanged_text']; 
			break;
		case 'NoticeOld':
			$headers .='X-NP_PHPMailList_EmailType: '.$EmailType."\r\n";		
			$subject = $ListConfig['updatesubject'];
			$body=$ListConfig['emailchanged_text_oldaddress']; 	
			break;
		default:
	}
 
	// let's replace some template variables
	$body=str_replace('[CONFIRMATIONURL]',$confirmUrl,$body);
	$body=str_replace('[LISTS]',$Lists,$body);				
	$body=str_replace('[PREFERENCESURL]',$preferencesurl,$body);
	$body=str_replace('[LISTS]',$Lists,$body);	
	$body=str_replace('[SUBSCRIBEURL]',$subscribeUrl,$body);
	$body=str_replace('[PREFERENCESURL]',$preferencesurl,$body);
	$body=str_replace('[CONFIRMATIONINFO]','',$body);
	$body=str_replace('[USERDATA]','',$body);	
	$body=str_replace('[DOMAIN]',$domain,$body);	
	$body=str_replace('[UNSUBSCRIBEURL]',$unsubscribeurl,$body);	
 
	// uncomment these next 4 lines, to see the e-mail that will be send out
#	echo '<br>';	
#	echo nl2br(htmlentities($headers)).'<br>';
#	echo nl2br(htmlentities($subject)).'<br>';
#	echo nl2br(htmlentities($body)).'<br>';
 
	// Let's send the e-mail	
	mail($to,$subject,$body,$headers,"-r ".$envelope_from);
 
	//Let's notify the administrator	
	$admin_body.=$admin_sign;  # sign the e-mail with admin URL
	//Check if Administrator needs to be notified (some basic logic)
	$notifyAdmin=($PluginGlobals['AlwaysNotifyAdmin']=='yes');
	$notifyAdmin = ($notifyAdmin || ($EmailType=='changed' && ($PluginGlobals['notifyofchanges']=='yes')));
	$notifyAdmin = ($notifyAdmin || ($EmailType=='AskConfirm' && ($PluginGlobals['NotifyofSubscribe']=='yes')));	
	$notifyAdmin = ($notifyAdmin || ($EmailType=='ConfirmSub' && ($PluginGlobals['notifyofconfirm']=='yes')));	
	$notifyAdmin = ($notifyAdmin || ($EmailType=='GoodBye' && ($PluginGlobals['notifyofunsubscribe']=='yes')));	
	if ($notifyAdmin) mail($PluginGlobals['AdminAddress'],$admin_subject,$admin_body,$admin_headers,"-r ".$envelope_from);
} # enfo SendEmail function
 
 
function sortAttribute ($arr) {
 
	function cmp($a, $b)
	{	
	   if ($a['2'] == $b['2']) {
			return 0;
			}
		return ($a['2'] < $b['2']) ? -1 : 1;
	}
 
	uasort($arr, "cmp");	
	return $arr;
} # end of sortAttribute
 
function ShowAttribute ($AttribID,$PHPlist,$PageData,$default) {
 
	$AttributeData = $PHPlist->getAttributeData($AttribID); # get the attribute's data
 
	$AttributeSettings= sv2array($PageData['attribute'.sprintf("%03d",$AttribID)],'###'); # get the default values
	// fill in the default values 
	$AttributeData['required'] = $AttributeSettings['3'];
	$AttributeData['default_value'] = $AttributeSettings['1'];
	if (!empty($default)) $AttributeData['default_value']=$default;
	// display the attribute
	switch ($AttributeData['type']) {
		case 'textline':
			$html .= '
						<tr><td>';
			if ($AttributeData['required']=='1') {
				$html .= '<div class="required">'.$AttributeData['name'].'</div>';
			} else {
				$html .= '<div>'.$AttributeData['name'].'</div>';			
			}
			$html .= '</td><td class="attributeinput">';
			$html .= '<input type =text name ="attribute'.$AttributeData['id'].'" class="attributeinput" size="40" value="'.$AttributeData['default_value'].'">';
			if ($AttributeData['required']=='1') {
				$html .= '<script language="Javascript" type="text/javascript">addFieldToCheck("attribute'.$AttributeData['id'].'","'.$AttributeData['name'].'");</script>';
			}
			break;
		case 'checkbox':
			$html .= '
					<tr><td colspan=2>';
			$html .= '<input type="checkbox" name="attribute'.$AttributeData['id'].'" value ="on" class="attributeinput">';
			if ($AttributeData['required']=='1') {
				$html .= '<span class="required">'.$AttributeData['name'].'</span>';
			} else {
				$html .= '<span>'.$AttributeData['name'].'</span>';			
			}			
 
			break;
		default:
			addLog(ERROR,'WARNING: type '.$AttributeData['type'].' for field '.$AttributeData['name'].' is not supported.');
	}
	$html .= '<input type=hidden name="attributeID['.$AttributeData['id'].']" value="'.$AttributeData['name'].'"/>';
	$html .= '</td></tr>';
	return $html;
} # end of ShowAttribute
 
 
// analyses a string with a defined seperator and returns it in an array.
function sv2array($str,$seperator) {
    $str = trim($str);
    $str = trim($str,$seperator);
    $str = preg_replace('/(\s*,\s*)+/', $seperator, $str);
    $array = explode($seperator, $str);
    return $array;
} # end of sv2array
 
// generates HTML code of lists that are included in a subscribtion page
function ShowLists($lists,$PHPlist,$uidData) {
 
	foreach ($lists as $list) {
 
		$listData=$PHPlist->getList($list);
		$checkStr='';
		if (isset($_GET['p']) && ($_GET['p']=='preferences')) { #userdata is detected..... hmmm we are updating
			$SelLists=$PHPlist->getListsByEmail($uidData['email']);
			if (is_array($SelLists)) { # user is subscribed to more then one list
				foreach ($SelLists as $selList) { # let's check if the user is subscribed to the list we are showing
					if ($selList==$list) { # yup, user is subscribed
						$checkStr='checked';
						break; # leave the foreach... loop
					}
				}				
			}
			if ($SelLists==$list) $checkStr='checked'; # user is only subscribed to one list, is it the sameone we are showing ?
		}
		$html .= '<li class="list"><input type="checkbox" name="list[' .$list . ']" value=signup  '.$checkStr.' /><b>'.$listData['name'].'</b>
			<div class="listdescription"><input type=hidden name="listname['.$list . ']" value="' . $listData['name'] . '"/>
				'.$listData['description'].'</div></li>';			
	}
 
	return $html;
} # end of Showlists function
 
// Generates the HTML code to display the E-mail type question in the subscribeform
function SubEmailTypeField($PageData,$PluginGlobals,$uidData) { 
 
	$FieldType=$PageData['htmlchoice'];
	$html='<span class="attributeinput">';
 
	switch ($FieldType) {
		case 'textonly': #don't offer choice, text default
			$html = '<input type=hidden name="htmlemail" value="0">';
		break;
		case 'htmlonly': #don't offer choice, html default
			$html = '<input type=hidden name="htmlemail" value="1">';
		break;
		case 'checkforhtml': #offer checkbox for html
			$html = '<input type=checkbox name="htmlemail" value="'.$uidData['htmlemail'].'" /></span>
						<span class="attributename">'.$PluginGlobals['textPreferHTMLEmail'].'</span>';
		break;
		case 'checkfortext': #offer checkbox for text
			$html = '<input type=checkbox name="textemail" value="'.$uidData['htmlemail'].'" /></span>
						<span class="attributename">'.$PluginGlobals['textPreferPlainEmail'].'</span>';
		break;
		case 'radiotext':
			$html .='<span class="attributeinput"><input type=radio name="htmlemail" value="'.$uidData['htmlemail'].'" checked /></span>
					<span class="attributename">Text</span>
					<span class="attributeinput"><input type=radio name="htmlemail" value="'.$uidData['htmlemail'].'"  /></span>
					<span class="attributename">HTML</span>';
		break;
		case 'radiohtml':
			$html .='<span class="attributeinput"><input type=radio name="htmlemail" value="'.$uidData['htmlemail'].'" /></span>
					<span class="attributename">Text</span>
					<span class="attributeinput"><input type=radio name="htmlemail" value="'.$uidData['htmlemail'].'"  checked /></span>
					<span class="attributename">HTML</span>';
		break;		
		Default:
	}
	$html .= '</span>';
	return $html;	
}# end of SubEmailTypeField
 
// Generates HTML code to display the unsubscription process
function UnsubscribePage($PHPlist,$PluginGlobals,$PageData,$uidData,$silent=false){  
 
		if (is_array($uidData)) {
			$useremail = $uidData['email'];
			$result=$PHPlist->unsubscribe($useremail);
		}  elseif (isset($_POST["unsubscribe"]) && isset($_POST["unsubscribeemail"])) { #unsubscribe info found in Postdata 
			$useremail = $_POST['unsubscribeemail'];
			if ($PHPlist->isKnown($useremail,'email')) {
				$uidData=$PHPlist->getUserData($useremail);
				$result=$PHPlist->unsubscribe($useremail);
			} else $result=2;
		} else $result=3;
	switch ($result) {
		case false:
			$html =  'Het is niet gelukt om het adres '. $useremail . ' te verwijderen.<BR>
						(Waarschijnlijk is dit adres niet bij ons bekend.) <BR>';
			break;
		case 1:
			$PHPlist->blacklistUser($useremail);
			if (!$silent) SendEmail($PHPlist,$PageData,$uidData,$PluginGlobals,'GoodBye');
			$html= str_replace('[EMAIL]',$useremail,$PluginGlobals['goodbyeMsg']);
			break;
		case 2:
			$html = 'Het opgegeven email adres ( '.$useremail. ' ) is niet bij ons bekend.<br>';
			break;
		case 3:
			$html= $PluginGlobals['UnsubTitle'].'<BR>';
			$html = $html.'<form method=post ><table>
  						<tr><td>'.$PluginGlobals['UnsubEmailLabel'].'</td><td colspan=3><input type=text name="unsubscribeemail" value="" size=40></td></tr>
  						</table><input type=submit name=unsubscribe value="'.$PluginGlobals['UnsubscribeButton'].'"></form>';			
			break;
		default:
 
	}
	return $html;
} # end of UnsubscribePage
 
 
 
// The PHPlist functions
// working for PHPlist v2.10.4
class phpList {
 
  var $listdb;
  var $tablePrefix;
  var $userTablePrefix;
  var $database_name;
 
  function phpList($pathToPhpList=NULL) {
 
    // if no path specified, assume this file is in thephplist dir
    if (empty($pathToPhpList)) $pathToPhpList = dirname(__FILE__);
 
    // Include your phpList config.php file here
    require($pathToPhpList."/config/config.php");
    $this->tablePrefix = $table_prefix;
    $this->userTablePrefix = $usertable_prefix;
 
    // Setup and connect to the database (this only needs to be done once per session
    // You don't need to change anything here.
    require_once("MDB2.php");
 
    $this->listdb = MDB2::factory("mysql://$database_user:$database_password@$database_host/$database_name");
    $this->database_name=$database_name;
    if (MDB2::isError($this->listdb)) die($this->listdb->getMessage());
    $this->listdb->setFetchMode(MDB2_FETCHMODE_ASSOC);
  } # end of phpList
 
	// Load all configuration data from config table
	function loadConfig(){
 
		$sql = "SELECT * FROM ".$this->tablePrefix . "config";
		$Data = $this->listdb->queryAll($sql);
		$ConfigList=false;
		if (!empty($Data) && is_array($Data)) {
			// let's reformat the array to a structure like item.value
			$ConfigList = array();
			foreach ($Data as $Record) { 
				$key= $Record['item'];
				$value=$Record['value'];
				$ConfigList[$key]=$value;
			}
		}
		return $ConfigList;	
	 } # end of function loadConfig
 
 
  // takes a php mailing list id
  // returns an array of email addresses subscribed to this list
  function getSubscriberIds($listId) {
    $sql = "SELECT userid
              FROM ".$this->tablePrefix."listuser
             WHERE listid='".addslashes($listId)."'";
    $userIds = $this->listdb->queryCol($sql);
    return($userIds);
  } # end of getSubscribersIds
 
 
	function setAttributes($userIdOrEmail,$attributes,$overwrite=false) {
		if (is_numeric($userIdOrEmail)) $userId = $userIdOrEmail;
		else $userId = $this->email2id($userIdOrEmail);
		if (empty($userId)) return(false);
 
		// if attributes were specified, try and map them to attribute ids in the db
		$attributeIds = array();
		if (is_array($attributes)) {
		  foreach ($attributes as $name=>$value) {
			$sql = "SELECT id FROM ".$this->userTablePrefix."attribute WHERE name='".addslashes($name)."'";
			$id = $this->listdb->queryOne($sql);
			if ($id) $attributeIds[$name] = $id;
		  }
		}
		// insert attributes (if any) for the user
		foreach ($attributeIds as $name=>$id) {
		  $value = $attributes[$name];
		  // special case for countries - get the country id instead of using the name
		  if (strtolower($name)=="country") {
			$sql = "SELECT id FROM ".$this->tablePrefix."listattr_countries WHERE name='".addslashes($value)."'";
			$value = $this->listdb->queryOne($sql);
			// if the country name wasn't found, skip
			if (empty($value)) continue;
		  }
		  if ($overwrite) $sql = "REPLACE INTO ";
		  else $sql = "INSERT IGNORE INTO ";
		  $sql .= $this->userTablePrefix."user_attribute (attributeid,userid,value) values ('".addslashes($id)."','".addslashes($userId)."','".addslashes($value)."')";
		  $result = $this->listdb->query($sql);
		}
		return(true);
	} # end of setAttributes
  
	 // check if given id is known by PHPlist
	function isKnown($id,$type) {
		if (empty($id)) return(false);
		if (empty($type)) return (false);
 
		switch($type) {
			case 'uniqid':
				$sql="SELECT `uniqid` FROM ".$this->userTablePrefix."user WHERE `uniqid`='".$id."'";
				break;
			case 'pageID':
				$sql="SELECT `id` FROM ".$this->tablePrefix."subscribepage WHERE `id`=".$id;  		
				break;
			case 'email':
				$sql="SELECT `email` FROM ".$this->userTablePrefix."user WHERE `email`='".$id."'";
				break;
			default:
		}
		$data=$this->listdb->queryOne($sql); # check db
		return ($data==$id); # if the db is talking about the same id, then we know the ID
	} # end of isKnown
	
	function ConfirmUser($uid) {
		 $sql = 'UPDATE `'.$this->userTablePrefix.'user` SET `confirmed`=1 , `blacklisted`=0 WHERE `uniqid`=\''.$uid.'\'';
		$result = $this->listdb->query($sql);
		$sql = "SELECT email FROM ".$this->userTablePrefix."user WHERE `uniqid`='".$uid."'";
		$email =$this->listdb->queryOne($sql);
 
		if (!empty($email)) {
			$sql = "DELETE FROM `".$this->userTablePrefix."blacklist` WHERE `email`='".$email."'";
		$result = $this->listdb->query($sql);
			$sql = "DELETE FROM `".$this->userTablePrefix."blacklist_data` WHERE `email`='".$email."'";
		$result = $this->listdb->query($sql);
		}
		 //check if success
		 $sql = 'SELECT * FROM `'.$this->userTablePrefix.'user` WHERE `uniqid`=\''.$uid.'\'';
		$UserData = $this->listdb->queryRow($sql);
		$result = ($UserData['confirmed']=='1' && $UserData['uniqid']==$uid);
		return $result;
	}# end of ComfirmUser
 
  function email2id($email) {
    $sql = "SELECT id FROM ".$this->userTablePrefix."user WHERE email='".addslashes($email)."'";
    $userId = $this->listdb->queryOne($sql);
    if (empty($userId)) return(false);
    return($userId);
  } # end of email2id
  
  function id2email($userId) {
    $sql = "SELECT email FROM ".$this->userTablePrefix."user WHERE id='".addslashes($userId)."'";
    $email = $this->listdb->queryOne($sql);
    if (empty($email)) return(false);
    return($email);
  } # end of id2email
 
   function id2uid($userId) {
    $sql = "SELECT uniqid FROM ".$this->userTablePrefix."user WHERE id='".addslashes($userId)."'";
    $uid = $this->listdb->queryOne($sql);
    if (empty($uid)) return(false);
    return($uid);
  } # end of id2uid
 
 
  function createUser($email,$SubscrPageID,$htmlemail,$attributes=false) {
    // create a unique id for the user (and make sure it's unique in the database)
    do {
      $uniqueId = md5(uniqid(mt_rand(0,1000).$email));
      $sql = "SELECT COUNT(*) FROM ".$this->userTablePrefix."user WHERE uniqid='".addslashes($uniqueId)."'";
      $exists = $this->listdb->queryOne($sql);
    } while ($exists);
 
    // insert the user
    $sql = "INSERT INTO ".$this->userTablePrefix."user (email,entered,confirmed,uniqid,htmlemail,subscribepage) values ('".addslashes($email)."',now(),0,'".addslashes($uniqueId)."','".$htmlemail."','".addslashes($SubscrPageID)."')";
    $result = $this->listdb->query($sql);
 
    // add a note saying we imported them manually
    $sql = "INSERT INTO ".$this->userTablePrefix."user_history (userid,date,summary) values('".addslashes($userId)."',now(),'Import via phpList Class')";
    $result = $this->listdb->query($sql);
 
    // get the new user id
    $sql = "SELECT id FROM ".$this->userTablePrefix."user WHERE uniqid='".addslashes($uniqueId)."'";
    $userId = $this->listdb->queryOne($sql);
 
    // set attributes if any
    if ($attributes) $this->setAttributes($userId,$attributes);
 
 
    return($userId);
  } # end of createUser
 
  // subscribe a user to a list - accepts either a user id or an email addy
  // user must exist
  function subscribe($userIdOrEmail,$listId) {
    if (is_numeric($userIdOrEmail)) $userId = $userIdOrEmail;
    else $userId = $this->email2id($userIdOrEmail);
    if (empty($userId)) return(false);
 
    // subscribe them to the specified list
    $sql = "INSERT IGNORE INTO ".$this->tablePrefix."listuser (userid,listid,entered) VALUES ('".addslashes($userId)."','".addslashes($listId)."',now())";
    $result = $this->listdb->query($sql);
 
    // add a note saying we subscribed them manually
    $sql = "INSERT INTO ".$this->userTablePrefix."user_history (userid,date,summary) values('".addslashes($userId)."',now(),'Subscribed to list ".addslashes($listId)." via phpList Class')";
    $result = $this->listdb->query($sql);
 
    return(true);
  } # end of subscribe
 
	function blacklistUser($userIdOrEmail) {
 
		if (is_numeric($userIdOrEmail)) {
			$userId = $userIdOrEmail;
		   $email=id2email($userid);
		} else { 
			$userId = $this->email2id($userIdOrEmail);
			$email=$userIdOrEmail;
		}
		if (empty($userId)) return(false);
 
 
			// ad them to the blacklist
		$sql = "INSERT IGNORE INTO ".$this->userTablePrefix."blacklist (email,added) values('".$email."',now())";
		$result = $this->listdb->query($sql);    
		$sql = "INSERT IGNORE INTO ".$this->userTablePrefix."blacklist_data (email,name,data) values('".$email."','reason','removed by NP_PHPmaillist')";
		$result = $this->listdb->query($sql); 
		 $sql = 'UPDATE `'.$this->userTablePrefix.'user` SET `blacklisted`=1 WHERE `email`=\''.$email.'\'';
		$result = $this->listdb->query($sql);
	return (true);
	}
 
  // unsubscribe an email addy from the list
  // if no list id provided, unsubscribe the user from all lists
  function unsubscribe($userIdOrEmail,$listId=NULL) {
    if (is_numeric($userIdOrEmail)) {
    	$userId = $userIdOrEmail;
       $email=id2email($userid);
    } else { 
    	$userId = $this->email2id($userIdOrEmail);
    	$email=$userIdOrEmail;
    }
    if (empty($userId)) return(false);
 
    // unsubscribe them   
    $sql = "DELETE FROM ".$this->tablePrefix."listuser
             WHERE userid='".addslashes($userId)."'";
    if ($listId) $sql .= " AND listid='".addslashes($listId)."'";
    $this->listdb->query($sql);
 
    // add a note saying we unsubscribed them manually
    $sql = "INSERT INTO ".$this->userTablePrefix."user_history (userid,date,summary) values('".addslashes($userId)."',now(),'Unsubscribed from list ".addslashes($listId)." via phpList Class')";
    $result = $this->listdb->query($sql);
 
 
    return(true);
  } # end of unsubscribe
 
   // takes a php mailing list id and e-mail address to determine if currently subscribed
  // returns true if subscribed and false if not
  function getSubscriberStatus($userIdOrEmail, $listId) {
    if (is_numeric($userIdOrEmail)) $userId = $userIdOrEmail;
    else $userId = $this->email2id($userIdOrEmail);
    if (empty($userId)) return(false);
 
    $sql = "SELECT userid
              FROM ".$this->tablePrefix."listuser
             WHERE listid='".addslashes($listId)."'
          AND userid = '".addslashes($userId)."'";
 
    $userId = $this->listdb->queryOne($sql);
    if ($this->listdb->queryOne($sql)) return(true);
   else return(false);
  } # end of getsubscriberStatus
  
  // returns an array of all lists
	function getAllLists($id) {
		$sql  = "SELECT id, name, description ";
		$sql .= "FROM ".$this->tablePrefix."list ";
		$sql .= "ORDER BY id ";
		$arrLists = $this->listdb->queryAll($sql);
		return($arrLists);
	} # end of getAllLists
	
	function getActiveLists() {
		$sql  = "SELECT id, name, description ";
		$sql .= "FROM ".$this->tablePrefix."list ";
		$sql .= "WHERE active=".addslashes('1')." ";
		$sql .= "ORDER BY id ";
		$arrLists = $this->listdb->queryAll($sql);
		return($arrLists);
	} # end of getAllLists
	
	function getList($id) {
		$sql  = "SELECT  name, description ";
		$sql .= "FROM ".$this->tablePrefix."list ";
		$sql .= "WHERE id =".addslashes($id);
		$arrLists = $this->listdb->queryRow($sql);	
		return($arrLists);
	} # end of getAllLists	
	
	function getListbyName($name) {
		$sql  = "SELECT  id ";
		$sql .= "FROM ".$this->tablePrefix."list ";
		$sql .= "WHERE name ='".addslashes($name)."'";
		#doDebug($sql,'1184:$getListbyName->sql');
		$arrLists = $this->listdb->queryOne($sql);	
		#doDebug($arrLists,'arrlist');
		return($arrLists);
	} # end of getAllLists		
	
	// Return all data of an PHPlist user.
	function getUserData($userIdOrEmail,$UseUID=false) {
	$sql = "SELECT * ";
	$sql .= "FROM ".$this->userTablePrefix."user ";	
	if ($UseUID) {
		$sql .= "WHERE `uniqid` ='".$userIdOrEmail."'";	
	}else {
		if (is_numeric($userIdOrEmail)) $userId = $userIdOrEmail;
		else $userId = $this->email2id($userIdOrEmail);
		if (empty($userId)) return(false);	
		$sql .= "WHERE id =".addslashes($userId);
	}
	$arrData = $this->listdb->queryRow($sql);
	if (empty($arrData)) return(false);
	return $arrData;
	} #end of getUserData
	
  // return subscribe pages data as an array
	function getPageData($id) {
		$sql  = "SELECT name, data ";
		$sql .= "FROM ".$this->tablePrefix."subscribepage_data ";
		$sql .= "WHERE id =".addslashes($id);
		$arrLists = $this->listdb->queryAll($sql);
		$Data['id']=$id;
		if (is_array($arrLists)) {
			foreach ($arrLists as $Record) {
				$Data[$Record['name']]=$Record['data'];
			}
		} else {
			return(false);
		}
		$sql = "SELECT title FROM ".$this->tablePrefix."subscribepage WHERE id =".addslashes($id);
		$Data['title']=$this->listdb->queryOne($sql);
		return($Data);
	} # end of getPageData	
	
	function getSPages($OnlyActive) {
		$sql  = "SELECT id, title, active ";
		$sql .= "FROM ".$this->tablePrefix."subscribepage ";
		if ($OnlyActive) {
			$sql .= "WHERE active =".addslashes(1);
		}
		#doDebug($sql,'sql');
		$arrLists = $this->listdb->queryAll($sql);
		#doDebug($arrList,'arrlist');
		return($arrLists);
	} # end of getSPages	
 
	function getAttributeValues($attribID,$userid) {
		$sql = "SELECT value FROM ".$this->userTablePrefix."user_attribute ";
		$sql .= "WHERE userid =".addslashes($userid);
		$sql .= " AND attributeid = ".addslashes($attribID);
		$arrLists = $this->listdb->queryOne($sql);
		return($arrLists);	
	} # end of getAttributeData
 
	function getAttributeData($id) {
		$sql = "SELECT * FROM ".$this->userTablePrefix."attribute ";
		$sql .= "WHERE id =".addslashes($id);
		$arrLists = $this->listdb->queryRow($sql);
		return($arrLists);	
	} # end of getAttributeData
	
	// load PHPlist configuration into an array
	function getConfig($item) {
		$sql = "SELECT value FROM ".$this->tablePrefix."config ";
		$sql .= "WHERE item =\"".addslashes($item)."\"";
		$arrLists = $this->listdb->queryOne($sql);
		return($arrLists);	
	} # end of getconfig
 
 
	// takes a user email
	// returns an array of the lists the user subscribed to
	function getListsByEmail($email) {
		$sql  = "SELECT l.id ";
		$sql .= "FROM ".$this->tablePrefix."listuser lu, ".$this->tablePrefix."list l, ".$this->tablePrefix."user_user uu ";
		$sql .= "WHERE uu.email='".addslashes($email)."' ";
		$sql .= "AND uu.id=lu.userid ";
		$sql .= "AND lu.listid=l.id ";
		$listIds = $this->listdb->queryCol($sql);
	return($listIds);
	} # end of getListsByEmail
 
} # end of class PHPlist
?>
np_phplist_code.txt · Last modified: 2008/04/11 13:19 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki