File: D:/HostingSpaces/SBogers10/deensekroon.komma-mediadesign.nl/wwwroot/admin/php/functions2.php
<?php
/*
functions2.php
Mike Ontwerpt 2012
www.mikeontwerpt.nl
*/
/* login function */
function checkLogin(){
//access the global sql object
global $mysqli;
$login = 0;
if(isset($_SESSION['adminstr'])){
//get the admins
$query = "SELECT id, user, email, hash, rank FROM shop_admin";
if(!$result = $mysqli->query($query))
{
//error handling
}
else{
while($record = $result->fetch_assoc()){
$str = $record['id'].'_'.md5($record['hash']);
if($str == ( $_SESSION['adminstr'] )){
$login = 1; // 1 stands for correct login
}
}
}
}
/* TODO
else if(isset($_COOKIE['dk_autologin']) && strlen($_COOKIE['dk_autologin']) == 106){
/*
references
- http://stackoverflow.com/questions/4773609/what-is-a-relatively-secure-way-of-using-a-login-cookie
- http://jaspan.com/improved_persistent_login_cookie_best_practice
//cookie exists, is it valid?
$temp = explode('|',$_COOKIE['dk_autologin']);
$session = mysql_real_escape_string($temp[0]);
$token = mysql_real_escape_string($temp[1]);
$userhash = mysql_real_escape_string($temp[2]);
//check with database
$result = mysql_query('SELECT user
FROM shop_autologin_tokens
WHERE session = '.$session.'
AND token = '.$token.'
AND md5(user) = '.$userhash.';');
if(mysql_num_rows($result) == 1){
//cookie valid!
$login = 1;
//new token & new cooke
$newseries = $session;
$newtoken = md5(mcrypt_create_iv(22, MCRYPT_DEV_RANDOM));
$newuserhash = md5($user);
$newvalue = $newseries.'|'.$newtoken.'|'.$newuserhash;
$newexpire = time()+(3600*24*7);
//set the cooke
setcookie('dk_autologin',$newvalue,$newexpire,'/','www.deensekroon.nl');
//insert data in database
mysql_query('UPDATE shop_autologin_tokens
SET expire = '.$newexpire.', token = '.$newtoken.'
WHERE session = '.$session.'
AND token = '.$token.'
AND md5(user) = '.$userhash.' LIMIT 1');
}
else if (mysql_num_rows(mysql_query('SELECT user FROM shop_autologin_tokens WHERE session = '.$session.' AND md5(user) = '.$userhash.';') == 1)){
//token is differt session is valid
//we're probably under attack!
mysql_query('DELETE FROM shop_autologin_tokens WHERE id = '.$adminId);
}
else{
//something went wrong?
}
}
*/
return $login;
}
function getLanguage(){
//access the global sql object
global $mysqli;
//query
$query = 'SELECT lang FROM shop_admin LIMIT 1';
if(!$lang_result = $mysqli->query($query)){
//error handling
}
else{
$lang_record = $lang_result->fetch_assoc();
include './lang/'.$lang_record['lang'].'.php';
return $siteLabels;
}
}
function getRank(){
//access the global sql object
global $mysqli;
$temp = explode('_',$_SESSION['adminstr']);
$adminId = $temp[0];
$query = 'SELECT rank FROM shop_admin WHERE id = '.$adminId.' LIMIT 1';
if(!$result = $mysqli->query($query))
{
//error handling
return false;
}
else{
$record = $result->fetch_assoc();
$rank = $record['rank'];
return $rank;
}
}
function generateSalt($workFactor){
//get random number
$iv = mcrypt_create_iv(22, MCRYPT_DEV_RANDOM);
//hash number with md5 algorithm
$md5Iv = md5($iv);
//make it 22 characters long
$workFactor = str_pad($workFactor,2,0,STR_PAD_LEFT);
$saltStr = substr($md5Iv, 0 ,22);
$salt = '$2a$'.$workFactor.'$'.$saltStr;
return $salt;
}
function getMailNewPass($user, $pass){
$query = 'SELECT lang FROM shop_admin LIMIT 1';
if(!$lang_result = $mysqli->query($query)){
//error handling
}
else{
$mail = '';
$lang_record = $lang_result->fetch_assoc();
switch($lang_record['lang']){
//default english mail
default :
$mail .= 'Dear '.$user.',<br /><br />';
$mail .= 'You requested a new password on Deensekroon.nl<br /><br />';
$mail .= '<strong>New login data</strong><br />';
$mail .= 'User: '.$user.'<br />';
$mail .= 'Password: '.$pass.'<br /><br />';
$mail .= 'This is an automatic generated message, please do not re-ply.';
break;
}
return $mail;
}
}
function isEmail($input){
return preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $input);
}
function linkname($input){
/*
$output = trim($input);
$output = str_replace(' ','-',$output);
//remove these characters
$forbidden = array("'", '"', '\\', '/', ';', ';', '|', '>', '<', '[', ']', '!','?', '@', '#', '$', '%', '^', '&', '*', '(', ')','+','=','{','}','`', '~', '.', ',');
foreach($forbidden as $key => $value){
$output = str_replace($value, '', $output);
}
$output = strtolower($output);
$output = iconv('utf-8','ASCII//IGNORE//TRANSLIT',$output);
*/
// Remove whitespace
$output = trim($input);
// Lowercase
$output = strtolower($output);
// Replace & with "en" or "and"
$output = str_replace('&', 'en', $output);
// Replace special letters with normal letters
$output = preg_replace( "`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i","\\1", $output );
// Remove html entities
$pattern = '#(&)([a-z]*)([;$])#';
$output = preg_replace($pattern,'',$output);
// Remove all special characters
$output = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $output);
// Replace spaces with a dash
$output = str_replace(' ','-',$output);
$output = str_replace('.','',$output);
// Replace multiple dashes with one dash
$output = preg_replace('/-{2,}/','-',$output);
return $output;
}
function inDatabase($input){
global $mysqli;
$str = $mysqli->real_escape_string($input);
// Remove whitespace
$str = trim($str);
// Convert html text to utf-8 special characters
$str = htmlentities($str, ENT_NOQUOTES, 'utf-8');
// Keep html tags
$str = str_replace("<","<",$str);
$str = str_replace(">",">",$str);
$str = str_replace("&","&",$str);
// Convert single <,> or & back to utf-8 special characters
$str = str_replace("& ","& ",$str);
$str = str_replace(" >"," >",$str);
$str = str_replace("< ","< ",$str);
return $str;
}
function fromDatabase($input){
$input = stripslashes($input);
return $input;
}
function existInArray($val, $arr){
$exists = false;
foreach($arr as $key => $arrval){
if($arrval == $val) $exists = true;
}
return $exists;
}
function displayErrors($errors){
//error msg
$fmmsg = '<span class="fm-err fm-global">';
$fmmsg .= '<span class="fm-err-x">×</span>Some errors occured';
$fmmsg .= '<ul class="error-list">';
foreach($errors as $key => $msg){
$fmmsg .= '<li>'.$msg.'</li>';
}
$fmmsg .= '</ul>';
$fmmsg .= '</span>';
$_SESSION['feed-msg'] = $fmmsg;
}
function getConfigURL(){
global $mysqli;
if($result = $mysqli->query('SELECT url FROM shop_config LIMIT 1')){
$record = $result->fetch_assoc();
$url = $record['url'];
if(substr($url,-1,1) == '/') $url = substr($url,0,-1);
return $url;
}
else{
return false;
}
}
function getDeliveryCosts($isocode){
global $mysqli;
$isocode = strtoupper($isocode);
if($result = $mysqli->query('SELECT shippingCost FROM countries WHERE isocode = "'.$isocode.'" LIMIT 1')){
if($result->num_rows > 0){
$record = $result->fetch_assoc();
$delivery = $record['shippingCost'];
// bij nederland is er nog kortin mogelijk
if( ($isocode == 'NL' || $isocode == 'BE' ) && $_SESSION['cart']['discountcode']['freeshipnl']){
$delivery = 0;
}
}
else{
//overige landen
if($restresult = $mysqli->query('SELECT shippingCost FROM countries WHERE isocode = "-" LIMIT 1')){
$restrecord = $restresult->fetch_assoc();
$delivery = $restrecord['shippingCost'];
}
}
return $delivery;
}
else{
return $mysqli->error;
}
}
/* Create Image : Updated august 2, 2012 */
function createImage($value, $pad, $targetW='', $targetH=''){
$pad = substr($pad,1);
$pad = DOCUMENT_ROOT . $pad;
#1 copy original image to the server & get dimensions
copy($value, $pad);
list($oldWidth, $oldHeight) = getimagesize($pad);
#2 new image settings
$maxWidth = 1000;
$maxHeight = 800;
$quality = 100;
#3 info: how to prepare ?
/*
- !empty(targetW) && !empty(targetH) -> create image from that width & height
- !empty(targetW) && empty(targetH) -> create images by width
- empty(targetW) && !empty(targetH) -> create images by height
- empty(targetW) && empty(targetH) -> just scale image down within max length & height
*/
#4 prepare image
if(!empty($targetW) && !empty($targetH)){
#4a -> prepare image for targetted width & height
if(($oldWidth / $oldHeight) > ($targetW / $targetH)){
//bv Oud liggend en Nieuw Staand / Vierkantiger
if($targetH <= $oldHeight){
$newHeight = $targetH;
$newWidth = ceil(($newHeight*$oldWidth)/$oldHeight);
}
//is the target bigger then original ? do not scale up!
else{
//adjust targetH
$newHeight = $targetH = $oldHeight;
if($targetW > $oldWidth){
//adjust targetW
$newWidth = $targetW = $oldWidth;
}
else{
//don't adjust targetW
$newWidth = ceil(($newHeight*$oldWidth)/$oldHeight);
}
}
#5 is the image to large ?
if($newWidth > $maxWidth){
$newWidth = $targetW = $maxWidth;
$newHeight = $targetH = ceil(($newWidth*$oldHeight)/$oldWidth);
}
if($newHeight > $maxHeight){
$newHeight = $targetH = $maxHeight;
$newWidth = $targetW = ceil(($newHeight*$oldWidth)/$oldHeight);
}
//get position X
$posX = ceil(($newWidth - $targetW) / -2);
//position Y = 0
$posY = 0;
}
else{
//bv Oud staand en Nieuw Liggender / Vierkantiger
// the other way arround
if($targetW <= $oldWidth){
$newWidth = $targetW;
$newHeight = ceil(($newWidth*$oldHeight)/$oldWidth);
}
else{
//adjust targetW
$newWidth = $targetW = $oldWidth;
if($targetH > $oldHeight){
//adjust targetH
$newHeight = $targetH = $oldHeight;
}
else{
//don't adjust targetH
$newHeight = ceil(($newWidth*$oldHeight)/$oldWidth);
}
}
if($newWidth > $maxWidth){
$newWidth = $targetW = $maxWidth;
$newHeight = $targetH = ceil(($newWidth*$oldHeight)/$oldWidth);
}
if($newHeight > $maxHeight){
$newHeight = $targetH = $maxHeight;
$newWidth = $targetW = ceil(($newHeight*$oldWidth)/$oldHeight);
}
$posX = 0;
$posY = ceil(($newHeight - $targetH) / -2);
}
}
else if (!empty($targetW) && empty($targetH)){
#4b -> create images by width
if($targetW <= $oldWidth){ $newWidth = $targetW; } else{ $newWidth = $targetW = $oldWidth; }
$newHeight = $targetH = ceil(($newWidth*$oldHeight)/$oldWidth);
$posX = 0;
$posY = 0;
}
else if (empty($targetW) && !empty($targetH)){
#4c -> create images by height
if($targetH <= $oldHeight){ $newHeight = $targetH; }else{ $newHeight = $targetH = $oldHeight; }
$newWidth = $targetW = ceil(($newHeight*$oldWidth)/$oldHeight);
$posX = 0;
$posY = 0;
}
else if (empty($targetW) && empty($targetH)){
#4c -> just use old dimensions
$newWidth = $targetW = $oldWidth;
$newHeight = $targetH = $oldHeight;
$posX = 0;
$posY = 0;
}
#5 is the image to large ?
if($newWidth > $maxWidth){
$newWidth = $targetW = $maxWidth;
$newHeight = $targetH = ceil(($newWidth*$oldHeight)/$oldWidth);
}
if($newHeight > $maxHeight){
$newHeight = $targetH = $maxHeight;
$newWidth = $targetW = ceil(($newHeight*$oldWidth)/$oldHeight);
}
#7 get file extention
$arr = explode('.', $pad);
$fileExt = strtolower($arr[(count($arr) - 1)]);
#8 create raw image
if( ! empty($fileExt))
{
switch($fileExt){
case 'jpg':
case 'jpeg':
$img_raw = imagecreatefromjpeg($pad);
break;
case 'png':
$img_raw = imagecreatefrompng($pad);
break;
case 'gif':
$img_raw = imagecreatefromgif($pad);
break;
}
// imagecreatetruecolor() returns an image identifier representing a black image of the specified size.
$dst_r = imagecreatetruecolor($targetW, $targetH);
imagealphablending($dst_r, false);
imagesavealpha($dst_r, true);
//bool imagecopyresampled(resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h )
imagecopyresampled($dst_r, $img_raw, $posX, $posY, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight );
//get rid of the original image
unlink($pad);
//create the new image
if($fileExt == 'png' || $fileExt == 'gif'){
if(imagepng($dst_r, $pad, 8)){ return true; }else{ return false; }
}
else if(imagejpeg($dst_r, $pad, $quality)){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
/* Create Image : Updated april 6, 2012 */
/*
function createImage($value, $pad, $targetW='', $targetH=''){
#1 copy original image to the server & get dimensions
copy($value, $pad);
list($oldWidth, $oldHeight) = getimagesize($pad);
#2 new image settings
$maxWidth = 1000;
$maxHeight = 800;
$quality = 100;
#3 info: how to prepare ?
/*
- !empty(targetW) && !empty(targetH) -> create image from that width & height
- !empty(targetW) && empty(targetH) -> create images by width
- empty(targetW) && !empty(targetH) -> create images by height
- empty(targetW) && empty(targetH) -> just scale image down within max length & height
#4 prepare image
if(!empty($targetW) && !empty($targetH)){
#4a -> prepare image for targetted width & height
if(($oldWidth / $oldHeight) > ($targetW / $targetH)){
//is the target bigger then original ? do not scale up!
if($targetH <= $oldHeight){
$newHeight = $targetH;
$newWidth = ceil(($newHeight*$oldWidth)/$oldHeight);
}
else{
//adjust targetH
$newHeight = $targetH = $oldHeight;
if($targetW > $oldWidth){
//adjust targetW
$newWidth = $targetW = $oldWidth;
}
else{
//don't adjust targetW
$newWidth = ceil(($newHeight*$oldWidth)/$oldHeight);
}
}
//get position X
$temp = $newWidth - $targetW;
if($temp != 0){ $posX = ceil(($newWidth - $targetW) / 2); }
else{ $posX = 0; }
//position Y = 0
$posY = 0;
}
else{
// the other way arround
if($targetW <= $oldWidth){
$newWidth = $targetW;
$newHeight = ceil(($newWidth*$oldHeight)/$oldWidth);
}
else{
//adjust targetW
$newWidth = $targetW = $oldWidth;
if($targetH > $oldHeight){
//adjust targetH
$newHeight = $targetH = $oldHeight;
}
else{
//don't adjust targetH
$newHeight = ceil(($newWidth*$oldHeight)/$oldWidth);
}
}
$posX = 0;
$temp = $newHeight - $targetH;
if($temp != 0){ $posY = ceil(($newHeight - $targetH) / 2); }
else{ $posY = 0; }
}
}
else if (!empty($targetW) && empty($targetH)){
#4b -> create images by width
if($targetW <= $oldWidth){ $newWidth = $targetW; } else{ $newWidth = $targetW = $oldWidth; }
$newHeight = $targetH = ceil(($newWidth*$oldHeight)/$oldWidth);
$posX = 0;
$posY = 0;
}
else if (empty($targetW) && !empty($targetH)){
#4c -> create images by height
if($targetH <= $oldHeight){ $newHeight = $targetH; }else{ $newHeight = $targetH = $oldHeight; }
$newWidth = $targetW = ceil(($newHeight*$oldWidth)/$oldHeight);
$posX = 0;
$posY = 0;
}
else if (empty($targetW) && empty($targetH)){
#4c -> just use old dimensions
$newWidth = $targetW = $oldWidth;
$newHeight = $targetH = $oldHeight;
$posX = 0;
$posY = 0;
}
#5 is the image to large ?
if($newWidth > $maxWidth){
$newWidth = $targetW = $maxWidth;
$newHeight = $targetH = ceil(($newWidth*$oldHeight)/$oldWidth);
}
if($newHeight > $maxHeight){
$newHeight = $targetH = $maxHeight;
$newWidth = $targetW = ceil(($newHeight*$oldWidth)/$oldHeight);
}
#7 get file extention
$arr = explode('.', $pad);
$fileExt = strtolower($arr[(count($arr) - 1)]);
#8 create raw image
switch($fileExt){
case 'jpg':
case 'jpeg':
$img_raw = imagecreatefromjpeg($pad);
break;
case 'png':
$img_raw = imagecreatefrompng($pad);
break;
case 'gif':
$img_raw = imagecreatefromgif($pad);
break;
}
// imagecreatetruecolor() returns an image identifier representing a black image of the specified size.
$dst_r = imagecreatetruecolor($targetW, $targetH);
imagealphablending($dst_r, false);
imagesavealpha($dst_r, true);
//bool imagecopyresampled(resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h )
imagecopyresampled($dst_r, $img_raw, 0, 0, $posX, $posY, $newWidth, $newHeight, $oldWidth, $oldHeight );
//get rid of the original image
unlink($pad);
//create the new image
if($fileExt == 'png' || $fileExt == 'gif'){
if(imagepng($dst_r, $pad, 8)){ return true; }else{ return false; }
}
else if(imagejpeg($dst_r, $pad, $quality)){
return true;
}
else{
return false;
}
}*/
function generateMpArray($linkname, $label = ''){
/*
returns a field array container the fields of the input page
part of the multipage system
Mike Ontwerpt 2012
www.mikeontwerpt.nl
*/
/* access the global sql object */
global $mysqli;
/* create the array */
$mp_fields = array();
/* $mp_fields['form-config'] contains the configuration of the form */
$mp_fields['form-config']['linkname'] = $linkname;
$mp_fields['form-config']['table'] = $linkname;
!empty($label) ? $mp_fields['form-config']['label'] = $label : $mp_fields['form-config']['label'] = $linkname;
$mp_fields['form-config']['action'] = '';
/* get pageId */
$pageQuery = 'SELECT id FROM mp_pages WHERE linkname = "'.$linkname.'" LIMIT 1';
if($pageResult = $mysqli->query($pageQuery)){
$pageRecord = $pageResult->fetch_assoc();
$pageId = $pageRecord['id'];
$mp_fields['form-config']['pageId'] = $pageId;
/* array key */
$key = 0;
/* get fields for this array */
$query = 'SELECT linkname, label, type, required, clear, value
FROM mp_fields
WHERE pageId = '.$pageId.'
ORDER BY fieldOrder DESC';
if($result = $mysqli->query($query)){
/* fill array */
while($record = $result->fetch_assoc()){
/* database table */
$mp_fields[$key]['db'] = $mp_fields['form-config']['table'].'.'.$record['linkname'];
/* input linkname*/
$mp_fields[$key]['linkname'] = $record['linkname'];
/* input type */
$mp_fields[$key]['type'] = $record['type'];
/* field required ? */
$record['required'] == 1 ? $mp_fields[$key]['required'] = true : $mp_fields[$key]['required'] = false;
/* clear after field ? */
$record['clear'] == 1 ? $mp_fields[$key]['clear'] = true : $mp_fields[$key]['clear'] = false;
/* handle field label / val by type*/
switch($record['type']){
case 'text':
case 'dateToTimest':
case 'wysiwyg':
$mp_fields[$key]['label'] = $record['label'];
break;
case 'fixedValue':
$mp_fields[$key]['value'] = $record['value'];
break;
case 'submit':
$mp_fields[$key]['label'] = $record['label'];
break;
}
$key++;
}
/* return array */
return $mp_fields;
}
else{
return false;
}
}
else{
return false;
}
}
// REPLACE SHORTCODES FUNCTION
// How to use: $output .= replaceShortcodes($textFromDatabase, $colorForVimeo);
function replaceShortcodes($input, $width=622, $dirPad = '/images/uploads/', $color='#9EA8AF') {
global $mysqli;
// Patern to look for the shortcode
$pattern = "/\[(\d){11}\]/";
// Find matches
preg_match_all($pattern, $input, $matches);
// Enter the loop
foreach($matches[0] as $key) {
// Get the raw code
$key = str_replace('[', '', $key);
$key = str_replace(']', '', $key);
$key = $mysqli->real_escape_string($key);
// Make new information array
$fileArray = array();
// Query to backtrace the shortcode
$query = 'SELECT m.title, m.type, m.path
FROM media_files AS m, content_status AS s
WHERE m.shortcode = '.$key.'
AND s.itemId = m.id
AND s.active = 1 LIMIT 1';
if(!$result = $mysqli->query($query)){
//do nothing
}
else{
$numItems = $result->num_rows;
$record = $result->fetch_assoc();
// Store the information
$fileArray[$key]['title'] = $record['title'];
$fileArray[$key]['path'] = $record['path'];
$fileArray[$key]['type'] = $record['type'];
$tempOutput = '';
// See if shortcode is found
if ($numItems == 1) {
$extractedTitle = htmlentities($fileArray[$key]['title']);
$extractedType = htmlentities($fileArray[$key]['type']);
$extractedPath = htmlentities($fileArray[$key]['path']);
switch($extractedType) {
case 1:
if(is_file(DOCUMENT_ROOT . substr($dirPad,1) .$extractedPath)){
$size = getimagesize(DOCUMENT_ROOT . substr($dirPad,1) .$extractedPath);
$extractedWidth = $size[0];
// EXTENTION FOR DEENSE KROON (blog extention) //
if(defined('URL_PAGE') && URL_PAGE == 'blogt'){
$width = 622;
$tempOutput .= '<div class="blog-item-image">';
}
// END EXTENTION //
// Add to output
$tempOutput .= '<img src="'.$dirPad.$extractedPath.'" alt="'.$extractedTitle.'"';
if($extractedWidth > $width) $tempOutput.= ' width="'.$width.'"' ;
$tempOutput .= '/>';
// EXTENTION FOR DEENSE KROON (blog extention) //
if(defined('URL_PAGE') && URL_PAGE == 'blogt'){
$tempOutput .= '</div>';
}
// END EXTENTION //
}
break;
case 2:
// Extract the vimeo video ID
$extractedPathArray = explode('/', $extractedPath);
$vimeoPath = $extractedPathArray[(count($extractedPathArray) - 1)];
//calculate height based on a resolution 16x9
$height = ($width*9)/16;
// Add to output
$tempOutput .= '<iframe src="http://player.vimeo.com/video/'.$vimeoPath.'?title=0&byline=0&portrait=0&color='.$color.'" width="'.$width.'" height="'.$height.'" frameborder="0"></iframe>';
break;
/*case 3:
$objArr = explode('</object>', $fileArray[$key]['path']);
$objPath = $objArr[0].'</object>';
$tempOutput .= '<div class="soundCloudCon">';
$tempOutput .= $objPath;
$tempOutput .= '</div>';
break;*/
case 3:
// Extract the youtube video ID
$extractedPathArray = explode('/', $extractedPath);
$youtubePath = $extractedPathArray[(count($extractedPathArray) - 1)];
$tempArr = explode('watch?v=', $youtubePath);
if(count($tempArr)>1){$youtubePath = $tempArr[1];}
//make sure there are no parameters but the key
$paramArr = explode('&', $youtubePath);
if(count($paramArr)>0) {$youtubePath = $paramArr[0]; }
//calculate height based on a resolution 16x9
$height = ($width*9)/16;
// Add to output
/* $tempOutput .= '<object width="'.$width.'" height="'.$height.'">
<param name="movie" value="http://www.youtube.com/v/'.$youtubePath.'?version=3&hl=en_US"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/'.$youtubePath.'?version=3&hl=en_US" type="application/x-shockwave-flash" width="'.$width.'" height="'.$height.'" allowscriptaccess="always" allowfullscreen="true"></embed>
</object>'; */
$tempOutput .= '<iframe width="'.$width.'" height="'.$height.'" src="http://www.youtube.com/embed/'.$youtubePath.'?wmode=transparent" frameborder="0" allowfullscreen></iframe>';
break;
case 4:
$tempOutput .= '<a href="'.$extractedPath.'" target="_blank">'.$extractedTitle.'</a>';
break;
}
}
$input = str_replace('['.$key.']', $tempOutput, $input);
}
}
return $input;
}
function ip(){
if(getenv("HTTP_X_FORWARDED_FOR")) {
$IPadres = getenv("HTTP_X_FORWARDED_FOR");
}
else if(getenv("HTTP_CLIENT_IP")){
$IPadres = getenv("HTTP_CLIENT_IP");
}
else {
$IPadres = $_SERVER["REMOTE_ADDR"];
}
return $IPadres;
}
function displayPrice($input, $addCurrencySymbol = true){
if($input != 0) $input = checkPrice($input);
$temp = explode('.',$input); # price
isset($temp[1]) ? $displayCents = str_pad($temp[1], 2, STR_PAD_LEFT) : $displayCents = '00';
$displayPrice = $temp[0].','.$displayCents;
if($addCurrencySymbol) $displayPrice = '€ ' . $displayPrice;
return $displayPrice;
}
function displayPriceForMail($input){
if($input != 0) $input = checkPrice($input);
$temp = explode('.',$input); # price
isset($temp[1]) ? $displayCents = str_pad($temp[1], 2, STR_PAD_LEFT) : $displayCents = '00';
$displayPrice = '€ '.$temp[0].','.$displayCents;
return $displayPrice;
}
function displayPriceForPDF($input){
if($input != 0) $input = checkPrice($input);
$temp = explode('.',$input); # price
isset($temp[1]) ? $displayCents = str_pad($temp[1], 2, STR_PAD_LEFT) : $displayCents = '00';
$displayPrice = chr(128).' '.$temp[0].','.$displayCents;
return $displayPrice;
}
function checkPrice($input){
$forbidden = array('!','@','#','$','%','^','&','*','(',')','-','+','=','_','{','}','[',']',':',';','"','\'','<','>','?','/');
foreach($forbidden as $i => $val){
$input=str_replace($val,'',$input); //replaces "," with "."
}
if(!empty($input)){
$input=str_replace(',','.',$input); //replaces "," with "."
$input=str_replace('€','',$input); //replaces "," with "."
$input = trim($input);
$input = number_format($input, 2, '.', '');
$pricecheckpattern = "#^[0-9]{1,3}\.[0-9]{2}$#";
if (preg_match($pricecheckpattern,$input)==1){
return $input;
}
else{
return false;
}
}
else{
return false;
}
}
function checkProductDiscount($productId){
global $mysqli;
$discountPer = false;
#1 check which actions are active
#2 check which actions don't need codes
$query = 'SELECT da.id, da.type, dd.catId, dd.searchtag, dd.percentage
FROM discount_action AS da, discount_details AS dd, content_status AS cs
WHERE (da.active = 1
OR (da.starts < '.time().' AND da.expires > '.time().'))
AND cs.active = 1
AND cs.linkname = "discount_action"
AND cs.itemId = da.id
AND da.discountCode = ""
AND da.id = dd.actionId';
if($result = $mysqli->query($query)){
if($result->num_rows > 0){
//er zijn dus acties die nu gelden en waarvoor geen code nodig, komt dit product in aanmerking?
while($record = $result->fetch_assoc()){
$actionId = $record['id'];
$type = $record['type'];
//pre-define
$allDiscount = 0;
$searchDiscount = 0;
$catDiscount = 0;
$temp = explode('-',$type);
switch($temp[0]){
#3 check discount all products
case 'allproducts':
//dit product komt dus in aanmerking voor de korting
if($temp[1] == 'per' && $record['percentage'] != 0 && !empty($record['percentage'])) $allDiscount = $record['percentage'];
/*
TODO "temp[1] == 'abs'
*/
break;
#4 check posibility searchtag
case 'searchtag':
$searchtag = $record['searchtag'];
// kijk of het discount catId hetzelfde is als van dit product
if($searchtagResult = $mysqli->query('SELECT id FROM product_searchtags WHERE productId = "'.$productId.'" AND searchtag = "'.$searchtag.'" LIMIT 1'))
{
if($searchtagResult->num_rows > 0){
//product gevonden, dit product komt dus in aanmerking
if($temp[1] == 'per' && $record['percentage'] != 0 && !empty($record['percentage'])) $searchDiscount = $record['percentage'];
//echo 'SELECT id FROM product_searchtags WHERE productId = "'.$productId.'" AND searchtag = "'.$searchtag.'" LIMIT 1';
/*
TODO "temp[1] == 'abs'
*/
}
}
break;
#5 check posibility category
case 'category':
$catId = $record['catId'];
// kijk of het discount catId hetzelfde is als van dit product
if($catResult = $mysqli->query('SELECT catId FROM product_products WHERE id = "'.$productId.'" AND catId = "'.$catId.'" LIMIT 1'))
{
if($catResult->num_rows > 0){
//product gevonden, dit product komt dus in aanmerking
if($temp[1] == 'per' && $record['percentage'] != 0 && !empty($record['percentage'])) $catDiscount = $record['percentage'];
/*
TODO "temp[1] == 'abs'
*/
}
}
break;
}
if($allDiscount != 0 || $searchDiscount != 0 || $catDiscount != 0){
if($allDiscount > $discountPer) $discountPer = $allDiscount;
if($searchDiscount > $discountPer) $discountPer = $searchDiscount;
if($catDiscount > $discountPer) $discountPer = $catDiscount;
return $discountPer;
}
}
}
}
}
function checkAvailableInStock($productId){
global $mysqli;
$available = 0;
if($stockResult = $mysqli->query('SELECT inStock
FROM shop_stock
WHERE productId = '.$productId.' LIMIT 1')){
if($stockResult->num_rows > 0){
$stockRecord = $stockResult->fetch_assoc();
//redefine variables
$inStock = $stockRecord['inStock'];
//get IN ORDER
$inOrderQuery = 'SELECT op.numProducts
FROM shop_order_products AS op, shop_order_info AS oi
WHERE op.orderId = oi.id
AND op.productId = '.$productId.'
AND oi.orderStatus = 0';
$numInOrder = 0;
if($inOrderResult = $mysqli->query($inOrderQuery)){
while($inOrderRecord = $inOrderResult->fetch_assoc()){
$numInOrder += $inOrderRecord['numProducts'];
}
}
else{
echo $mysqli->error;
}
// get available
$available = $inStock - $numInOrder;
}
}
return $available;
}
function checkAvailableSizes($productId)
{
global $mysqli;
if($stockResult = $mysqli->query('SELECT size, inStock FROM shop_stock WHERE productId = '.$productId.' ORDER BY id ASC')){
$sizes = array();
while($stockRecord = $stockResult->fetch_assoc())
{
$size = $stockRecord['size'];
$inStock = $stockRecord['inStock'];
$inOrderQuery = 'SELECT op.numProducts
FROM shop_order_products AS op, shop_order_info AS oi
WHERE op.orderId = oi.id
AND op.productId = '.$productId;
if( ! empty($size)) $inOrderQuery .= ' AND op.size = "' . $size . '"';
$inOrderQuery .= ' AND (oi.orderStatus = 0
OR oi.orderStatus = 2)';
$numInOrder = 0;
if($inOrderResult = $mysqli->query($inOrderQuery)){
while($inOrderRecord = $inOrderResult->fetch_assoc()){
$numInOrder += $inOrderRecord['numProducts'];
}
}
// get available
$available = $inStock - $numInOrder;
if( ! empty($size) && $available > 0)
{
$sizes[$size] = $inStock;
}
}
return $sizes;
}
return false;
}
function createExcelFile(){
global $mysqli;
require_once './Spreadsheet/Excel/Writer.php';
## date of today ##
$today = date('ymd',time());
## Creating a workbook ##
$workbook = new Spreadsheet_Excel_Writer();
$xlsName = 'deense_kroon';
## sending HTTP headers ##
$workbook->send($today.'_'.$xlsName.'.xls');
## Creating a worksheet ##
$workbook->setVersion(8);
################### Creating an order worksheet ####################
$ws_order =& $workbook->addWorksheet('Orders - Info');
## Creating the format ##
$format_bold =& $workbook->addFormat();
$format_bold->setBold();
$format_cur =& $workbook->addFormat();
$format_cur->setNumFormat( chr(128) . '#,##0.00');
$format_num =& $workbook->addFormat();
$format_num->setNumFormat(0);
$format_date =& $workbook->addFormat();
$format_date->setNumFormat('D-MMM-YYYY');
## Get info from the database ##
$query = 'SELECT DISTINCT oi.id AS orderId, oi.orderCode, oi.customerId, oi.orderDate, oi.amount, oi.paymentMethod, oi.paymentStatus, oi.paymentDate, oi.shippingMethod, oi.shippingDate, oi.orderStatus, oi.lastUpdate,
cp.firstName, cp.middleName, cp.lastName, cp.city, cp.customerCode
FROM shop_order_info AS oi, shop_customer_personal AS cp, shop_customer_login AS cl
WHERE cl.id = oi.customerId
AND cl.personalId = cp.id
AND NOT oi.orderStatus = "-1"
ORDER BY oi.lastUpdate DESC';
if($result = $mysqli->query($query)){
$numOrders = $result->num_rows;
$row = 0;
$col = 0;
## Set Column width ##
$info = array();
$info['orderdatum']['w'] = 20;
$info['ordernummer']['w'] = 32;
$info['bedrag']['w'] = 10;
$info['debiteurnr']['w'] = 20;
$info['achternaam']['w'] = 32;
$info['voornaam']['w'] = 32;
$info['woonplaats']['w'] = 20;
$info['betaalstatus']['w'] = 20;
$info['betaaldatum']['w'] = 10;
$info['betaalmethode']['w'] = 20;
$info['orderstatus']['w'] = 20;
$info['verzenddatum']['w'] = 10;
## create columns ##
foreach($info as $key => $value){
$ws_order->setColumn($col,$col,$value['w']);
$ws_order->write($row, $col, ucfirst($key), $format_bold);
$col++;
}
$col = 0;
$row+=2; //lege regel
while($record = $result->fetch_assoc()){
## store data ##
$info['orderdatum'] = date('d / m / Y',$record['orderDate']);
$info['ordernummer'] = 'order: '.$record['orderCode'];
$info['bedrag'] = $record['amount'];
$temp = explode('.',$info['bedrag'] ); # price
isset($temp[1]) ? $displayCents = str_pad($temp[1], 2, STR_PAD_LEFT) : $displayCents = '00';
$info['bedrag'] = chr(128).' '.$temp[0].'.'.$displayCents;
$info['debiteurnr'] = fromDatabase($record['customerCode']);
$info['achternaam'] = fromDatabase($record['lastName']);
if(!empty($record['middleName'])) $info['achternaam'] .= ', '.fromDatabase($record['middleName']);
$info['voornaam'] = fromDatabase($record['firstName']);
$info['woonplaats'] = fromDatabase($record['city']);
$info['betaalstatus'] = fromDatabase($record['paymentStatus']);
!empty($record['paymentDate']) ? $paymentDate = date('d / m / Y',$record['paymentDate']) : $paymentDate = '-';
$info['betaaldatum'] = $paymentDate;
$info['betaalmethode'] = fromDatabase($record['paymentMethod']);
$orderStatusResult = $mysqli->query('SELECT orderStatus
FROM shop_status
WHERE statusNr = '.$record['orderStatus'].' LIMIT 1');
$orderStatusRecord = $orderStatusResult->fetch_assoc();
$displayOrderStatus = $orderStatusRecord['orderStatus'];
$info['orderstatus'] = $displayOrderStatus;
!empty($record['shippingDate']) ? $shippingDate = date('d / m / Y',$record['shippingDate']) : $shippingDate = '-';
$info['verzenddatum'] = $shippingDate;
foreach($info as $key => $value){
## check format ##
/*if($key == 'bedrag'){
$ws_order->write($row, $col, 'cur: '.$value, $format_cur);
}
else if($key == 'orderdatum' || $key == 'betaaldatum' || $key == 'verzenddatum'){
$ws_order->write($row, $col, 'date: '.$value, $format_date);
}
else if($key == 'ordernummer'){
$ws_order->write($row, $col, 'num: '.$value, $format_num);
}
else{
$ws_order->write($row, $col, 'normal: '.$value);
}*/
$ws_order->write($row, $col, $value);
$col++;
}
$col = 0;
$row++;
}
}
#######################################################################
################### Creating an products worksheet ####################
$ws_products =& $workbook->addWorksheet('Orders - Products');
## Get info from the database ##
$query = 'SELECT DISTINCT op.title, op.price_original, op.price_current, op.instanceId, op.color, op.stockCode, op.numProducts, oi.orderDate, oi.orderCode
FROM shop_order_products AS op, shop_order_info AS oi
WHERE oi.id = op.orderId
AND NOT oi.orderStatus = "-1"
ORDER BY oi.orderDate DESC';
if($result = $mysqli->query($query)){
$numOrders = $result->num_rows;
$row = 0;
$col = 0;
## Set Column width ##
$info = array();
$info['orderdatum']['w'] = 20;
$info['ordernummer']['w'] = 32;
$info['stockcode']['w'] = 32;
$info['productname']['w'] = 40;
$info['number']['w'] = 5;
$info['price orginal']['w'] = 10;
$info['price sold']['w'] = 10;
## create columns ##
foreach($info as $key => $value){
$ws_products->setColumn($col,$col,$value['w']);
$ws_products->write($row, $col, ucfirst($key), $format_bold);
$col++;
}
$col = 0;
$row+=2; //lege regel
while($record = $result->fetch_assoc()){
## store data ##
$info['orderdatum'] = date('d / m / Y',$record['orderDate']);
$info['ordernummer'] = 'order: '.$record['orderCode'];
$info['stockcode'] = $record['stockCode'];
$info['productname'] = fromDatabase($record['title']);
$info['number'] = $record['numProducts'];
$info['price orginal'] = $record['price_original'];
$temp = explode('.',$info['price orginal'] ); # price
isset($temp[1]) ? $displayCents = str_pad($temp[1], 2, STR_PAD_LEFT) : $displayCents = '00';
$info['price orginal'] = chr(128).' '.$temp[0].'.'.$displayCents;
$info['price sold'] = $record['price_current'];
$temp = explode('.',$info['price sold'] ); # price
isset($temp[1]) ? $displayCents = str_pad($temp[1], 2, STR_PAD_LEFT) : $displayCents = '00';
$info['price sold'] = chr(128).' '.$temp[0].'.'.$displayCents;
foreach($info as $key => $value){
## check format ##
/*if($key == 'bedrag'){
$ws_order->write($row, $col, 'cur: '.$value, $format_cur);
}
else if($key == 'orderdatum' || $key == 'betaaldatum' || $key == 'verzenddatum'){
$ws_order->write($row, $col, 'date: '.$value, $format_date);
}
else if($key == 'ordernummer'){
$ws_order->write($row, $col, 'num: '.$value, $format_num);
}
else{
$ws_order->write($row, $col, 'normal: '.$value);
}*/
$ws_products->write($row, $col, $value);
$col++;
}
$col = 0;
$row++;
}
}
else{
$ws_products->write(0, 0,$mysqli->error);
}
####################################################################
################### Creating an customer worksheet ####################
$ws_customer =& $workbook->addWorksheet('Customers');
## Get info from the database ##
$query = 'SELECT DISTINCT cl.id AS customerId, cl.email, cl.status, cp.title, cp.customerCode, cp.firstName, cp.middleName, cp.lastName, cp.timest, cp.newsletter, cp.postal, cp.street ,cp.number,cp.addition, cp.city, cp.country, cp.birthday, cp.phone
FROM shop_customer_login AS cl, shop_customer_personal AS cp
WHERE cl.personalId = cp.id
ORDER BY cp.timest';
if($result = $mysqli->query($query)){
$numOrders = $result->num_rows;
$row = 0;
$col = 0;
## Set Column width ##
$info = array();
$info['debiteurnr']['w'] = 24;
$info['achternaam']['w'] = 32;
$info['voornaam']['w'] = 32;
$info['klant sinds']['w'] = 32;
$info['email']['w'] = 32;
$info['nieuwsbrief']['w'] = 8;
$info['telefoon']['w'] = 10;
$info['adres']['w'] = 24;
$info['postcode']['w'] = 8;
$info['woonplaats']['w'] = 16;
$info['land']['w'] = 16;
$info['geboortedag']['w'] = 8;
## create columns ##
foreach($info as $key => $value){
$ws_customer->setColumn($col,$col,$value['w']);
$ws_customer->write($row, $col, ucfirst($key), $format_bold);
$col++;
}
$col = 0;
$row+=2; //lege regel
while($record = $result->fetch_assoc()){
## store data ##
$info['debiteurnr'] = 'klant: '.$record['customerCode'];
$info['achternaam'] = fromDatabase($record['lastName']);
$info['voornaam'] = fromDatabase($record['firstName']);
$info['klant sinds'] = date('d / m / Y',$record['timest']);
$info['email'] = $record['email'];
$record['newsletter'] == 1 ? $newsletter = 'Ja' : $newsletter = 'Nee';
$info['nieuwsbrief'] = $newsletter;
$info['telefoon'] = 't: '.$record['phone'];
$info['adres'] = fromDatabase($record['street']).' '.$record['number'].' '.$record['addition'];
$info['postcode'] = $record['postal'];
$info['woonplaats'] = fromDatabase($record['city']);
$info['land'] = $record['country'];
$info['geboortedag'] = date('d / m / Y',$record['birthday']);
foreach($info as $key => $value){
## check format ##
/*if($key == 'bedrag'){
$ws_order->write($row, $col, 'cur: '.$value, $format_cur);
}
else if($key == 'orderdatum' || $key == 'betaaldatum' || $key == 'verzenddatum'){
$ws_order->write($row, $col, 'date: '.$value, $format_date);
}
else if($key == 'ordernummer'){
$ws_order->write($row, $col, 'num: '.$value, $format_num);
}
else{
$ws_order->write($row, $col, 'normal: '.$value);
}*/
$ws_customer->write($row, $col, $value);
$col++;
}
$col = 0;
$row++;
}
}
####################################################################
## Let's send the file ##
$workbook->close();
}
function createSimpleExcel(){
global $mysqli;
## Get info from the database ##
$query = 'SELECT DISTINCT cl.id AS customerId, cl.email, cl.status, cp.title, cp.customerCode, cp.firstName, cp.middleName, cp.lastName, cp.timest, cp.newsletter, cp.postal, cp.street ,cp.number,cp.addition, cp.city, cp.country, cp.birthday, cp.phone
FROM shop_customer_login AS cl, shop_customer_personal AS cp
WHERE cl.personalId = cp.id
ORDER BY cp.customerCode';
$contents="Deense Kroon - Klantenbestand\n\n";
if($result = $mysqli->query($query)){
$numOrders = $result->num_rows;
$row = 0;
$col = 0;
## Set Column width ##
$info = array();
$info['debiteurnr'] = '';
$info['achternaam'] = '';
$info['tussenvoegsel'] = '';
$info['voornaam'] = '';
$info['klant sinds'] = '';
$info['email'] = '';
$info['nieuwsbrief'] = '';
$info['telefoon'] = '';
$info['adres'] = '';
$info['postcode'] = '';
$info['woonplaats'] = '';
$info['land'] = '';
$info['geboortedag'] = '';
## create columns ##
foreach($info as $key => $value){
$contents.= strtoupper($key).',';
}
$contents = substr($contents,0,-1);
$contents .= "\n\n";
while($record = $result->fetch_assoc()){
## store data ##
$info['debiteurnr'] = 'klant: '.$record['customerCode'];
$info['achternaam'] = fromDatabase($record['lastName']);
$info['achternaam'] = ucfirst($info['achternaam']);
$info['tussenvoegsel'] = fromDatabase($record['middleName']);
$info['tussenvoegsel'] = ucfirst($info['tussenvoegsel']);
$info['voornaam'] = fromDatabase($record['firstName']);
$info['voornaam'] = ucfirst($info['voornaam']);
$info['klant sinds'] = date('d / m / Y',$record['timest']);
$info['email'] = $record['email'];
$record['newsletter'] == 1 ? $newsletter = 'Ja' : $newsletter = 'Nee';
$info['nieuwsbrief'] = $newsletter;
$info['telefoon'] = 't: '.$record['phone'];
$info['adres'] = fromDatabase($record['street']).' '.$record['number'].' '.$record['addition'];
$info['postcode'] = $record['postal'];
$info['woonplaats'] = fromDatabase($record['city']);
$info['woonplaats'] = ucfirst($info['woonplaats']);
$info['land'] = $record['country'];
$info['geboortedag'] = date('d / m / Y',$record['birthday']);
foreach($info as $key => $value){
$value = inDatabase($value);
$contents.= $value.',';
}
$contents = substr($contents,0,-1);
$contents .= "\n";
}
}
$contents = strip_tags($contents); // remove html and php tags etc.
Header("Content-Disposition: attachment; filename=klantenbestand.csv");
print $contents;
exit();
}
function createSimpleExcelStock(){
global $mysqli;
## Get info from the database ##
$query = 'SELECT DISTINCT p.id, p.stockCode, p.titleNL, p.price, p.purchase, p.ean
FROM product_products AS p, content_status AS s
WHERE s.itemId = p.id
AND s.active = 1
AND s.linkname = "product_products"
ORDER BY p.stockCode ASC';
$contents="Deense Kroon - Voorraad\n\n";
if($result = $mysqli->query($query)){
## Set Column width ##
$info = array();
$info['ean'] = '';
$info['stockcode'] = '';
$info['inStock'] = '';
$info['inOrder'] = '';
$info['available'] = '';
$info['titel'] = '';
$info['maat'] = '';
$info['inkoopprijs'] = '';
$info['verkoopprijs'] = '';
## create columns ##
foreach($info as $key => $value){
$contents.= strtoupper($key).',';
}
$contents = substr($contents,0,-1);
$contents .= "\n\n";
while($record = $result->fetch_assoc()){
//create productid
$productId = $record['id'];
$info['ean'] = str_replace(',','.',$record['ean']);
$info['stockcode'] = str_replace(',','.',$record['stockCode']);
//predefine variables
$info['inStock'] = $inStock = '?';
$info['available'] = $available = '?';
$info['inOrder'] = $inOrder = 0;
$stockResult = $mysqli->query('SELECT st.inStock, st.size
FROM shop_stock as st
WHERE st.productId = '.$productId.' LIMIT 1');
if($stockResult->num_rows > 0){
$stockRecord = $stockResult->fetch_assoc();
//redefine variables
$inStock = $info['inStock'] = $stockRecord['inStock'];
$info['maat'] = $stockRecord['size'];
//get IN ORDER
$inOrderQuery = 'SELECT op.numProducts
FROM shop_order_products AS op, shop_order_info AS oi
WHERE op.orderId = oi.id
AND op.productId = '.$productId.'
AND (oi.orderStatus = 0
OR oi.orderStatus = 2)';
$numInOrder = 0;
if($inOrderResult = $mysqli->query($inOrderQuery)){
while($inOrderRecord = $inOrderResult->fetch_assoc()){
$numInOrder += $inOrderRecord['numProducts'];
}
}
$info['inOrder'] = $numInOrder;
// get available
$info['available'] = $available = $inStock - $numInOrder;
//title
$info['titel'] = stripslashes($record['titleNL']);
$info['titel'] = htmlspecialchars_decode($info['titel']);
$info['titel'] = mb_convert_encoding($info['titel'],'ISO-8859-15','utf-8');
$info['titel'] = str_replace(',',' - ',$info['titel']);
// Price
if($record['price'] != 0) $input = checkPrice($record['price']);
$temp = explode('.',$input); # price
isset($temp[1]) ? $displayCents = str_pad($temp[1], 2, STR_PAD_LEFT) : $displayCents = '00';
$displayPrice = $temp[0].".".$displayCents;
// Purchase
if($record['purchase'] != 0)
{
$input = checkPrice($record['purchase']);
$temp = explode('.',$input); # price
isset($temp[1]) ? $displayCents = str_pad($temp[1], 2, STR_PAD_LEFT) : $displayCents = '00';
$displayPurchase = $temp[0].".".$displayCents;
$info['inkoopprijs'] = $displayPurchase;
}
else
{
$info['inkoopprijs'] = '-';
}
$info['verkoopprijs' ] = $displayPrice;
}
foreach($info as $key => $value){
//$value = inDatabase($value);
$contents.= $value.',';
}
$contents = substr($contents,0,-1);
$contents .= "\n";
}
}
$contents = strip_tags($contents); // remove html and php tags etc.
header("Content-Disposition: attachment; filename=voorraad.csv");
//header('Content-type: text/csv; charset=UTF-8');
print $contents;
exit();
}
function createSimpleDiscountExcel(){
/*
Get info from the database
# Discounts
- Datum
- Ordercode
- Discount code
- Naam
- Klantnaam
- Woonplaats
- Land
# Giftcards
- Datum
- Ordercode
- Discount code
- Naam
- Klantnaam
- Woonplaats
- Land
*/
global $mysqli;
$query = 'SELECT DISTINCT d.discountCode, d.timest, oc.invoice_firstName, oc.invoice_middleName, oc.invoice_lastName, oc.invoice_city, oc.invoice_country
FROM discount_codes AS d, shop_order_customer AS oc
WHERE d.orderId = oc.orderCode
ORDER BY d.timest DESC';
$contents="Deense Kroon - Kortingscodes\n\n";
if($result = $mysqli->query($query))
{
$numOrders = $result->num_rows;
$info = array();
$info['date'] = '';
$info['kortingscode'] = '';
$info['achternaam'] = '';
$info['voornaam'] = '';
$info['woonplaats'] = '';
$info['land'] = '';
// heading
foreach($info as $key => $value)
{
$contents.= strtoupper($key).',';
}
$contents = substr($contents,0,-1);
$contents .= "\n\n";
while($record = $result->fetch_assoc())
{
$info['date'] = date('d / m / Y',$record['timest']);
$info['kortingscode'] = $record['discountCode'];
$info['achternaam'] = fromDatabase($record['invoice_lastName']);
if( ! empty($record['middleName'])) $info['achternaam'] .= '- '.fromDatabase($record['invoice_middleName']);
$info['voornaam'] = fromDatabase($record['invoice_firstName']);
$info['woonplaats'] = fromDatabase($record['invoice_city']);
$info['land'] = fromDatabase($record['invoice_country']);
foreach($info as $key => $value)
{
//$value = inDatabase($value);
$contents.= $value.',';
}
$contents = substr($contents,0,-1);
$contents .= "\n";
}
}
else
{
echo $mysqli->error;
exit;
}
// GIFTCARDS
$contents .= "\n";
$contents .= "Deense Kroon - Giftcards\n\n";
$query = 'SELECT DISTINCT gc.code, gu.timest, cp.firstName, cp.middleName, cp.lastName, cp.city, cp.country
FROM gc_cards AS gc, gc_used AS gu, shop_customer_login AS cl, shop_customer_personal AS cp, shop_order_info AS oi
WHERE gu.orderId = oi.id
AND gu.cardId = gc.id
AND cl.personalId = cp.id
AND oi.customerId = cl.id
ORDER BY gu.timest DESC';
if($result = $mysqli->query($query))
{
$numOrders = $result->num_rows;
$info = array();
$info['date'] = '';
$info['kortingscode'] = '';
$info['achternaam'] = '';
$info['voornaam'] = '';
$info['woonplaats'] = '';
$info['land'] = '';
// heading
foreach($info as $key => $value)
{
$contents.= strtoupper($key).',';
}
$contents = substr($contents,0,-1);
$contents .= "\n\n";
while($record = $result->fetch_assoc())
{
$info['date'] = date('d / m / Y',$record['timest']);
$info['kortingscode'] = $record['code'];
$info['achternaam'] = fromDatabase($record['lastName']);
if( ! empty($record['middleName'])) $info['achternaam'] .= '- '.fromDatabase($record['middleName']);
$info['voornaam'] = fromDatabase($record['firstName']);
$info['woonplaats'] = fromDatabase($record['city']);
$info['land'] = fromDatabase($record['country']);
foreach($info as $key => $value)
{
//$value = inDatabase($value);
$contents.= $value.',';
}
$contents = substr($contents,0,-1);
$contents .= "\n";
}
}
$contents = strip_tags($contents); // remove html and php tags etc.
Header("Content-Disposition: attachment; filename=kortingscodes.csv");
print $contents;
exit();
}
function categoryHasSize($category)
{
return in_array($category, [
1, //sieraden
27, // kids
61, // kids > jongens
64, // kids > unisex
63, // kids > kinderschoenen
62, // kids > meisjes
32, // schoenen
30, // modeaccessoires
46, //brillen
44, //kousen
41, //mutsen hoeden
43, //pantys
40, //riemen
39, //sjaals
42, //tassen portomonees
45, //toilettassen
47, //blouses en tunieken
48, //broeken
49, //jassen en blazers
50, //jumpsuits
51, //jurken
52, //rokken
53, //tops en shirts
54, //truien en vesten
60, // heren > broeken
56, // heren > jassen colberts
59, // heren > overhemden
58, // heren > t shirts
57, // heren > truien vesten
65, // heren > heren schoenen
]);
}
function mailToDeveloper($msg)
{
require_once DOCUMENT_ROOT . 'admin/lib/mail/php_mailer.class.php';
$mail = new PHPMailer(TRUE);
try
{
$mail->AddAddress('mike@komma.pro', 'Mike');
$mail->SetFrom('mike@komma.pro', 'Deense Kroon Shop');
$mail->Subject = 'Errorlog';
$mail->MsgHTML($msg);
$mail->Send();
}
catch (phpmailerException $e)
{
return FALSE;
}
}
function dd($value)
{
echo '<pre>';
var_dump($value);
exit;
}
function komma_ip()
{
return $_SERVER['REMOTE_ADDR'] == '5.172.219.238';
}