File: D:/HostingSpaces/SBogers10/verrassendveel.komma.pro/wwwroot/admin/php/functions.php
<?php
/*
functions.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 = removeAccents($output);
$output = str_replace(' ','-',$output);
$output = html_entity_decode($output);
//remove these characters
$forbidden = array("'", '"', '\\', '/', ';', ';', '|', '>', '<', '[', ']', '!','?', '@', '#', '$', '%', '^', '&', '*', '(', ')','+','=','{','}','`', '~', '.', ',');
foreach($forbidden as $key => $value){
$output = str_replace($value, '', $output);
}
$output = strtolower($output);
return $output;
}
function inDatabase($input){
global $mysqli;
$input = trim($input);
$input = $mysqli->real_escape_string($input);
return $input;
}
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;
}
/* 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);
$posX = 0;
$temp = $newHeight - $targetH;
if($temp != 0){ $posY = ceil(($newHeight - $targetH) / 2); }
else{ $posY = 0; }
}
if($newHeight > $maxHeight){
$newHeight = $targetH = $maxHeight;
$newWidth = $targetW = 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;
}
#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;
}
}
/* Create a grayscale Image : Updated may 23, 2012 */
function createGrayImage($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);
$posX = 0;
$temp = $newHeight - $targetH;
if($temp != 0){ $posY = ceil(($newHeight - $targetH) / 2); }
else{ $posY = 0; }
}
if($newHeight > $maxHeight){
$newHeight = $targetH = $maxHeight;
$newWidth = $targetW = 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;
}
#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;
}
if($img_raw && imagefilter($img_raw, IMG_FILTER_GRAYSCALE))
{
// 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;
}
}
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 'checkbox':
$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($dirPad.$extractedPath)){
$size = getimagesize($dirPad.$extractedPath);
$extractedWidth = $size[0];
// EXTENTION FOR DEENSE KROON (blog extention) //
if(isset($_GET['page']) && $_GET['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(isset($_GET['page']) && $_GET['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="'.$dirPad.$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){
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 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 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'];
$actionId = $record['id'];
//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'];
break;
#4 check posibility category
case 'searchtag':
$searchtag = $record['searchtag'];
// kijk of het discount catId hetzelfde is als van dit product
$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';
}
break;
#5 check posibility searchtag
case 'category':
$catId = $record['catId'];
// kijk of het discount catId hetzelfde is als van dit product
$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'];
}
break;
}
//check multiple
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($instanceId){
global $mysqli;
$available = 0;
if($stockResult = $mysqli->query('SELECT inStock, inRetour
FROM shop_stock
WHERE instanceId = '.$instanceId.' LIMIT 1')){
if($stockResult->num_rows > 0){
$stockRecord = $stockResult->fetch_assoc();
//redefine variables
$inStock = $stockRecord['inStock'];
$inRetour = $stockRecord['inRetour'];
//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.instanceId = '.$instanceId.'
AND oi.orderStatus = 0';
$numInOrder = 0;
if($inOrderResult = $mysqli->query($inOrderQuery)){
while($inOrderRecord = $inOrderResult->fetch_assoc()){
$numInOrder += $inOrderRecord['numProducts'];
}
}
else{
$output .= $mysqli->error;
}
// get available
$available = $inStock - $numInOrder;
}
}
return $available;
}
function showPopular($numCol = 6){
global $mysqli;
/* load & display popular collection */
$output = '';
$output .= '<div class="collection-title">';
$output .= '<span class="icon-heart-bullet"></span>';
$output .= '<h2>popular</h2>';
$output .= '</div>';
switch($numCol){
case 6:
$colClass = "hextuple-column";
break;
case 5:
$colClass = "quintuple-column";
break;
case 4:
$colClass = "quadruple-column";
break;
}
$output .= '<div class="'.$colClass.'">';
/* start first row */
$output .= '<div class="product-thumb-row">';
////// dummy //////
/* load products from database */
$query = 'SELECT p.id, p.catId, p.titleNL, p.isNew, p.published, p.price, p.discountPrice, pm.modified
FROM product_products as p, content_status as s, popular_modified AS pm
WHERE s.active = 1
AND s.itemId = p.id
AND s.linkname = "product_products"
AND pm.productId = p.id
ORDER BY pm.total DESC LIMIT '.$numCol;
if($result = $mysqli->query($query)){
$i = 1;
while($record = $result->fetch_assoc()){
/* published ? */
$published = $record['published'];
if($published == 1){
//create productid
$id = $record['id'];
$catId = $record['catId'];
$title = $record['titleNL'];
$linkTitle = linkname($title);
//price
$price = $record['price'];
$displayPrice = displayPrice($price);
//DISCOUNT
$discountPrice = $record['discountPrice'];
$displayDiscountPrice = '';
if(!empty($discountPrice)){
// het product is hard afgeprijsd
$displayDiscountPrice = displayPrice($discountPrice);
}
else{
// als het product niet hard afgeprijsd is.
if($per = checkProductDiscount($id)){
$tempAmount = ($price * $per) / 100;
if($checkAmount = checkPrice($tempAmount)){
$discount = $checkAmount;
$discountPrice = $price - $discount;
$displayDiscountPrice = displayPrice($discountPrice);
}
}
}
//new ?
$new = $record['isNew'];
//thumbnail
$thumb = '';
$instanceQuery = 'SELECT i.id AS instanceId, m.filename_medium, m.filename_hover
FROM product_instances AS i, media_files AS m, content_status AS s
WHERE productId = '.$id.'
AND s.itemId = m.id
AND s.active = 1
AND s.linkname = "media_files"
AND i.shortcode = m.shortcode
ORDER BY i.instanceOrder DESC LIMIT 1';
if($instanceResult = $mysqli->query($instanceQuery)){
$instanceRecord = $instanceResult->fetch_assoc();
$thumb = './images/uploads/'.$instanceRecord['filename_medium'];
$hover = '';
if(!empty($instanceRecord['filename_hover'])) $hover = './images/uploads/'.$instanceRecord['filename_hover'];
}
else{
//echo $mysqli->error;
}
if($instanceResult->num_rows == 0){
// if no image
$thumb = './images/structure/noimage.jpg';
$color = 'ffffff';
}
/* output */
$output .= '<div class="product-thumb-holder ';
if(!($i % 6) ) $output .= ' no-margin';
$output .='">';
//output image
$output .= '<div class="product-thumb-image"';
//on hover?
if(!empty($hover)) $output .= ' onmouseover="hoveroverProduct(\'product'.$id.'\');" onmouseout="hoveroutProduct(\'product'.$id.'\');"';
$output .= '>';
//new ?
if($new == 1) $output .= '<div class="product-thumb-new"><h3>nieuw!</h3></div>';
$output .= '<a href="./toont-het-artikel/'.$linkTitle.'-'.$id.'/">';
if(!empty($hover)) $output .= '<img src="'.$hover.'" alt="Deense Kroon sieraad genaamd '.$title.'" width="160" class="collection_hover" id="product'.$id.'"/>';
$output .= '<img src="'.$thumb.'" alt="Deense Kroon sieraad genaamd '.$title.'" width="160" />';
$output .= '</a>';
$output .= '</div>';
//output title
$output .= '<div class="product-thumb-title">
<a href="./toont-het-artikel/'.$linkTitle.'-'.$id.'/">'.$title.'</a>
</div>';
//output bottom
$output .= '<a href="./toont-het-artikel/'.$linkTitle.'-'.$id.'/"><span class="icon-arrow"></span></a>';
if(empty($displayDiscountPrice)){ $output .= '<span class="product-thumb-price">'.$displayPrice.'</span>'; }
else{ $output .= '<span class="product-thumb-price product-price-line-through">'.$displayPrice.'</span><span class="product-thumb-price-discount">'.$displayDiscountPrice.'</span>';}
$output .= '<a href="./toont-uw-winkelwagen/voeg-product-toe/'.$id.'/"><span class="icon-add-to-cart product-thumb-cart"></span></a>';
$output .= '</div>';
$i++;
}
}
}
$output .= '<div class="clear"></div>';
/* end row */
$output .= '</div>';
$output .= '</div>';
$output .= '<div class="clear"></div>';
return $output;
}
function removeAccents($str) {
$a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ʼn', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ', 'Ά', 'ά', 'Έ', 'έ', 'Ό', 'ό', 'Ώ', 'ώ', 'Ί', 'ί', 'ϊ', 'ΐ', 'Ύ', 'ύ', 'ϋ', 'ΰ', 'Ή', 'ή');
$b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o', 'Α', 'α', 'Ε', 'ε', 'Ο', 'ο', 'Ω', 'ω', 'Ι', 'ι', 'ι', 'ι', 'Υ', 'υ', 'υ', 'υ', 'Η', 'η');
return str_replace($a, $b, $str);
}
/**
* QnD fix for query strings
*
* @return bool
*/
function parseQueryString()
{
if( ! isset($_GET['sub'])) return false;
if( strpos($_GET['sub'],'?') === false) return false;
// Get the query string
$queryString = substr($_GET['sub'],1);
parse_str($queryString,$variables);
// So this wasn't a sub page
unset($_GET['sub']);
// Put query string variables into request
foreach($variables as $key => $value)
{
$_GET[$key] = $value;
}
return true;
}
/**
* Is variant for A / B testing?
*/
function isVariant()
{
// Do we have variant B ?
return isset($_GET['v']) && $_GET['v'] == 'b';
}