blog-app/core/Helpers.php

119 lines
3.4 KiB
PHP
Raw Normal View History

2021-09-16 20:27:51 +08:00
<?php
if (! function_exists('db')) {
function db()
{
$config = new Core\Config;
return new Core\Database\QueryBuilder(
Core\Database\Connection::make($config->get('database'))
);
}
}
if (! function_exists('view')) {
function view($name, $data = [])
{
if (isset($_SESSION['errors'])) {
$data['errors'] = $_SESSION['errors'];
unset($_SESSION['errors']);
}
if (isset($_SESSION['comment_errors'])) {
$data['comment_errors'] = $_SESSION['comment_errors'];
unset($_SESSION['comment_errors']);
}
if (isset($_SESSION['messages'])) {
$data['messages'] = $_SESSION['messages'];
unset($_SESSION['messages']);
}
if (isset($_SESSION['inputs'])) {
$inputs = $_SESSION['inputs'];
foreach ($inputs as $key => $value) {
$data[$key] = $value;
}
unset($_SESSION['inputs']);
}
$blade = new Jenssegers\Blade\Blade('views', 'views/cache');
$blade->compiler()->directive('markdown', function ($expression) {
return "<?php echo markdown({$expression}) ?>";
});
return $blade->make($name)->with($data);
}
}
if (! function_exists('markdown')) {
function markdown($content)
{
$parsedown = new \Parsedown;
$html = $parsedown->text($content);
$config = \HTMLPurifier_Config::createDefault();
$purifier = new \HTMLPurifier($config);
return $purifier->purify($html);
}
}
if (! function_exists('valid_username')) {
function valid_username($username)
{
$sql = 'SELECT * FROM users WHERE name=?';
$query = db()->prepare($sql);
$query->execute([$username]);
$user = $query->fetchAll(\PDO::FETCH_CLASS, 'Core\\Record');
return strlen($username) <= 32 &&
preg_match('/^[\w\d._]+$/', $username) &&
! count($user);
}
}
if (! function_exists('valid_email')) {
function valid_email($email)
{
$sql = 'SELECT * FROM users WHERE email=?';
$query = db()->prepare($sql);
$query->execute([$email]);
$user = $query->fetchAll(\PDO::FETCH_CLASS, 'Core\\Record');
return filter_var($email, FILTER_VALIDATE_EMAIL) &&
! count($user);
}
}
if (! function_exists('valid_password')) {
function valid_password($password1, $password2)
{
return preg_match('/^[!-~]+$/', $password1) &&
$password1 == $password2;
}
}
if (! function_exists('send_mail')) {
function send_mail($options)
{
$config = new Core\Config;
$mail = new PHPMailer\PHPMailer\PHPMailer(true);
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = $config->get('mailer')['host'];
$mail->SMTPAuth = true;
$mail->Username = $config->get('mailer')['username'];
$mail->Password = $config->get('mailer')['password'];
$mail->SMTPSecure = 'tls';
$mail->Port = 465;
$mail->setFrom($config->get('mailer')['from']);
$mail->addAddress($options['email']);
$mail->isHTML(true);
$mail->Subject = $options['title'];
$mail->Body = $options['body'];
$mail->send();
}
}
if (! function_exists('port')) {
function port()
{
$config = new Core\Config;
return $config->get('port');
}
}