<?php

/*
 * common.fun.php (安装公共方法)
 * @projectname  QCCMS
 * @package      
 * @author       qccms
 * @copyright    qccms
 * @license     
 * @version      2013-08-14
 */

function dir_writeable($dir) {
	$writeable = 0;
	if (!is_dir($dir)) {
		@mkdir($dir, 0777);
	}
	if (is_dir($dir)) {
		if ($fp = @fopen("$dir/test.txt", 'w')) {
			@fclose($fp);
			@unlink("$dir/test.txt");
			$writeable = 1;
		} else {
			$writeable = 0;
		}
	}
	return $writeable;
}

//整理sql语句
function sql_format($sqlStr, $tablepre) {
	$tablepre == 'qc_' || $sqlStr = str_replace('qc_', $tablepre, $sqlStr);
	//解决windows下\r\n和linux下\n问题
	$sqlStr = str_replace("\r", "\n", $sqlStr);
	$sqlArr = explode(";\n", trim($sqlStr));
	foreach ($sqlArr as $k => $v) {
		$line = explode("\n", trim($v));
		$line=  array_filter($line);
		foreach ($line as $k1 => $v1) {
			$str1 = substr($v1, 0, 1);
			if ($str1 != '#' && $str1 != '-')
				$sql[$k] .= trim($v1);
		}
	}
	return $sql;
}

//生成密码
function generatePassword($password) {

    if (!extension_loaded('mcrypt')) {
        exit('mcrypt扩展没有开启');
    }
    $rand = mcrypt_create_iv(20, MCRYPT_DEV_URANDOM);
    if ($rand === false) {
        exit('生成随机字节错误');
    }


    $salt = sprintf("$2y$%02d$", 13);
    $salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22));
    $hash = crypt($password, $salt);
    return $hash;
}

function generateAuthKey() {

    if (!extension_loaded('mcrypt')) {
        exit('mcrypt扩展没有开启');
    }
    $rand = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
    if ($rand === false) {
        exit('生成随机字节错误');
    }

    return strtr(substr(base64_encode($rand), 0, 32), '+/', '_-');
}

