ruạṛ
<?php /** * Global functions file * @version 0.9 * @author Robert Urquhart <programmer@activatedesign.co.nz> * @package WEP-CMS */ /** * DATABASE FUNCTIONS */ /** * establish and return a database connection * @return resource */ function connect_to_db() { $mysqluser=MYSQLUSER; $mysqlpasswd=MYSQLPASSWD; $mysqlhost=MYSQLHOST; $connID= mysql_connect($mysqlhost, $mysqluser, $mysqlpasswd); if ($connID) { mysql_select_db(DATABASE); return $connID; } else { $message="There was an error opening data from the database, please try again"; setcookie("message", $message, time()+5); url_redirect($back); return; } } /** * quickly return a single value from the database * only use when you expect exactly one value as a result or want the first returned record only * @param string $table * @param string $field can also be a mysql function eg count(*), max(fieldname) * @param string $id_field can also be a mysql function eg concat_ws(':',page_id,active) * @param string $id * @return mixed can test for === false to detect no rows returned */ function select_one($table, $field, $id_field="1", $id="1") // { $one = mysql_query("select $field from $table where $id_field = '$id'"); if($one && mysql_num_rows($one)>0) { $one = mysql_fetch_row($one); $one = $one[0]; return $one; } else { return false; } } /** * toggle a boolean field in an arbitrary record * @param string $table * @param string $id_field * @param int $id (could also be a string) * @param string field * @return int */ function flip_switch($table, $id_field='', $id=0, $bool_field="active") { // rational default if($id_field == ''){$id_field = $table.'_id';} //check for existance of table/field/id combo $result=@mysql_query("select $bool_field from $table where $id_field = '$id'"); if(!$result || mysql_num_rows($result)==0) { return false; //we can check for === false to tell if the check failed exit; } else { // get current value and reverse $row=mysql_fetch_row($result); $active = ($row[0]==0) ? 1 : 0; //if there is a wierd value in the database this will catch it if(!$update = mysql_query("update $table set $bool_field = '$active' where $id_field = '$id'")) { return $row[0]; //existing state } //else return $active; //new state } } /** * DATA CLEANING AND VALIDATION */ /** * clean data of html tags eg script and escape for database entry * @param string $input * @return string */ function clean_plain_data($input) { return mysql_real_escape_string(htmlentities(strip_tags(stripslashes($input)),ENT_QUOTES,'UTF-8')); } /** * clean data of html tags eg script and escape for database entry */ function clean_html_data($input) { return mysql_real_escape_string(htmlentities(trim(stripslashes($input)),ENT_QUOTES,'UTF-8')); } /** * undo escaping * @param string $str * @return string */ function unescape_lines($str) { return str_replace(array('\r\n','\n'),"\n",$str); } /** * confirm that a number is 0 or a +ve integer & by default abort script if not * by default don't return any possibly clueful error messages, or go to a useful page * note in practice I've found we usually don't abort but return a harmless value and test it * @param string $id * @param bool $abort action to take if validation fails * @param string $message message to include when aborting * @param string $url page to abort to * @return mixed (functionally bool) */ function is_numeric_id($id, $abort=true, $message = '', $url='index.php') { if(!ctype_digit((string)$id)) { if($abort) { die('not numeric '.$id); //debugging getout($message, $url); exit; } else { return false; } } return $id; } /** * validate integer value by default float >= 0 * secondarily strip out thousands separator * @param string $v * @param float $min minimum value default for positive numbers only * @param float $max maximum value * @return string */ function is_decimal_data($v='',$min=0, $max=NULL) { //global $message; /* * validate bounds and exit on fail * (ie if someone has made an error entering parameters we do not want the function to continue) */ if( ($min != 0 && !filter_var($min,FILTER_VALIDATE_FLOAT)) || !(is_null($max) || filter_var($max,FILTER_VALIDATE_INT)) ) { //$message .= "$v Min $min Max $max fail 1 <br />"; return false; } /* * remove thousands separator (allowed in user input) */ $v = str_replace(',','',$v); /* * check format and against bounds * why doesn't FILTER_VALIDATE_FLOAT have the same sort of options as FITER_VALIDATE_INT? */ if(!($v==0 || filter_var($v, FILTER_VALIDATE_FLOAT)) || $v < $min || (!is_null($max) && $v > $max) ) { //$message .= "$v Min $min Max $max fail 2 <br />"; return false; } //else return $v; } /** * validate hexadecimal number (eg CSS colour) * @param string $v * @param bool $short allow 3-letter version (FFCC00 == FC0) * @return string */ function is_hex($v='',$short=true) { /* * remove leading # (allowed in user input) * (a non-leading # implies an input error requiring checking by the user) */ $v = preg_replace(array('/^#/'),'',$v); if($short){ return (preg_match('/^[0-9a-fA-F]{3}|[0-9a-fA-F]{6}$/',$v)) ? $v : false; } //else return (preg_match('/^[0-9a-fA-F]{6}$/',$v)) ? $v : false; } /** * validate email address, exclude local email addresses (eg @localhost - see {@link http://nz.php.net/manual/en/filter.filters.validate.php }) * backported (direct replacement) WEP3 version 2012-12-10 * @param string $email address to check * @return string (functionally bool) */ function is_email($email) { if(filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.*\..*$/',$email) //make sure there is at least one '.' after the @ ) { return $email; } //else return false; } /** * strip out special characters and replace spaces to make a valid directory name * @var string $txt input * @return str */ function dir_name($txt) { // :punct: Does not replace emdashes and endashes, so these need to be replaced separately $txt = preg_replace(array('/&[^;]*;/', '/[[:punct:]]/','/[[:blank:]]/',"/–/","/—/",),array('','','-','-','-'),trim(html_entity_decode($txt,ENT_QUOTES)) ); $txt = preg_replace("/(-){2,}/",'-',$txt); return $txt; } /** * strip out special characters (allow .) and replace spaces to make a valid file name * http://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words * @var string $txt input * @return str */ function file_name($txt) { $txt = preg_replace(array('/[\/\\?%*–—:|"<>]/','/[[:blank:]]/'),array('','-'),trim(html_entity_decode($txt,ENT_QUOTES)) ); $txt = preg_replace("/(-){2,}/",'-',$txt); return $txt; } /** * generate a random salt of specified length for encrypting passwords * @param int $n length of string to return */ function mmm_salt($n=22) { /** * @var string $chars valid chracters to include in the salt * @var string $salt string to return * @var int $i number of characters currently in $salt */ $chars = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; $salt = ''; $i = 0; while ($i < $n) { /* * get a random character and append it to the salt string, increment the counter */ $salt .= substr($chars, mt_rand(0, strlen($chars)-1), 1); $i++; } return $salt; } /** * SCRIPT HANDLING FUNCTIONS */ /** * store message to be displayed on next page and exit processing script * @param string $message * @param string $url page to go to if not going "back" */ function getout($message='', $url='') { if(strpos($url,'?')===0) { //$r=$_SERVER['HTTP_REFERER']; //$url = (strpos($r,'?')) ? $r.'&'.ltrim($url,'?') : $r.$url; $oldUrl = $_SERVER["HTTP_REFERER"]; $oldQuery = parse_url($oldUrl, PHP_URL_QUERY); $severedUrl = explode("?", $oldUrl); $oldParameters = array(); parse_str($oldQuery, $oldParameters); $newQuery = $url; $newQuery[0] = "&"; $newParameters = array(); parse_str($newQuery, $newParameters); $parameters = array_merge($oldParameters, $newParameters); $url = $severedUrl[0] . "?"; foreach($parameters as $parameterKey => $parameterValue) { $url .= $parameterKey . "=" . $parameterValue . "&"; } $url = rtrim($url, "&"); } elseif($url==''){$url=getenv('HTTP_REFERER');} //setcookie("message", $message, time()+60*60); $_SESSION['message'] = $message; header("Location: $url"); exit; } /** * DISPLAY FUNCTIONS */ /** * generate nested list of pages with info needed for summary displays * recursive * @todo make pages objects then we can just return an array of them * @param $parent return only children of this page (all pages for 0) * @return array */ function build_page_tree($parent=0) { $connID = connect_to_db(); $tree = array(); $pages = mysql_query("select * from page_data where parent_id = '$parent' order by menu_id, position"); // echo mysql_error(); // debugging while($p = mysql_fetch_assoc($pages)) { $path = ($p['external']) ? $p['external_path'] : $p['path']; $tree[$p['page_id']] = array('page_id'=>$p['page_id'] ,'name'=>$p['name'] ,'type'=>$p['page_type'] ,'parent_id'=>$p['parent_id'] ,'path'=>$path ,'position'=>$p['position'] ,'active'=>$p['active'] ,'menu'=>$p['menu'] ,'menu_id'=>$p['menu_id'] ,'text'=>$p['menu_text'] ,'home'=>$p['index_page'] ,'error'=>$p['error_page'] ,'external'=>$p['external'] ,'visited'=>$p['visited'] ,'branches'=>build_page_tree($p['page_id']) //recursive ); } return $tree; } /** * generate list of pages as <option>s for use in select boxes * recursive * @param $pages page tree generated by build_page_tree() * @param bool $selected * @param int $tier what level of the tree we are at (styling and compare to $depth) * @param bool $menu only pages with on_menu? * @param int $depth how many tiers down to stop (compare with $tier) (0 = output all) * @param bool $opts wrap in <optgroup> * @return string */ function build_page_select($pages=array(), $selected=0, $tier=1, $menu=0,$depth=0, $opts=false) { $rows = ""; foreach($pages as $p) { if($opts && $p['menu_id'] != $menu) { $rows .= ($menu==0) ? '':'</optgroup>'."\n"; $rows .= '<optgroup label="'.select_one('menus','menu_title','menu_id',$p['menu_id']).'">'."\n"; $menu = $p['menu_id']; } $name = $p['name']; if($p['home']){ $name .= ' (homepage)'; } if($p['error']){ $name .= ' (404 page)'; } for($i=1;$i<$tier;$i++) { $name = '-'.$name; } $name = '<span class="tier-'.$tier.'"> '.$name.'</span>'; $rows .= '<option value="'.$p['page_id'].'" class="tier-'.$tier.'"'; $rows .= ($p['page_id']==$selected) ? ' selected="selected"' : ''; $rows .= '>'.$name."</option>\n"; if($tier < $depth || $depth == 0) { $rows .= build_page_select($p['branches'],$selected,$tier+1,$menu,$depth); // recursive } } if($opts) { $rows .= '</optgroup>'; } return $rows; } /** * generate nested list of categories with info needed for summary displays * @todo make categories objects then we can just return an array of them * @param $parent return only children of this category (all categories for 0) * @return array */ function build_category_tree($parent=0) { $connID = connect_to_db(); $tree = array(); $categories = mysql_query("select * from categories where parent_id = '$parent' order by position"); echo mysql_error(); // debugging while($c = mysql_fetch_assoc($categories)) { $tree[] = array('cat_id'=>$c['cat_id'] ,'name'=>$c['cat_name'] ,'path'=>$c['cat_path'] ,'title'=>$c['title'] ,'keywords'=>$c['keywords'] ,'description'=>$c['description'] ,'content'=>$c['content'] ,'products'=>$c['num_products'] ,'menu'=>$c['menu'] ,'parent_id'=>$c['parent_id'] ,'position'=>$c['position'] ,'active'=>$c['active'] ,'featured'=>$c['featured'] ,'sidebar'=>$c['sidebar'] ,'visited'=>$c['visited'] ,'branches'=>build_category_tree($c['cat_id']) //recursive ); } return $tree; } /** * generate list of categories as <option>s for use in select boxes * recursive * @param $cats tree generated by build_category_tree() * @param int $tier what level of the tree we are at (styling and compare to $depth) * @param bool $menu only categories with on_menu? * @param int $depth how many tiers down to stop (compare with $tier) (0 = output all) * @param bool $opts wrap in <optgroup> * @return string */ function build_category_select($cats=array(), $tier=1, $menu=0,$depth=0, $opts=false) { global $category_id; $rows = ''; foreach($cats as $c) { $name = $c['name']; for($i=1;$i<$tier;$i++) { $name = '-'.$name; } // $name = '<span class="tier-'.$tier.'"> '.$name.'</span>'; $rows .= '<option value="'.$c['cat_id'].'" class="tier-'.$tier.'"'; $rows .= ($c['cat_id'] == $category_id) ? ' selected="selected"' : ''; $rows .= '>'.$name."</option>\n"; if($tier < $depth || $depth == 0) { $rows .= build_category_select($c['branches'],$tier+1,$menu,$depth); // recursive } } if($opts) { //$rows .= '</optgroup>'; } return $rows; } /** * Generate nested list of categories with info needed for summary displays * @param array $cats * @param array $selected * @param int $tier * @param int $depth * @return string */ function build_category_checkboxes($cats=array(), $selected=array(), $tier=1, $depth=0) { $rows = ''; foreach($cats as $c) { $name = $c['name']; for($i=1;$i<$tier;$i++) { $name = '-'.$name; } $name = '<span> '.$name.'</span>'; $id = $c['cat_id']; $rows .= '<label for="cat-'.$id.'" class="tier-'.$tier.'"><input type="checkbox" name="category['.$id.']" id="cat-'.$id.'" value="1"'; $rows .= (in_array($c['cat_id'],$selected)) ? ' checked="checked"' : ''; $rows .= ' />'.$name.'</label> '; if($tier < $depth || $depth == 0) { $rows .= build_category_checkboxes($c['branches'],$selected,$tier+1,$depth); // recursive } } return $rows; } /** * build a list of checkboxes to go with MODULE_CUSTOMER_INTERESTS * @param array $interests * @param array $selected * @return string */ function build_interest_checkboxes($interests=array(), $selected=array()) { if(!is_array($selected)) { $selected = array($selected); } $rows = ''; foreach($interests as $name => $label) { $rows .= '<label for="'.$name.'"><input type="checkbox" name="'.$name.'" id="'.$name.'" value="'.$label.'"'; $rows .= (in_array($name,$selected)) ? ' checked="checked"' : ''; $rows .= ' />'.$label.'</label> '; } return $rows; } /** * build a list of next/prev page links * @param int $records total number of records in the set * @param int $dpp dispaly per page * @param int $start where we are now * @param string $query_string extra variables to append ('start' is generated for each link by the function) * @param bool $echo output immediately or return in practice we almost always return to an echo in the script so it is clear what is happening * @return string */ function paging($records,$dpp,$start,$query_string='',$echo=false) { $pages = ceil($records/$dpp); $this_page = floor($start/$dpp)+1; $url = $_SERVER['PHP_SELF'].'?start='; $paging = ''; if($start > 0) { $paging .= '<a href="'.$url.($start-$dpp).'&'.$query_string.'" class="move" ><< Previous</a> '; } if($records > $dpp) { if($start > 0) { $paging .= "- "; } $paging .= "<a href=\"{$url}0&$query_string\" "; if($this_page==1){$paging .= "class=\"current\"";} $paging .= ">1</a> "; $i = $f =0; if($pages > 10) { $i = $this_page-4; $f = $this_page+4; } if($i > 2) { $paging .= "... "; } else { $i = 2; $f = 9; $paging .= "- "; } if($f >= $pages) { $f = $pages-1; if(($f-$i < 7) && $pages > 10 ) $i = $f-7; } while($i<=$f) { $s = $dpp*($i-1); //starting record if($i==$this_page) { $paging .= "<a href=\"{$url}$s&$query_string\" "; if($this_page==$i){$paging .= "class=\"current\"";} $paging .= ">$i</a></b> - "; } else { $paging .= "<a href=\"{$url}$s&$query_string\" >$i</a> - "; } $i++; //echo "$records $pages $i $f $s $paging "; exit; } if($pages > $f+1) { $paging = substr($paging,0,-2); $paging .= "... "; } $paging .= "<a href=\"{$url}".($dpp*($pages-1))."&$query_string\" "; if($this_page==$pages){$paging .= "class=\"current\"";} $paging .= ">$pages</a> "; } if($this_page < $pages) { $paging .= '- <a href="'.$url.($start+$dpp).'&'.$query_string.'" class="move" >Next >></a>'; } $paging = "<p class=\"pages\">$paging</p>"; if($echo) echo $paging; return $paging; } /** * Format float to price for display, usually going into a string so return rather than echo * @var float $price; * @return string */ function format_price($price) { return '$'.number_format($price,2); } /** * Utilities */ /** * return the code for a toggle state */ function onOrOff($flag=0){ return ($flag) ? '<span class="on">✔</span>' : '<span class="off">✘</span>'; } /** * return the singular of most common plurals * @param string $str * @return string */ function dict_singular($str) { if(preg_match('/ies$/',$str)) { return substr($str,0,-3).'y'; } elseif(preg_match('/s$/',$str)) { return substr($str,0,-1); } else { return $str; } } /** * FILESYSTEM FUNCTIONS */ /** * Check directory path and create stub file * @param string $path directory we want created * @param array $contents variables and values to include in file * @global string $message * @return bool */ function create_stub_file($path = '', $contents = array()) { global $message; /** * san check - empty path, attempts to go up a level, invalid contents */ if(!$path || strpos($path,'.') !== false || !is_array($contents) || empty($contents)) { $message .= 'Unable to create file: path or contents are empty. <br />'; return false; } /** * san check to prevent arbitrary code being written into the file * also we do not allow a leading _ or byte characters */ foreach($contents as $var => $val) { if(!preg_match('/^[a-zA-Z][a-zA-Z0-9_]*$/',$var) || !is_numeric_id($val,0)) { $message .= 'Unable to create file: invalid '.clean_plain_data($var).' ('.clean_plain_data($val).') <br />'; return false; //abort on first fail } } /** * check for/create product directory/url */ $dir = DOC_ROOT.$path; if(file_exists($dir)) { $message .= 'Unable to create file: directory already exists. <br />'; return false; } //else if(!mkdir($dir, 0755)) { $message .= 'There was an error creating the directory path: '.$dir.' <br />'; exit; } //else chmod($dir, DIR_PERMS); /** * create file * @var string $code */ $page_file= $dir."/index.php"; $code="<?php \n"; foreach($contents as $var => $val) { $code .= "\$$var = $val;\n"; } $code .= "require_once(\$_SERVER['DOCUMENT_ROOT'].'/resources/template/template.php');\n?>"; file_put_contents($page_file, $code); chmod($page_file, FILE_PERMS); return true; } /** * recursively delete all files and sub-directories in a directory * @param string $dh directory path * @param bool $self delete this directory as well as contents? * @return bool */ function clean_dir($dh, $self=false) { global $message; //$message .= $self ? 'self true <br />' : 'self false <br />'; /* * remove trailing slash if present */ $dh = rtrim($dh,'/'); if($dh==DOC_ROOT) { $message .= "WARNING: cannot delete root directory"; return false; } /** * check valid directory, empty * @var resource $do open directory */ if($dh && is_dir($dh)) { $do = opendir($dh); while ($i = readdir($do)) { if($i == "." || $i == ".."){ } // do nothing elseif(is_dir("$dh/$i")){ clean_dir("$dh/$i"); rmdir("$dh/$i"); } else { unlink("$dh/$i"); } } closedir($do); if($self) { rmdir("$dh"); return true; } } //else return false; } /** * upload a file * @var string $upload name of form file field * @var string $dir directory to place files in * @var string $filename optional filename (use $upload filename by default) * @global array $FILE_TYPES * @return string $message */ function upload_file($upload,$dir,$filename='') { global $FILE_TYPES; $message = ''; /* * do we have a file? */ if ($_FILES[$upload] && is_uploaded_file($_FILES[$upload]['tmp_name'])) { /* * check for upload errors */ if (($_FILES[$upload]['error'] > 0 )) { switch ($_FILES[$upload]['error']) { case 1: $message .= 'File exceeded maximum allowed filesize.<br />'; break; case 2: $message .= 'File exceeded maximum allowed filesize.<br />'; break; case 3: $message .= 'File was only partially uploaded. Please try again.<br />'; break; case 4: $message .= 'No file selected.<br />'; break; } if ($message != '') { return $message; } } /* * check file type */ $name = $_FILES[$upload]['name']; $suffix = ltrim(strrchr($name,'.'),'.'); if(!in_array($suffix,array_keys($FILE_TYPES))) { $message .= $suffix.'Invalid file type. <br />'; return $message; } //$message .="|$name|"; //debugging if(!$filename) { $filename = $name; } //$message .="|$filename|"; //debugging $filepath = $dir.$filename; //$message .= $filepath.'<br />'.$thumbpath; //debugging /* * copy in file and resize */ if (!move_uploaded_file($_FILES[$upload]['tmp_name'], $filepath)) { $message .= "There was a problem relocating the $type file. Please try again.<br />"; continue; } else { $message .= strtoupper($type)." file successfully uploaded. <br />"; //chmod($filepath, 0777); } } else { //$message .= "No file selected for $upload.<br />"; } return $message; } /** * return the appropriate suffix for an image type * @param string $filename (path) * @return string */ function image_suffix($filename='') { $suff = ''; if($filename && file_exists($filename)) { switch(exif_imagetype($filename)) { case IMAGETYPE_GIF: $suff = '.gif'; break; case IMAGETYPE_JPEG: $suff = '.jpg'; break; case IMAGETYPE_PNG: $suff = '.png'; break; } } return $suff; } /* * resize an image (not just for thumbnails) * @param string $file source file * @param string $target destination file * @param int $maxWidth * @param int $maxHeight * @return string $message */ function thumbnail($file,$target,$maxWidth,$maxHeight) { $message = ''; list($width, $height, $type) = @getimagesize($file); //san check $maxWidth = round($maxWidth); $maxHeight = round($maxHeight); if(($width <= $maxWidth || $maxWidth == 0) && ($height <= $maxHeight || $maxHeight == 0)) { // no resizing required copy($file,$target); return; } //$message .= "Image starts at $width x $height<br />"; //debugging //@todo combine operations if ($width > $maxWidth && $maxWidth>0) //skip if $maxWidth == 0 or -ve { (integer)$iw=$maxWidth; (integer)@$ih=$height/($width/$maxWidth); //$img_src = @imagecreatefromjpeg( $file ); switch ($type) { case IMAGETYPE_GIF: $img_src = imagecreatefromgif($file); $img_dst = @imagecreatetruecolor( $iw, $ih ); break; case IMAGETYPE_JPEG: $img_src = imagecreatefromjpeg($file) ; $img_dst = @imagecreatetruecolor( $iw, $ih ); break; case IMAGETYPE_PNG: $img_src = imagecreatetruecolor($width, $height); imagealphablending($img_src, false); imagesavealpha($img_src, true); $transparent = imagecolorallocatealpha($img_src, 255, 255, 255, 127); //imagefilledrectangle($img_src, 0, 0, $width, $height, $transparent); imagefill($img_src, 0, 0, $transparent); $source = imagecreatefrompng($file); imagealphablending($source, false); imagesavealpha($source, true); imagecopyresampled($img_src, $source, 0, 0, 0, 0, $width, $height, $width, $height); imagedestroy($source); $img_dst = @imagecreatetruecolor( $iw, $ih ); imagealphablending($img_dst, false); imagesavealpha($img_dst, true); $transparent = imagecolorallocatealpha($img_dst, 255, 255, 255, 127); //imagefilledrectangle($img_src, 0, 0, $width, $height, $transparent); imagefill($img_dst, 0, 0, $transparent); break; default: $message .= "Invalid image type for $file. Please upload a .jpg, .png or .gif image.<br />"; return $message; break; } @imagecopyresampled( $img_dst, $img_src, 0, 0, 0, 0, $iw, $ih, $width, $height); imagedestroy($img_src); switch($type) { case IMAGETYPE_GIF: $new_img = imagegif($img_dst, $target); break; case IMAGETYPE_JPEG: $new_img = imagejpeg( $img_dst, $target, 99 ); break; case IMAGETYPE_PNG: $new_img = imagepng($img_dst, $target, 0); break; default: } /* if( !@imagejpeg( $img_dst, $target, 99 ) ) { $message .= "Error creating $target.<br />"; return $message; } */ //$message .= "Resizes by width to $iw x $ih <br />"; //debugging /* * new height - can't rely on calculated height to match generated image +/- 1px */ //$message .= "New image $width x $height<br />"; //debugging list($width, $height, $type) = @getimagesize($target); $file = $target; //reassign source image for height resizing } // end width if ($height > $maxHeight && $maxHeight >0) //skip if $maxHeight == 0 or -ve { //list($width, $height, $type, $attr) = @getimagesize($target); (integer)$ih=$maxHeight; (integer)@$iw=$width/($height/$maxHeight); //$img_src = @imagecreatefromjpeg( $file ); switch ($type) { case IMAGETYPE_GIF: $img_src = imagecreatefromgif($file); $img_dst = @imagecreatetruecolor( $iw, $ih ); break; case IMAGETYPE_JPEG: $img_src = imagecreatefromjpeg($file) ; $img_dst = @imagecreatetruecolor( $iw, $ih ); break; case IMAGETYPE_PNG: $img_src = imagecreatetruecolor($width, $height); imagealphablending($img_src, false); imagesavealpha($img_src, true); $transparent = imagecolorallocatealpha($img_src, 255, 255, 255, 127); //imagefilledrectangle($img_src, 0, 0, $width, $height, $transparent); imagefill($img_src, 0, 0, $transparent); $source = imagecreatefrompng($file); imagealphablending($source, false); imagesavealpha($source, true); imagecopyresampled($img_src, $source, 0, 0, 0, 0, $width, $height, $width, $height); imagedestroy($source); $img_dst = @imagecreatetruecolor( $iw, $ih ); imagealphablending($img_dst, false); imagesavealpha($img_dst, true); $transparent = imagecolorallocatealpha($img_dst, 255, 255, 255, 127); //imagefilledrectangle($img_src, 0, 0, $width, $height, $transparent); imagefill($img_dst, 0, 0, $transparent); break; default: $message .= "Invalid image type for $file. Please upload a .jpg, .png or .gif image. (3)<br />"; return $message; break; } @imagecopyresampled( $img_dst, $img_src, 0, 0, 0, 0, $iw, $ih, $width, $height); imagedestroy($img_src); /* if( !@imagejpeg( $img_dst, $target, 99 ) ) { $message .= "Error creating $target.<br />"; return $message; } */ switch($type) { case IMAGETYPE_GIF: $new_img = imagegif($img_dst, $target); break; case IMAGETYPE_JPEG: $new_img = imagejpeg( $img_dst, $target, 99 ); break; case IMAGETYPE_PNG: $new_img = imagepng($img_dst, $target, 0); break; default: } //$message .= "Resizes by height to $iw x $ih <br />"; //debugging } // end height //list($width, $height, $type) = @getimagesize($target); //$message .= "New image $width x $height<br />"; //debugging return $message;// compact('width','height'); } /** * upload and resize an image * @var string $upload name of form file field * @var array $dims dimensions for resizing * @var string $dir directory to place images in * @var string $filename optional filename (use $upload by default) * @var bool $thumbnail create a thumbnail * @return string $message * @todo use global $message and return bool */ function upload_image($upload,$dim,$dir,$filename='',$thumbnail=true) { $message = ''; /* * do we have a file? */ if ($_FILES[$upload]) // && is_uploaded_file($_FILES[$upload]['tmp_name']) fails on error 1 before geting to error checking { /* * check for upload errors */ if (($_FILES[$upload]['error'] > 0 )) { switch ($_FILES[$upload]['error']) { case 1: $message .= 'Image exceeded maximum allowed filesize.<br />'; break; case 2: $message .= 'Image exceeded maximum allowed filesize.<br />'; break; case 3: $message .= 'Image was only partially uploaded. Please try again.<br />'; break; case 4: $message .= 'No image selected.<br />'; break; } if ($message != '') { return $message; } } $suff = image_suffix($_FILES[$upload]['tmp_name']); if(!$suff) { $message .= "Invalid image type for $upload. Please upload a .jpg, .png or .gif image.<br />"; return $message; } //$message .="|$filename|"; //debugging if(!$filename) { $filename = $upload.$suff; } $filepath = $dir.$filename; $thumbpath = $dir.THUMBNAIL_PREFIX.$filename; //$message .= $filepath.'<br />'.$thumbpath; //debugging /* * copy in file and resize */ if (!move_uploaded_file($_FILES[$upload]['tmp_name'], $filepath)) { $message .= "There was a problem relocating the $upload image file. Please try again.<br />"; return $message; } else { $message .= ucfirst(str_replace('_', ' ', $upload))." image successfully uploaded. <br />"; //perform resizing $message .= thumbnail($filepath,$filepath,$dim['w'],$dim['h']); chmod($filepath, FILE_PERMS); if($thumbnail) { $message .= thumbnail($filepath,$thumbpath,$dim['tw'],$dim['th']); //don't send width or height - they're from the pre-resized $filepath chmod($thumbpath, FILE_PERMS); } } } else { $message .= "No image selected for $upload.<br />";//.print_r($_FILES,true); } return $message; } /** * update all the images in a standard block * @param $dim array dimensions * @param string $upload name of the form fields (array) */ function update_images($dim=array(), $upload = 'image') { global $message; /** * replacement files */ if(isset($_FILES[$upload])) { foreach($_FILES[$upload]['name'] as $image => $filename){ if($filename!='') { $id = ltrim($image,'image'); list($image_path,$image_filename) = explode(':',select_one('image_data',"concat_ws(':',image_path,image_filename)",'image_id',$id)); $currentType = image_suffix(DOC_ROOT.$image_path.$image_filename); $newType = image_suffix($_FILES[$upload]['tmp_name'][$image]); //$message .= IMAGETYPE_JPEG."Current: $currentType ; New: $newType <br />"; //debugging $message .= "$image $image_path"; upload_product_image($image,$dim,DOC_ROOT.$image_path); if($newType && file_exists(DOC_ROOT.$image_path.$image.$newType)) { if($newType != $currentType) { mysql_query("update image_data set image_filename = '$image$newType' where image_id = '$id'"); @unlink(DOC_ROOT.$image_path.$image_filename); @unlink(DOC_ROOT.$image_path.THUMBNAIL_PREFIX.$image_filename); } list($w,$h) = getimagesize(DOC_ROOT.$image_path.$image.$newType); mysql_query("update image_data set width = '$w', height = '$h' where image_id = '$id'"); } } else { // $message .= "$filename empty for $image. ".print_r($_FILES,true).'<br />'; } } } else { //$message .= '$_FILES['.$upload.'] not found. '.print_r($_FILES,true).'<br />'; } /** * image captions */ if(isset($_POST[$upload.'_caption']) && is_array($_POST[$upload.'_caption'])) { foreach($_POST[$upload.'_caption'] as $image => $caption){ $id = ltrim($image,'caption'); $caption = clean_plain_data($caption); mysql_query("update image_data set title = '$caption' where image_id = '$id'"); } } /** * image links * don't use these in standard installation but have left code in here in case it is required in future */ if(isset($_POST[$upload.'_link']) && is_array($_POST[$upload.'_link'])) { foreach($_POST[$upload.'_link'] as $image => $link){ $id = ltrim($image,'image'); $link = clean_plain_data($link); mysql_query("update image_data set link = '$link' where image_id = '$id'"); } } /** * image order */ if(isset($_POST[$upload.'_position']) && is_array($_POST[$upload.'_position'])) { $p = order_for_db($_POST[$upload.'_position']); foreach($p as $id => $pos){ if(is_numeric_id($id,0)) { mysql_query("update image_data set image_position = '$pos' where image_id = '$id'"); } } /* asort($p); $i = 10; foreach($p as $id => $pos){ //actual entered value ($pos) is irrelevant if($id=='new'){$id=$img_id;} if(is_numeric_id($id,0)>0) //skip $img_id == 0 (no new file uploaded) and any injected non-numeric ids { mysql_query("update image_data set image_position = '$i' where image_id = '$id'"); } $i+=10; } */ } } /** * upload and resize a slideshow image - because $_FILES is structured differently * @var string $upload name of form file field * @var array $dims dimensions for resizing * @var string $dir directory to place images in * @var string $filename optional filename (use $upload by default) * @var bool $thumbnail create a thumbnail * @return string $message */ function upload_slideshow_image($upload,$dim,$dir,$filename='',$thumbnail=true) { global $message; //$message .= print_r($_FILES,true); /* * do we have a file? */ if ($_FILES['slideshow'] && is_uploaded_file($_FILES['slideshow']['tmp_name'][$upload])) { /* * check for upload errors */ if (($_FILES['slideshow']['error'][$upload] > 0 )) { $m = ''; switch ($_FILES['slideshow']['error'][$upload]) { case 1: $m .= 'Image exceeded maximum allowed filesize.<br />'; break; case 2: $m .= 'Image exceeded maximum allowed filesize.<br />'; break; case 3: $m .= 'Image was only partially uploaded. Please try again.<br />'; break; case 4: $m .= 'No image selected.<br />'; break; } if ($m != '') { $message .= $m; return false; } } $suff = image_suffix($_FILES['slideshow']['tmp_name'][$upload]); if(!$suff) { $message .= "Invalid image type for $upload. Please upload a .jpg, .png or .gif image.<br />"; return false; } //$message .="|$filename|"; //debugging if(!$filename) { $filename = $upload.$suff; } $filepath = $dir.$filename; $thumbpath = $dir.THUMBNAIL_PREFIX.$filename; //$message .= $filepath.'<br />'.$thumbpath; //debugging /* * copy in file and resize */ if (!move_uploaded_file($_FILES['slideshow']['tmp_name'][$upload], $filepath)) { $message .= "There was a problem relocating the $upload image file. Please try again.<br />"; return false; } else { $message .= $filename." successfully uploaded. <br />"; //perform resizing $message .= thumbnail($filepath,$filepath,$dim['w'],$dim['h']); chmod($filepath, FILE_PERMS); if($thumbnail) { $message .= thumbnail($filepath,$thumbpath,$dim['tw'],$dim['th']); chmod($thumbpath, FILE_PERMS); } } } else { //$message .= "No image selected for $upload.<br />"; //debugging } return true; } /** * upload and resize a product gallery image - because $_FILES is structured differently * @var string $upload name of form file field * @var array $dims dimensions for resizing * @var string $dir directory to place images in * @var string $filename optional filename (use $upload by default) * @var bool $thumbnail create a thumbnail * @return string $message */ function upload_product_image($upload,$dim,$dir,$filename='',$thumbnail=true) { global $message; //$message .= print_r($_FILES,true); /* * do we have a file? */ if ($_FILES['image'] && is_uploaded_file($_FILES['image']['tmp_name'][$upload])) { /* * check for upload errors */ if (($_FILES['image']['error'][$upload] > 0 )) { $m = ''; switch ($_FILES['image']['error'][$upload]) { case 1: $m .= 'Image exceeded maximum allowed filesize.<br />'; break; case 2: $m .= 'Image exceeded maximum allowed filesize.<br />'; break; case 3: $m .= 'Image was only partially uploaded. Please try again.<br />'; break; case 4: $m .= 'No image selected.<br />'; break; } if ($m != '') { $message .= $m; return false; } } $suff = image_suffix($_FILES['image']['tmp_name'][$upload]); if(!$suff) { $message .= "Invalid image type for $upload. Please upload a .jpg, .png or .gif image.<br />"; return false; } //$message .="|$filename|"; //debugging if(!$filename) { $filename = $upload.$suff; } $filepath = $dir.$filename; $thumbpath = $dir.THUMBNAIL_PREFIX.$filename; //$message .= $filepath.'<br />'.$thumbpath; //debugging /* * copy in file and resize */ if (!move_uploaded_file($_FILES['image']['tmp_name'][$upload], $filepath)) { $message .= "There was a problem relocating the $upload image file. Please try again.<br />"; return false; } else { $message .= $filename." successfully uploaded. <br />"; //perform resizing $message .= thumbnail($filepath,$filepath,$dim['w'],$dim['h']); chmod($filepath, FILE_PERMS); if($thumbnail) { $message .= thumbnail($filepath,$thumbpath,$dim['tw'],$dim['th']); chmod($thumbpath, FILE_PERMS); } } } else { $message .= "No image selected for $upload.<br />"; //debugging } return true; } /** * upload and resize a gallery image - because $_FILES is structured differently * copy of upload_slideshow image - needs generalised * @var string $upload name of form file field * @var array $dims dimensions for resizing * @var string $dir directory to place images in * @var string $filename optional filename (use $upload by default) * @var bool $thumbnail create a thumbnail * @return string $message */ function upload_gallery_image($upload,$dim,$dir,$filename='',$thumbnail=true) { $message = ''; /* * do we have a file? */ if ($_FILES['gallery'] && is_uploaded_file($_FILES['gallery']['tmp_name'][$upload])) { /* * check for upload errors */ if (($_FILES['gallery']['error'][$upload] > 0 )) { switch ($_FILES['gallery']['error'][$upload]) { case 1: $message .= 'Image exceeded maximum allowed filesize.<br />'; break; case 2: $message .= 'Image exceeded maximum allowed filesize.<br />'; break; case 3: $message .= 'Image was only partially uploaded. Please try again.<br />'; break; case 4: $message .= 'No image selected.<br />'; break; } if ($message != '') { return $message; } } $suff = image_suffix($_FILES['gallery']['tmp_name'][$upload]); if(!$suff) { $message .= "Invalid image type for $upload. Please upload a .jpg, .png or .gif image.<br />"; return $message; } //$message .="|$filename|"; //debugging if(!$filename) { $filename = $upload.$suff; } $filepath = $dir.$filename; $thumbpath = $dir.THUMBNAIL_PREFIX.$filename; //$message .= $filepath.'<br />'.$thumbpath; //debugging /* * copy in file and resize */ if (!move_uploaded_file($_FILES['gallery']['tmp_name'][$upload], $filepath)) { $message .= "There was a problem relocating the $upload image file. Please try again.<br />"; return false; } else { $message .= $filename." successfully uploaded. <br />"; //perform resizing $message .= thumbnail($filepath,$filepath,$dim['w'],$dim['h']); chmod($filepath, FILE_PERMS); if($thumbnail) { $message .= thumbnail($filepath,$thumbpath,$dim['tw'],$dim['th']); chmod($thumbpath, FILE_PERMS); } } } else { $message .= "No image selected for $upload.<br />"; } return $message; } /** * upload and resize a set image - because $_FILES is structured differently * generalised version of upload_slideshow image * @var string $set name of form file fields * @var string $upload specific name of form file * @var array $dims dimensions for resizing * @var string $dir directory to place images in * @var string $filename optional filename (use $upload by default) * @var bool $thumbnail create a thumbnail * @return string $message */ function upload_set_image($set,$upload,$dim,$dir,$filename='',$thumbnail=true) { global $message; /* * do we have a file? */ if ($_FILES[$set] && is_uploaded_file($_FILES[$set]['tmp_name'][$upload])) { /* * check for upload errors */ if (($_FILES[$set]['error'][$upload] > 0 )) { $m = ''; switch ($_FILES[$set]['error'][$upload]) { case 1: $m .= 'Image exceeded maximum allowed filesize.<br />'; break; case 2: $m .= 'Image exceeded maximum allowed filesize.<br />'; break; case 3: $m .= 'Image was only partially uploaded. Please try again.<br />'; break; case 4: $m .= 'No image selected.<br />'; break; } if ($message != '') { $message .= $m; return false; } } $suff = image_suffix($_FILES[$set]['tmp_name'][$upload]); if(!$suff) { $message .= "Invalid image type for $upload. Please upload a .jpg, .png or .gif image.<br />"; return false; } //$message .="|$filename|"; //debugging if(!$filename) { $filename = $upload.$suff; } $filepath = $dir.$filename; $thumbpath = $dir.THUMBNAIL_PREFIX.$filename; //$message .= $filepath.'<br />'.$thumbpath; //debugging /* * copy in file and resize */ if (!move_uploaded_file($_FILES[$set]['tmp_name'][$upload], $filepath)) { $message .= "There was a problem relocating the $upload image file. Please try again.<br />"; return false; } else { $message .= $filename." successfully uploaded. <br />"; //perform resizing $message .= thumbnail($filepath,$filepath,$dim['w'],$dim['h']); chmod($filepath, FILE_PERMS); if($thumbnail) { $message .= thumbnail($filepath,$thumbpath,$dim['tw'],$dim['th']); chmod($thumbpath, FILE_PERMS); } return true; } } else { $message .= "No image selected for $upload.<br />"; } return false; } /** * MISCELLANEOUS */ /** * assign evenly placed 'positions' to the items in an array * prior to db storage * @param array $a to be sorted - unique ids already validated * @param int $i number to start at * @param int $inc increment * @return array */ function order_for_db($a = array(),$i=10, $inc=10) { asort($a); $r = array(); foreach($a as $id => $pos){ $r[(string)$id] = $i; //(string) force associative array even if the ids could be interpreted as numeric - which they usually could be $i+=$inc; } return $r; } /** * detect an ajax request * @return bool */ function is_ajax_request() { return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; } ?>
cải xoăn