repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/modules/sample/Info.php
inc/modules/sample/Info.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ return [ 'name' => $core->lang['sample']['module_name'], 'description' => $core->lang['sample']['module_desc'], 'author' => 'Sruu.pl', 'version' => '1.0', 'compatibility' => '1.3.*', // Compatibility with Batflat version 'icon' => 'code', // Icon from http://fontawesome.io/icons/ // Registering page for possible use as a homepage 'pages' => ['Sample Page' => 'sample'], 'install' => function () use ($core) { }, 'uninstall' => function () use ($core) { } ];
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/modules/sample/Site.php
inc/modules/sample/Site.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Modules\Sample; use Inc\Core\SiteModule; /** * Sample site class */ class Site extends SiteModule { /** * Example module variable * * @var string */ protected $foo; /** * Module initialization * Here everything is done while the module starts * * @return void */ public function init() { $this->foo = 'Hello'; } /** * Register module routes * Call the appropriate method/function based on URL * * @return void */ public function routes() { // Simple: $this->route('sample', 'getIndex'); /* * Or: * $this->route('sample', function() { * $this->getIndex(); * }); * * or: * $this->router->set('sample', $this->getIndex()); * * or: * $this->router->set('sample', function() { * $this->getIndex(); * }); */ } /** * GET: /sample * Called method by router * * @return string */ public function getIndex() { $page = [ 'title' => $this->lang('title'), 'desc' => 'Your page description here', 'content' => $this->draw('hello.html') ]; $this->setTemplate('index.html'); $this->tpl->set('page', $page); } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/modules/langswitcher/Info.php
inc/modules/langswitcher/Info.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ return [ 'name' => $core->lang['langswitcher']['module_name'], 'description' => $core->lang['langswitcher']['module_desc'], 'author' => 'Sruu.pl', 'version' => '1.2', 'compatibility' => '1.3.*', 'icon' => 'flag', 'install' => function () use ($core) { $core->db()->pdo()->exec("INSERT INTO `settings` (`module`, `field`, `value`) VALUES ('settings', 'autodetectlang', 0)"); }, 'uninstall' => function () use ($core) { $core->db()->pdo()->exec("DELETE FROM `settings` WHERE `field` = 'autodetectlang'"); } ];
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/modules/langswitcher/Site.php
inc/modules/langswitcher/Site.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Modules\LangSwitcher; use Inc\Core\SiteModule; class Site extends SiteModule { public function init() { if ($this->settings('settings', 'autodetectlang') == '1' && empty(parseURL(1)) && !isset($_SESSION['langswitcher']['detected'])) { $detedcted = false; $languages = $this->_detectBrowserLanguage(); foreach ($languages as $value => $priority) { $value = substr($value, 0, 2); if ($detect = glob('inc/lang/'.$value.'_*')) { $this->core->loadLanguage(basename($detect[0])); break; } } } $_SESSION['langswitcher']['detected'] = true; if (isset($_GET['lang'])) { $lang = explode('_', $_GET['lang'])[0]; $this->_setLanguage($_GET['lang']); $dir = trim(dirname($_SERVER['SCRIPT_NAME']), '/'); $e = parseURL(); foreach ($this->_getLanguages() as $lng) { if ($lng['symbol'] == $e[0]) { array_shift($e); break; } } $slug = implode('/', $e); if ($this->db('pages')->where('slug', $slug)->where('lang', $_GET['lang'])->oneArray()) { redirect(url($lang.'/'.$slug)); } else { redirect(url($slug)); } } $this->tpl->set('langSwitcher', $this->_insertSwitcher()); } private function _insertSwitcher() { return $this->draw('switcher.html', ['languages' => $this->_getLanguages()]); } protected function _getLanguages($selected = null, $attr = 'selected', $all = false) { $langs = glob('inc/lang/*', GLOB_ONLYDIR); $result = []; foreach ($langs as $lang) { if (!$all & file_exists($lang.'/.lock')) { continue; } $lang = basename($lang); $result[] = [ 'dir' => $lang, 'name' => mb_strtoupper(preg_replace('/_[a-z]+/', null, $lang)), 'symbol'=> preg_replace('/_[a-z]+/', null, $lang), 'attr' => (($selected ? $selected : $this->core->lang['name']) == $lang) ? $attr : null ]; } return $result; } private function _setLanguage($value) { if (in_array($value, array_column($this->_getLanguages(), 'dir'))) { $_SESSION['lang'] = $value; return true; } return false; } private function _detectBrowserLanguage() { $prefLocales = array_reduce( explode(',', isset_or($_SERVER['HTTP_ACCEPT_LANGUAGE'], null)), function ($res, $el) { list($l, $q) = array_merge(explode(';q=', $el), [1]); $res[$l] = (float) $q; return $res; }, []); arsort($prefLocales); return $prefLocales; } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/defines.php
inc/core/defines.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ if (!version_compare(PHP_VERSION, '5.5.0', '>=')) { exit("Batflat requires at least <b>PHP 5.5</b>"); } // Admin cat name define('ADMIN', 'admin'); // Themes path define('THEMES', BASE_DIR . '/themes'); // Modules path define('MODULES', BASE_DIR . '/inc/modules'); // Uploads path define('UPLOADS', BASE_DIR . '/uploads'); // Lock files define('FILE_LOCK', false); // Basic modules define('BASIC_MODULES', serialize([ 8 => 'settings', 0 => 'dashboard', 2 => 'pages', 3 => 'navigation', 7 => 'users', 1 => 'blog', 4 => 'galleries', 5 => 'snippets', 6 => 'modules', 9 => 'contact', 10 => 'langswitcher', 11 => 'devbar', ])); // HTML beautifier define('HTML_BEAUTY', false); // Developer mode define('DEV_MODE', false);
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/Main.php
inc/core/Main.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core; use Inc\Core\Lib\QueryBuilder; use Inc\Core\Lib\Templates; use Inc\Core\Lib\Router; use Inc\Core\Lib\Settings; use Inc\Core\Lib\License; /** * Base for core classes */ abstract class Main { /** * Language array * * @var array */ public $lang = []; /** * Templates instance * * @var Templates */ public $tpl; /** * Router instance * * @var Router */ public $router; /** * Settings instance * * @var Settings */ public $settings; /** * List of additional header or footer content * * @var array */ public $appends = []; /** * Reference to ModulesCollection * * @var \Inc\Core\Lib\ModulesCollection|null */ public $module = null; /** * Settings cache * * @var array */ protected static $settingsCache = []; /** * User cache * * @var array */ protected static $userCache = []; /** * Main constructor */ public function __construct() { $this->setSession(); $dbFile = BASE_DIR.'/inc/data/database.sdb'; if (file_exists($dbFile)) { QueryBuilder::connect("sqlite:{$dbFile}"); } else { $this->freshInstall($dbFile); } $this->settings = new Settings($this); date_default_timezone_set($this->settings->get('settings.timezone')); $this->tpl = new Templates($this); $this->router = new Router; $this->append(base64_decode('PG1ldGEgbmFtZT0iZ2VuZXJhdG9yIiBjb250ZW50PSJCYXRmbGF0IiAvPg=='), 'header'); } /** * New instance of QueryBuilder * * @param string $table * @return QueryBuilder */ public function db($table = null) { return new QueryBuilder($table); } /** * get module settings * @param string $module * @param string $field * @param bool $refresh * * @deprecated * * @return string or array */ public function getSettings($module = 'settings', $field = null, $refresh = false) { if ($refresh) { $this->settings->reload(); } return $this->settings->get($module, $field); } /** * Set module settings value * * @param string $module * @param string $field * @param string $value * * @deprecated * * @return bool */ public function setSettings($module, $field, $value) { return $this->settings->set($module, $field, $value); } /** * safe session * @return void */ private function setSession() { ini_set('session.use_only_cookies', 1); session_name('bat'); session_set_cookie_params(0, (batflat_dir() === '/' ? '/' : batflat_dir().'/')); session_start(); } /** * create notification * @param string $type ('success' or 'failure') * @param string $text * @param mixed $args [, mixed $... ]] * @return void */ public function setNotify($type, $text, $args = null) { $variables = []; $numargs = func_num_args(); $arguments = func_get_args(); if ($numargs > 1) { for ($i = 1; $i < $numargs; $i++) { $variables[] = $arguments[$i]; } $text = call_user_func_array('sprintf', $variables); $_SESSION[$arguments[0]] = $text; } } /** * display notification * @return array or false */ public function getNotify() { if (isset($_SESSION['failure'])) { $result = ['text' => $_SESSION['failure'], 'type' => 'danger']; unset($_SESSION['failure']); return $result; } elseif (isset($_SESSION['success'])) { $result = ['text' => $_SESSION['success'], 'type' => 'success']; unset($_SESSION['success']); return $result; } else { return false; } } /** * adds CSS URL to array * @param string $path * @return void */ public function addCSS($path) { $this->appends['header'][] = "<link rel=\"stylesheet\" href=\"$path\">\n"; } /** * adds JS URL to array * @param string $path * @param string $location (header / footer) * @return void */ public function addJS($path, $location = 'header') { $this->appends[$location][] = "<script src=\"$path\"></script>\n"; } /** * adds string to array * @param string $string * @param string $location (header / footer) * @return void */ public function append($string, $location) { $this->appends[$location][] = $string."\n"; } /** * Batflat license verify * By removing or modifing these procedures you break our license. * * @param string $buffer * @return string */ public static function verifyLicense($buffer) { $core = isset_or($GLOBALS['core'], false); if (!$core) { return $buffer; } $checkBuffer = preg_replace('/<!--(.|\s)*?-->/', '', $buffer); $isHTML = strpos(get_headers_list('Content-Type'), 'text/html') !== false; $hasBacklink = strpos($checkBuffer, 'Powered by <a href="https://batflat.org/">Batflat</a>') !== false; $hasHeader = get_headers_list('X-Created-By') === 'Batflat <batflat.org>'; $license = License::verify($core->settings->get('settings.license')); if (($license == License::FREE) && $isHTML && (!$hasBacklink || !$hasHeader)) { return '<strong>Batflat license system</strong><br />The return link has been deleted or modified.'; } elseif ($license == License::TIME_OUT) { return $buffer.'<script>alert("Batflat license system\nCan\'t connect to license server and verify it.");</script>'; } elseif ($license == License::ERROR) { return '<strong>Batflat license system</strong><br />The license is not valid. Please correct it or go to free version.'; } return trim($buffer); } /** * chcec if user is login * @return bool */ public function loginCheck() { if (isset($_SESSION['bat_user']) && isset($_SESSION['token']) && isset($_SESSION['userAgent']) && isset($_SESSION['IPaddress'])) { if ($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR']) { return false; } if ($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) { return false; } if (empty(parseURL(1))) { redirect(url([ADMIN, 'dashboard', 'main'])); } elseif (!isset($_GET['t']) || ($_SESSION['token'] != @$_GET['t'])) { return false; } return true; } elseif (isset($_COOKIE['batflat_remember'])) { $token = explode(":", $_COOKIE['batflat_remember']); if (count($token) == 2) { $row = $this->db('users')->leftJoin('remember_me', 'remember_me.user_id = users.id')->where('users.id', $token[0])->where('remember_me.token', $token[1])->select(['users.*', 'remember_me.expiry', 'token_id' => 'remember_me.id'])->oneArray(); if ($row) { if (time() - $row['expiry'] > 0) { $this->db('remember_me')->delete(['id' => $row['token_id']]); } else { $_SESSION['bat_user'] = $row['id']; $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(6)); $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT']; $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR']; $this->db('remember_me')->where('remember_me.user_id', $token[0])->where('remember_me.token', $token[1])->save(['expiry' => time()+60*60*24*30]); if (strpos($_SERVER['SCRIPT_NAME'], '/'.ADMIN.'/') !== false) { redirect(url([ADMIN, 'dashboard', 'main'])); } return true; } } } setcookie('batflat_remember', null, -1, '/'); } return false; } /** * get user informations * @param string $filed * @param int $id (optional) * @return string */ public function getUserInfo($field, $id = null, $refresh = false) { if (!$id) { $id = isset_or($_SESSION['bat_user'], 0); } if (empty(self::$userCache) || $refresh) { self::$userCache = $this->db('users')->where('id', $id)->oneArray(); } return self::$userCache ? self::$userCache[$field] : null; } /** * Load installed modules * * @return void */ public function loadModules() { if ($this->module == null) { $this->module = new Lib\ModulesCollection($this); } } /** * Generating database with Batflat data * @param string $dbFile path to Batflat SQLite database * @return void */ private function freshInstall($dbFile) { QueryBuilder::connect("sqlite:{$dbFile}"); $pdo = QueryBuilder::pdo(); $core = $this; $modules = unserialize(BASIC_MODULES); foreach ($modules as $module) { $file = MODULES.'/'.$module.'/Info.php'; if (file_exists($file)) { $this->lang[$module] = parse_ini_file(MODULES.'/'.$module.'/lang/admin/en_english.ini'); $info = include($file); if (isset($info['install'])) { $info['install'](); } } } foreach ($modules as $order => $name) { $core->db('modules')->save(['dir' => $name, 'sequence' => $order]); } redirect(url()); } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/Admin.php
inc/core/Admin.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core; /** * Core Admin class */ class Admin extends Main { /** * Assigned variables for templates * * @var array */ private $assign = []; /** * Registered module pages * * @var array */ private $registerPage = []; /** * Instance of Modules Collection * * @var \Inc\Core\Lib\ModulesCollection */ public $module = null; /** * Admin constructor */ public function __construct() { parent::__construct(); $this->router->set('logout', function () { $this->logout(); }); $this->loadLanguage($this->settings->get('settings.lang_admin')); } /** * set variables to template core and display them * @param string $file * @return void */ public function drawTheme($file) { $username = $this->getUserInfo('fullname', null, true); $access = $this->getUserInfo('access'); $this->assign['username'] = !empty($username) ? $username : $this->getUserInfo('username'); $this->assign['notify'] = $this->getNotify(); $this->assign['path'] = url(); $this->assign['version'] = $this->settings->get('settings.version'); $this->assign['has_update'] = $this->module ? $this->module->settings->_checkUpdate() : false; $this->assign['update_access'] = ($access == 'all') || in_array('settings', explode(',', $access)) ? true : false; $this->assign['header'] = isset_or($this->appends['header'], ['']); $this->assign['footer'] = isset_or($this->appends['footer'], ['']); $this->tpl->set('bat', $this->assign); echo $this->tpl->draw(THEMES.'/admin/'.$file, true); } /** * load language files * @param string $lang * @return void */ private function loadLanguage($language) { $this->lang['name'] = $language; foreach (glob(MODULES.'/*/lang/admin/'.$language.'.ini') as $file) { $base = str_replace($language, 'en_english', $file); $module = str_replace([MODULES.'/', '/lang/admin/'.$language.'.ini'], null, $file); $this->lang[$module] = array_merge(parse_ini_file($base), parse_ini_file($file)); } foreach (glob('../inc/lang/'.$language.'/admin/*.ini') as $glob) { $base = str_replace($language, 'en_english', $glob); $file = pathinfo($glob); $this->lang[$file['filename']] = array_merge(parse_ini_file($base), parse_ini_file($glob)); } $this->tpl->set('lang', $this->lang); } /** * load module and set variables * @param string $name * @param string $feature * @param array $params (optional) * @return void */ public function loadModule($name, $method, $params = []) { $row = $this->module->{$name}; if ($row && ($details = $this->getModuleInfo($name))) { if (($this->getUserInfo('access') == 'all') || in_array($name, explode(',', $this->getUserInfo('access')))) { $anyMethod = 'any'.ucfirst($method); $method = strtolower($_SERVER['REQUEST_METHOD']).ucfirst($method); if (method_exists($this->module->{$name}, $method)) { $details['content'] = call_user_func_array([$this->module->{$name}, $method], array_values($params)); } elseif (method_exists($this->module->{$name}, $anyMethod)) { $details['content'] = call_user_func_array([$this->module->{$name}, $anyMethod], array_values($params)); } else { http_response_code(404); $this->setNotify('failure', "[@{$method}] ".$this->lang['general']['unknown_method']); $details['content'] = null; } $this->tpl->set('module', $details); } else { exit; } } else { exit; } } /** * create list of modules * @param string $activeModile * @param string $activeFeature * @return void */ public function createNav($activeModule, $activeMethod) { $nav = []; $modules = $this->module->getArray(); if ($this->getUserInfo('access') != 'all') { $modules = array_intersect_key($modules, array_fill_keys(explode(',', $this->getUserInfo('access')), null)); } foreach ($modules as $dir => $module) { $subnav = $this->getModuleNav($dir); $details = $this->getModuleInfo($dir); if (isset($details['pages'])) { foreach ($details['pages'] as $pageName => $pageSlug) { $this->registerPage($pageName, $pageSlug); } } if ($subnav) { if ($activeModule == $dir) { $activeElement = 'active'; } else { $activeElement = null; } $subnavURLs = []; foreach ($subnav as $key => $val) { if (($activeModule == $dir) && isset($activeMethod) && ($activeMethod == $val)) { $activeSubElement = 'active'; } else { $activeSubElement = null; } $subnavURLs[] = [ 'name' => $key, 'url' => url([ADMIN, $dir, $val]), 'active' => $activeSubElement, ]; } if (count($subnavURLs) == 1) { $moduleURL = $subnavURLs[0]['url']; $subnavURLs = []; } else { $moduleURL = '#'; } $nav[] = [ 'dir' => $dir, 'name' => $details['name'], 'icon' => $details['icon'], 'url' => $moduleURL, 'active' => $activeElement, 'subnav' => $subnavURLs, ]; } } $this->assign['nav'] = $nav; } /** * get module informations * @param string $dir * @return array */ public function getModuleInfo($dir) { $file = MODULES.'/'.$dir.'/Info.php'; $core = $this; if (file_exists($file)) { return include($file); } else { return false; } } /** * get module's methods * @param string $dir * @return array */ public function getModuleNav($dir) { if ($this->module->has($dir)) { return $this->module->{$dir}->navigation(); } return false; } /** * get module method * @param string $dir * @param string $feature * @param array $params (optional) * @return array */ public function getModuleMethod($name, $method, $params = []) { if (method_exists($this->module->{$name}, $method)) { return call_user_func_array([$this->module->{$name}, $method], array_values($params)); } $this->setNotify('failure', $this->lang['general']['unknown_method']); return false; } /** * user login * @param string $username * @param string $password * @return bool */ public function login($username, $password, $remember_me = false) { // Check attempt $attempt = $this->db('login_attempts')->where('ip', $_SERVER['REMOTE_ADDR'])->oneArray(); // Create attempt if does not exist if (!$attempt) { $this->db('login_attempts')->save(['ip' => $_SERVER['REMOTE_ADDR'], 'attempts' => 0]); $attempt = ['ip' => $_SERVER['REMOTE_ADDR'], 'attempts' => 0, 'expires' => 0]; } else { $attempt['attempts'] = intval($attempt['attempts']); $attempt['expires'] = intval($attempt['expires']); } // Is IP blocked? if ((time() - $attempt['expires']) < 0) { $this->setNotify('failure', sprintf($this->lang['general']['login_attempts'], ceil(($attempt['expires']-time())/60))); return false; } $row = $this->db('users')->where('username', $username)->oneArray(); if ($row && count($row) && password_verify(trim($password), $row['password'])) { // Reset fail attempts for this IP $this->db('login_attempts')->where('ip', $_SERVER['REMOTE_ADDR'])->save(['attempts' => 0]); $_SESSION['bat_user'] = $row['id']; $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(6)); $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT']; $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR']; if ($remember_me) { $token = str_gen(64, "1234567890qwertyuiop[]asdfghjkl;zxcvbnm,./"); $this->db('remember_me')->save(['user_id' => $row['id'], 'token' => $token, 'expiry' => time()+60*60*24*30]); setcookie('batflat_remember', $row['id'].':'.$token, time()+60*60*24*365, '/'); } return true; } else { // Increase attempt $this->db('login_attempts')->where('ip', $_SERVER['REMOTE_ADDR'])->save(['attempts' => $attempt['attempts']+1]); $attempt['attempts'] += 1; // ... and block if reached maximum attempts if ($attempt['attempts'] % 3 == 0) { $this->db('login_attempts')->where('ip', $_SERVER['REMOTE_ADDR'])->save(['expires' => strtotime("+10 minutes")]); $attempt['expires'] = strtotime("+10 minutes"); $this->setNotify('failure', sprintf($this->lang['general']['login_attempts'], ceil(($attempt['expires']-time())/60))); } else { $this->setNotify('failure', $this->lang['general']['login_failure']); } return false; } } /** * user logout * @return void */ private function logout() { $_SESSION = []; // Delete remember_me token from database and cookie if (isset($_COOKIE['batflat_remember'])) { $token = explode(':', $_COOKIE['batflat_remember']); $this->db('remember_me')->where('user_id', $token[0])->where('token', $token[1])->delete(); setcookie('batflat_remember', null, -1, '/'); } session_unset(); session_destroy(); redirect(url(ADMIN.'/')); } /** * Register module page * * @param string $name * @param string $path * @return void */ private function registerPage($name, $path) { $this->registerPage[] = ['id' => null, 'title' => $name, 'slug' => $path]; } /** * Get registered pages * * @return array */ public function getRegisteredPages() { return $this->registerPage; } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/Site.php
inc/core/Site.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core; /** * Core Site class */ class Site extends Main { /** * Current site template file * Does not use template if set to false * * @var mixed */ public $template = 'index.html'; /** * Site constructor */ public function __construct() { parent::__construct(); $this->loadLanguage(); $this->loadModules(); $return = $this->router->execute(); if (is_string($this->template)) { $this->drawTheme($this->template); } elseif ($this->template === false) { if (strpos(get_headers_list('Content-Type'), 'text/html') !== false) { header("Content-type: text/plain"); } echo $return; } $this->module->finishLoop(); } /** * set variables to template core and display them * @param string $file * @return void */ private function drawTheme($file) { $assign = []; $assign['notify'] = $this->getNotify(); $assign['powered'] = 'Powered by <a href="https://batflat.org/">Batflat</a>'; $assign['path'] = url(); $assign['theme'] = url(THEMES.'/'.$this->settings->get('settings.theme')); $assign['lang'] = $this->lang['name']; $assign['header'] = isset_or($this->appends['header'], ['']); $assign['footer'] = isset_or($this->appends['footer'], ['']); $this->tpl->set('bat', $assign); echo $this->tpl->draw(THEMES.'/'.$this->settings->get('settings.theme').'/'.$file, true); } /** * load files with language * @param string $lang * @return void */ public function loadLanguage($lang = null) { $this->lang = []; if ($lang != null && is_dir('inc/lang/'.$lang)) { $_SESSION['lang'] = $lang; } if (!isset($_SESSION['lang']) || !is_dir('inc/lang/'.$_SESSION['lang'])) { $this->lang['name'] = $this->settings->get('settings.lang_site'); $_SESSION['lang'] = $this->lang['name']; } else { $this->lang['name'] = $_SESSION['lang']; } foreach (glob(MODULES.'/*/lang/'.$this->lang['name'].'.ini') as $file) { $base = str_replace($this->lang['name'], 'en_english', $file); $module = str_replace([MODULES.'/', '/lang/'.$this->lang['name'].'.ini'], null, $file); $this->lang[$module] = array_merge(parse_ini_file($base), parse_ini_file($file)); } foreach (glob('inc/lang/'.$this->lang['name'].'/*.ini') as $file) { $base = str_replace($this->lang['name'], 'en_english', $file); $pathInfo = pathinfo($file); $this->lang[$pathInfo['filename']] = array_merge(parse_ini_file($base), parse_ini_file($file)); } $this->tpl->set('lang', $this->lang); } /** * check if user is login * @return bool */ public function loginCheck() { if (isset($_SESSION['bat_user']) && isset($_SESSION['token']) && isset($_SESSION['userAgent']) && isset($_SESSION['IPaddress'])) { if ($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR']) { return false; } if ($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) { return false; } return true; } else { return false; } } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/BaseModule.php
inc/core/BaseModule.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core; /** * Base class for each module functionality */ class BaseModule { /** * Reference to Core instance * * @var \Inc\Core\Main */ protected $core; /** * Reference to Template instance * * @var \Inc\Core\Lib\Templates */ protected $tpl; /** * Reference to Router instance * * @var \Inc\Core\Lib\Router */ protected $route; /** * Reference to Settings instance * * @var \Inc\Core\Lib\Settings */ protected $settings; /** * Module dir name * * @var string */ protected $name; /** * Reference to language array * * @var array */ protected $lang; /** * Module constructor * * @param Inc\Core\Main $core * @return void */ public function __construct(Main $core) { $this->core = $core; $this->tpl = $core->tpl; $this->router = $core->router; $this->settings = $core->settings; $this->lang = $core->lang; $this->name = strtolower(str_replace(['Inc\Modules\\', '\\Admin', '\\Site'], null, static::class)); } /** * Module initialization * * @return void */ public function init() { } /** * Procedures before destroy * * @return void */ public function finish() { } /** * Languages list * @param string $selected * @param string $currentAttr ('active' or 'selected') * @return array */ protected function _getLanguages($selected = null, $currentAttr = 'active', $all = false) { $langs = glob(BASE_DIR.'/inc/lang/*', GLOB_ONLYDIR); $result = []; foreach ($langs as $lang) { if (file_exists($lang.'/.lock')) { $active = false; if (!$all) { continue; } } else { $active = true; } if ($selected == basename($lang)) { $attr = $currentAttr; } else { $attr = null; } $result[] = ['name' => basename($lang), 'attr' => $attr, 'active' => $active]; } return $result; } /** * Hook to draw template with set variables * * @param string $file * @param array $variables * @return string */ protected function draw($file, array $variables = []) { if (!empty($variables)) { foreach ($variables as $key => $value) { $this->tpl->set($key, $value); } } if (strpos($file, BASE_DIR) !== 0) { if ($this instanceof AdminModule) { $file = MODULES.'/'.$this->name.'/view/admin/'.$file; } else { $file = MODULES.'/'.$this->name.'/view/'.$file; } } return $this->tpl->draw($file); } /** * Get current module language value * * @param string $key * @param string $module * @return string */ protected function lang($key, $module = null) { if (empty($module)) { $module = $this->name; } return isset_or($this->lang[$module][$key], null); } /** * Get or set module settings * * @param string $module Example 'module' or shorter 'module.field' * @param mixed $field If module has field it contains value * @param mixed $value OPTIONAL * @return mixed */ protected function settings($module, $field = false, $value = false) { if (substr_count($module, '.') == 1) { $value = $field; list($module, $field) = explode('.', $module); } if ($value === false) { return $this->settings->get($module, $field); } else { return $this->settings->set($module, $field, $value); } } /** * Database QueryBuilder * * @param string $table * @return \Inc\Core\Lib\QueryBuilder */ protected function db($table = null) { return $this->core->db($table); } /** * Create notification * @param string $type ('success' or 'failure') * @param string $text * @param mixed $args [, mixed $... ]] * @return void */ protected function notify() { call_user_func_array([$this->core, 'setNotify'], func_get_args()); } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/AdminModule.php
inc/core/AdminModule.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core; /** * Admin class for administration panel */ abstract class AdminModule extends BaseModule { /** * Module navigation * * @return array */ public function navigation() { return []; } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/SiteModule.php
inc/core/SiteModule.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core; /** * Site class for website's module controller */ abstract class SiteModule extends BaseModule { /** * Routes declarations for Site * Moved from __construct() * * @return void */ public function routes() { } /** * Set route * * @param string $pattern * @param mixed $callback callable function or name of module method * @return void */ protected function route($pattern, $callback) { if (is_callable($callback)) { $this->core->router->set($pattern, $callback); } else { $this->core->router->set($pattern, function () use ($callback) { return call_user_func_array([$this, $callback], func_get_args()); }); } } /** * Set site template * * @param string $file * @return void */ protected function setTemplate($file) { $this->core->template = $file; } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/Indenter.php
inc/core/lib/Indenter.php
<?php /** * @link https://github.com/gajus/dindent for the canonical source repository * @license https://github.com/gajus/dindent/blob/master/LICENSE BSD 3-Clause */ namespace Inc\Core\Lib; /** * Indenter class */ class Indenter { private $log = array(); private $options = array( 'indentation_character' => ' ' ); private $inline_elements = array('b', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'cite', 'code', 'dfn', 'em', 'kbd', 'strong', 'samp', 'var', 'a', 'bdo', 'br', 'img', 'span', 'sub', 'sup'); private $temporary_replacements_script = array(); private $temporary_replacements_inline = array(); const ELEMENT_TYPE_BLOCK = 0; const ELEMENT_TYPE_INLINE = 1; const MATCH_INDENT_NO = 0; const MATCH_INDENT_DECREASE = 1; const MATCH_INDENT_INCREASE = 2; const MATCH_DISCARD = 3; /** * @param array $options */ public function __construct(array $options = array()) { foreach ($options as $name => $value) { if (!array_key_exists($name, $this->options)) { trigger_error('Indenter: Unrecognized option.', E_USER_NOTICE); } $this->options[$name] = $value; } } /** * @param string $element_name Element name, e.g. "b". * @param ELEMENT_TYPE_BLOCK|ELEMENT_TYPE_INLINE $type * @return null */ public function setElementType($element_name, $type) { if ($type === static::ELEMENT_TYPE_BLOCK) { $this->inline_elements = array_diff($this->inline_elements, array($element_name)); } elseif ($type === static::ELEMENT_TYPE_INLINE) { $this->inline_elements[] = $element_name; } else { trigger_error('Indenter: Unrecognized element type.', E_USER_NOTICE); } $this->inline_elements = array_unique($this->inline_elements); } /** * @param string $input HTML input. * @return string Indented HTML. */ public function indent($input) { $this->log = array(); // Dindent does not indent <script> body. Instead, it temporary removes it from the code, indents the input, and restores the script body. if (preg_match_all('/<script\b[^>]*>([\s\S]*?)<\/script>/mi', $input, $matches)) { $this->temporary_replacements_script = $matches[0]; foreach ($matches[0] as $i => $match) { $input = str_replace($match, '<script>' . ($i + 1) . '</script>', $input); } } // Removing double whitespaces to make the source code easier to read. // $input = str_replace("\t", '', $input); // $input = preg_replace('/\s{2,}/', ' ', $input); // Remove inline elements and replace them with text entities. if (preg_match_all('/<(' . implode('|', $this->inline_elements) . ')[^>]*>(?:[^<]*)<\/\1>/', $input, $matches)) { $this->temporary_replacements_inline = $matches[0]; foreach ($matches[0] as $i => $match) { $input = str_replace($match, 'ᐃ' . ($i + 1) . 'ᐃ', $input); } } $subject = $input; $output = ''; $next_line_indentation_level = 0; do { $indentation_level = $next_line_indentation_level; $patterns = array( // block tag '/^(<([a-z]+)(?:[^>]*)>(?:[^<]*)<\/(?:\2)>)/' => static::MATCH_INDENT_NO, // DOCTYPE '/^<!([^>]*)>/' => static::MATCH_INDENT_NO, // tag with implied closing '/^<(input|link|meta|base|br|img|hr)([^>]*)>/' => static::MATCH_INDENT_NO, // opening tag '/^<[^\/]([^>]*)>/' => static::MATCH_INDENT_INCREASE, // closing tag '/^<\/([^>]*)>/' => static::MATCH_INDENT_DECREASE, // self-closing tag '/^<(.+)\/>/' => static::MATCH_INDENT_DECREASE, // whitespace '/^(\s+)/' => static::MATCH_DISCARD, // text node '/([^<]+)/' => static::MATCH_INDENT_NO ); $rules = array('NO', 'DECREASE', 'INCREASE', 'DISCARD'); foreach ($patterns as $pattern => $rule) { if ($match = preg_match($pattern, $subject, $matches)) { $this->log[] = array( 'rule' => $rules[$rule], 'pattern' => $pattern, 'subject' => $subject, 'match' => $matches[0] ); $subject = mb_substr($subject, mb_strlen($matches[0])); if ($rule === static::MATCH_DISCARD) { break; } if ($rule === static::MATCH_INDENT_NO) { } elseif ($rule === static::MATCH_INDENT_DECREASE) { $next_line_indentation_level--; $indentation_level--; } else { $next_line_indentation_level++; } if ($indentation_level < 0) { $indentation_level = 0; } $output .= str_repeat($this->options['indentation_character'], $indentation_level) . $matches[0] . "\n"; break; } } } while ($match); $interpreted_input = ''; foreach ($this->log as $e) { $interpreted_input .= $e['match']; } if ($interpreted_input !== $input) { trigger_error('Indenter: Did not reproduce the exact input.', E_USER_NOTICE); } $output = preg_replace('/(<(\w+)[^>]*>)\s*(<\/\2>)/', '\\1\\3', $output); foreach ($this->temporary_replacements_script as $i => $original) { $output = str_replace('<script>' . ($i + 1) . '</script>', $original, $output); } foreach ($this->temporary_replacements_inline as $i => $original) { $output = str_replace('ᐃ' . ($i + 1) . 'ᐃ', $original, $output); } return trim($output); } /** * Debugging utility. Get log for the last indent operation. * * @return array */ public function getLog() { return $this->log; } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/Pagination.php
inc/core/lib/Pagination.php
<?php /** * Pagination: The simplest PHP pagination class * * @author Leonard Shtika <leonard@shtika.info> * @link http://leonard.shtika.info * @copyright (C) Leonard Shtika * @license MIT. */ namespace Inc\Core\Lib; class Pagination { private $_currentPage; private $_totalRecords; private $_recordsPerPage; private $_url; public function __construct($currentPage = 1, $totalRecords = 0, $recordsPerPage = 10, $url = '?page=%d') { $this->_currentPage = (int) $currentPage; $this->_totalRecords = (int) $totalRecords; $this->_recordsPerPage = (int) $recordsPerPage; $this->_url = $url; } /** * Calculate offset * @return int * Example: for 10 recores per page * page 1 has offset 0 * page 2 has offset 10 */ public function offset() { return ($this->_currentPage - 1) * $this->_recordsPerPage; } /** * Get the records per page * @return int */ public function getRecordsPerPage() { return $this->_recordsPerPage; } /** * Calculate total pages */ private function _totalPages() { return ceil($this->_totalRecords / $this->_recordsPerPage); } /** * Calculate previous page * @return int */ private function _previousPage() { return $this->_currentPage - 1; } /** * Calculate next page * @return int */ private function _nextPage() { return $this->_currentPage + 1; } /** * Check if there is a previous page * @return boolean */ private function _hasPreviousPage() { return ($this->_previousPage() >= 1) ? true : false; } /** * Check if there is a next page * @return boolean */ private function _hasNextPage() { return ($this->_nextPage() <= $this->_totalPages()) ? true : false; } /** * Generate navigation * @param string $type ('pagination' or 'pager') * @param int $maxLinks * @return mixed (string or false) */ public function nav($type = 'pagination', $maxLinks = 10) { if ($this->_totalPages() > 1) { $filename = htmlspecialchars(pathinfo($_SERVER["SCRIPT_FILENAME"], PATHINFO_BASENAME), ENT_QUOTES, "utf-8"); $links = '<nav class="text-center">'; $links.= '<ul class="'.$type.'">'; if ($this->_hasPreviousPage()) { if ($type == 'pagination') { $links.= '<li><a href="'.sprintf($this->_url, 1).'">&laquo;</a></li>'; $links.= '<li><a href="'.sprintf($this->_url, $this->_previousPage()).'">-</a></li>'; } else { $links.= '<li class="previous"><a href="'.sprintf($this->_url, $this->_previousPage()).'">&larr;</a></li>'; } } else { if ($type == 'pagination') { $links.= '<li class="disabled"><a href="#">&laquo;</a></li>'; $links.= '<li class="disabled"><a href="#">-</a></li>'; } else { $links.= '<li class="previous disabled"><a href="#">&larr;</a></li>'; } } // Create links in the middle if ($type == 'pagination') { // Total links $totalLinks = ($this->_totalPages() <= $maxLinks) ? $this->_totalPages() : $maxLinks; // Middle link $middleLink = floor($totalLinks / 2); // Find first link and last link if ($this->_currentPage <= $middleLink) { $lastLink = $totalLinks; $firstLink = 1; } else { if (($this->_currentPage + $middleLink) <= $this->_totalPages()) { $lastLink = $this->_currentPage + $middleLink; } else { $lastLink = $this->_totalPages(); } $firstLink = $lastLink - $totalLinks + 1; } for ($i = $firstLink; $i <= $lastLink; $i++) { if ($this->_currentPage == $i) { $links .= '<li class="active"><a href="#">' . $i . '</a></li>'; } else { $links .= '<li><a href="'.sprintf($this->_url, $i).'">' . $i . '</a></li>'; } } } if ($this->_hasNextPage()) { if ($type == 'pagination') { $links.= '<li><a href="'.sprintf($this->_url, $this->_nextPage()).'">+</a></li>'; $links.= '<li><a href="'.sprintf($this->_url, $this->_totalPages()).'">&raquo;</a></li>'; } else { $links.= '<li class="next"><a href="'.sprintf($this->_url, $this->_nextPage()).'">&rarr;</a></li>'; } } else { if ($type == 'pagination') { $links.= '<li class="disabled"><a href="#">+</a></li>'; $links.= '<li class="disabled"><a href="#">&raquo;</a></li>'; } else { $links.= '<li class="next disabled"><a href="#">&rarr;</a></li>'; } } $links.='</ul>'; $links.='</nav>'; // Return all links of Pagination return $links; } else { return false; } } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/Parsedown.php
inc/core/lib/Parsedown.php
<?php # # # Parsedown # http://parsedown.org # # (c) Emanuil Rusev # http://erusev.com # # For the full license information, view the LICENSE file that was distributed # with this source code. # # namespace Inc\Core\Lib; class Parsedown { const version = '1.6.0'; protected $breaksEnabled; protected $markupEscaped; protected $inlineMarkerList = '!"*_&[:<>`~\\'; protected $specialCharacters = array( '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|', ); protected $DefinitionData; protected $StrongRegex = array( '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*[*])+?)[*]{2}(?![*])/s', '_' => '/^__((?:\\\\_|[^_]|_[^_]*_)+?)__(?!_)/us', ); protected $EmRegex = array( '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s', '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us', ); protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*(?:\s*=\s*(?:[^"\'=<>`\s]+|"[^"]*"|\'[^\']*\'))?'; protected $voidElements = array( 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', ); protected $textLevelElements = array( 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont', 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing', 'i', 'rp', 'del', 'code', 'strike', 'marquee', 'q', 'rt', 'ins', 'font', 'strong', 's', 'tt', 'sub', 'mark', 'u', 'xm', 'sup', 'nobr', 'var', 'ruby', 'wbr', 'span', 'time', ); private static $instances = array(); public function text($text) { # make sure no definitions are set $this->DefinitionData = array(); # standardize line breaks $text = str_replace(array("\r\n", "\r"), "\n", $text); # remove surrounding line breaks $text = trim($text, "\n"); # split text into lines $lines = explode("\n", $text); # iterate through lines to identify blocks $markup = $this->lines($lines); # trim line breaks $markup = trim($markup, "\n"); return $markup; } public function setBreaksEnabled($breaksEnabled) { $this->breaksEnabled = $breaksEnabled; return $this; } public function setMarkupEscaped($markupEscaped) { $this->markupEscaped = $markupEscaped; return $this; } public function setUrlsLinked($urlsLinked) { $this->urlsLinked = $urlsLinked; return $this; } protected $urlsLinked = true; protected $BlockTypes = array( '#' => array('Header'), '*' => array('Rule', 'List'), '+' => array('List'), '-' => array('SetextHeader', 'Table', 'Rule', 'List'), '0' => array('List'), '1' => array('List'), '2' => array('List'), '3' => array('List'), '4' => array('List'), '5' => array('List'), '6' => array('List'), '7' => array('List'), '8' => array('List'), '9' => array('List'), ':' => array('Table'), '<' => array('Comment', 'Markup'), '=' => array('SetextHeader'), '>' => array('Quote'), '[' => array('Reference'), '_' => array('Rule'), '`' => array('FencedCode'), '|' => array('Table'), '~' => array('FencedCode'), ); protected $unmarkedBlockTypes = array( 'Code', ); protected function lines(array $lines) { $CurrentBlock = null; foreach ($lines as $line) { if (chop($line) === '') { if (isset($CurrentBlock)) { $CurrentBlock['interrupted'] = true; } continue; } if (strpos($line, "\t") !== false) { $parts = explode("\t", $line); $line = $parts[0]; unset($parts[0]); foreach ($parts as $part) { $shortage = 4 - mb_strlen($line, 'utf-8') % 4; $line .= str_repeat(' ', $shortage); $line .= $part; } } $indent = 0; while (isset($line[$indent]) and $line[$indent] === ' ') { $indent ++; } $text = $indent > 0 ? substr($line, $indent) : $line; # ~ $Line = array('body' => $line, 'indent' => $indent, 'text' => $text); # ~ if (isset($CurrentBlock['continuable'])) { $Block = $this->{'block'.$CurrentBlock['type'].'Continue'}($Line, $CurrentBlock); if (isset($Block)) { $CurrentBlock = $Block; continue; } else { if ($this->isBlockCompletable($CurrentBlock['type'])) { $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock); } } } # ~ $marker = $text[0]; # ~ $blockTypes = $this->unmarkedBlockTypes; if (isset($this->BlockTypes[$marker])) { foreach ($this->BlockTypes[$marker] as $blockType) { $blockTypes []= $blockType; } } # # ~ foreach ($blockTypes as $blockType) { $Block = $this->{'block'.$blockType}($Line, $CurrentBlock); if (isset($Block)) { $Block['type'] = $blockType; if (! isset($Block['identified'])) { $Blocks []= $CurrentBlock; $Block['identified'] = true; } if ($this->isBlockContinuable($blockType)) { $Block['continuable'] = true; } $CurrentBlock = $Block; continue 2; } } # ~ if (isset($CurrentBlock) and ! isset($CurrentBlock['type']) and ! isset($CurrentBlock['interrupted'])) { $CurrentBlock['element']['text'] .= "\n".$text; } else { $Blocks []= $CurrentBlock; $CurrentBlock = $this->paragraph($Line); $CurrentBlock['identified'] = true; } } # ~ if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type'])) { $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock); } # ~ $Blocks []= $CurrentBlock; unset($Blocks[0]); # ~ $markup = ''; foreach ($Blocks as $Block) { if (isset($Block['hidden'])) { continue; } $markup .= "\n"; $markup .= isset($Block['markup']) ? $Block['markup'] : $this->element($Block['element']); } $markup .= "\n"; # ~ return $markup; } protected function isBlockContinuable($Type) { return method_exists($this, 'block'.$Type.'Continue'); } protected function isBlockCompletable($Type) { return method_exists($this, 'block'.$Type.'Complete'); } protected function blockCode($Line, $Block = null) { if (isset($Block) and ! isset($Block['type']) and ! isset($Block['interrupted'])) { return; } if ($Line['indent'] >= 4) { $text = substr($Line['body'], 4); $Block = array( 'element' => array( 'name' => 'pre', 'handler' => 'element', 'text' => array( 'name' => 'code', 'text' => $text, ), ), ); return $Block; } } protected function blockCodeContinue($Line, $Block) { if ($Line['indent'] >= 4) { if (isset($Block['interrupted'])) { $Block['element']['text']['text'] .= "\n"; unset($Block['interrupted']); } $Block['element']['text']['text'] .= "\n"; $text = substr($Line['body'], 4); $Block['element']['text']['text'] .= $text; return $Block; } } protected function blockCodeComplete($Block) { $text = $Block['element']['text']['text']; $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8'); $Block['element']['text']['text'] = $text; return $Block; } protected function blockComment($Line) { if ($this->markupEscaped) { return; } if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!') { $Block = array( 'markup' => $Line['body'], ); if (preg_match('/-->$/', $Line['text'])) { $Block['closed'] = true; } return $Block; } } protected function blockCommentContinue($Line, array $Block) { if (isset($Block['closed'])) { return; } $Block['markup'] .= "\n" . $Line['body']; if (preg_match('/-->$/', $Line['text'])) { $Block['closed'] = true; } return $Block; } protected function blockFencedCode($Line) { if (preg_match('/^['.$Line['text'][0].']{3,}[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches)) { $Element = array( 'name' => 'code', 'text' => '', ); if (isset($matches[1])) { $class = 'language-'.$matches[1]; $Element['attributes'] = array( 'class' => $class, ); } $Block = array( 'char' => $Line['text'][0], 'element' => array( 'name' => 'pre', 'handler' => 'element', 'text' => $Element, ), ); return $Block; } } protected function blockFencedCodeContinue($Line, $Block) { if (isset($Block['complete'])) { return; } if (isset($Block['interrupted'])) { $Block['element']['text']['text'] .= "\n"; unset($Block['interrupted']); } if (preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text'])) { $Block['element']['text']['text'] = substr($Block['element']['text']['text'], 1); $Block['complete'] = true; return $Block; } $Block['element']['text']['text'] .= "\n".$Line['body']; ; return $Block; } protected function blockFencedCodeComplete($Block) { $text = $Block['element']['text']['text']; $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8'); $Block['element']['text']['text'] = $text; return $Block; } protected function blockHeader($Line) { if (isset($Line['text'][1])) { $level = 1; while (isset($Line['text'][$level]) and $Line['text'][$level] === '#') { $level ++; } if ($level > 6) { return; } $text = trim($Line['text'], '# '); $Block = array( 'element' => array( 'name' => 'h' . min(6, $level), 'text' => $text, 'handler' => 'line', ), ); return $Block; } } protected function blockList($Line) { list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]+[.]'); if (preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches)) { $Block = array( 'indent' => $Line['indent'], 'pattern' => $pattern, 'element' => array( 'name' => $name, 'handler' => 'elements', ), ); $Block['li'] = array( 'name' => 'li', 'handler' => 'li', 'text' => array( $matches[2], ), ); $Block['element']['text'] []= & $Block['li']; return $Block; } } protected function blockListContinue($Line, array $Block) { if ($Block['indent'] === $Line['indent'] and preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches)) { if (isset($Block['interrupted'])) { $Block['li']['text'] []= ''; unset($Block['interrupted']); } unset($Block['li']); $text = isset($matches[1]) ? $matches[1] : ''; $Block['li'] = array( 'name' => 'li', 'handler' => 'li', 'text' => array( $text, ), ); $Block['element']['text'] []= & $Block['li']; return $Block; } if ($Line['text'][0] === '[' and $this->blockReference($Line)) { return $Block; } if (! isset($Block['interrupted'])) { $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']); $Block['li']['text'] []= $text; return $Block; } if ($Line['indent'] > 0) { $Block['li']['text'] []= ''; $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']); $Block['li']['text'] []= $text; unset($Block['interrupted']); return $Block; } } protected function blockQuote($Line) { if (preg_match('/^>[ ]?(.*)/', $Line['text'], $matches)) { $Block = array( 'element' => array( 'name' => 'blockquote', 'handler' => 'lines', 'text' => (array) $matches[1], ), ); return $Block; } } protected function blockQuoteContinue($Line, array $Block) { if ($Line['text'][0] === '>' and preg_match('/^>[ ]?(.*)/', $Line['text'], $matches)) { if (isset($Block['interrupted'])) { $Block['element']['text'] []= ''; unset($Block['interrupted']); } $Block['element']['text'] []= $matches[1]; return $Block; } if (! isset($Block['interrupted'])) { $Block['element']['text'] []= $Line['text']; return $Block; } } protected function blockRule($Line) { if (preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text'])) { $Block = array( 'element' => array( 'name' => 'hr' ), ); return $Block; } } protected function blockSetextHeader($Line, array $Block = null) { if (! isset($Block) or isset($Block['type']) or isset($Block['interrupted'])) { return; } if (chop($Line['text'], $Line['text'][0]) === '') { $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2'; return $Block; } } protected function blockMarkup($Line) { if ($this->markupEscaped) { return; } if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches)) { $element = strtolower($matches[1]); if (in_array($element, $this->textLevelElements)) { return; } $Block = array( 'name' => $matches[1], 'depth' => 0, 'markup' => $Line['text'], ); $length = strlen($matches[0]); $remainder = substr($Line['text'], $length); if (trim($remainder) === '') { if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) { $Block['closed'] = true; $Block['void'] = true; } } else { if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) { return; } if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder)) { $Block['closed'] = true; } } return $Block; } } protected function blockMarkupContinue($Line, array $Block) { if (isset($Block['closed'])) { return; } if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) { # open $Block['depth'] ++; } if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) { # close if ($Block['depth'] > 0) { $Block['depth'] --; } else { $Block['closed'] = true; } } if (isset($Block['interrupted'])) { $Block['markup'] .= "\n"; unset($Block['interrupted']); } $Block['markup'] .= "\n".$Line['body']; return $Block; } protected function blockReference($Line) { if (preg_match('/^\[(.+?)\]:[ ]*<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*$/', $Line['text'], $matches)) { $id = strtolower($matches[1]); $Data = array( 'url' => $matches[2], 'title' => null, ); if (isset($matches[3])) { $Data['title'] = $matches[3]; } $this->DefinitionData['Reference'][$id] = $Data; $Block = array( 'hidden' => true, ); return $Block; } } protected function blockTable($Line, array $Block = null) { if (! isset($Block) or isset($Block['type']) or isset($Block['interrupted'])) { return; } if (strpos($Block['element']['text'], '|') !== false and chop($Line['text'], ' -:|') === '') { $alignments = array(); $divider = $Line['text']; $divider = trim($divider); $divider = trim($divider, '|'); $dividerCells = explode('|', $divider); foreach ($dividerCells as $dividerCell) { $dividerCell = trim($dividerCell); if ($dividerCell === '') { continue; } $alignment = null; if ($dividerCell[0] === ':') { $alignment = 'left'; } if (substr($dividerCell, - 1) === ':') { $alignment = $alignment === 'left' ? 'center' : 'right'; } $alignments []= $alignment; } # ~ $HeaderElements = array(); $header = $Block['element']['text']; $header = trim($header); $header = trim($header, '|'); $headerCells = explode('|', $header); foreach ($headerCells as $index => $headerCell) { $headerCell = trim($headerCell); $HeaderElement = array( 'name' => 'th', 'text' => $headerCell, 'handler' => 'line', ); if (isset($alignments[$index])) { $alignment = $alignments[$index]; $HeaderElement['attributes'] = array( 'style' => 'text-align: '.$alignment.';', ); } $HeaderElements []= $HeaderElement; } # ~ $Block = array( 'alignments' => $alignments, 'identified' => true, 'element' => array( 'name' => 'table', 'handler' => 'elements', ), ); $Block['element']['text'] []= array( 'name' => 'thead', 'handler' => 'elements', ); $Block['element']['text'] []= array( 'name' => 'tbody', 'handler' => 'elements', 'text' => array(), ); $Block['element']['text'][0]['text'] []= array( 'name' => 'tr', 'handler' => 'elements', 'text' => $HeaderElements, ); return $Block; } } protected function blockTableContinue($Line, array $Block) { if (isset($Block['interrupted'])) { return; } if ($Line['text'][0] === '|' or strpos($Line['text'], '|')) { $Elements = array(); $row = $Line['text']; $row = trim($row); $row = trim($row, '|'); preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]+`|`)+/', $row, $matches); foreach ($matches[0] as $index => $cell) { $cell = trim($cell); $Element = array( 'name' => 'td', 'handler' => 'line', 'text' => $cell, ); if (isset($Block['alignments'][$index])) { $Element['attributes'] = array( 'style' => 'text-align: '.$Block['alignments'][$index].';', ); } $Elements []= $Element; } $Element = array( 'name' => 'tr', 'handler' => 'elements', 'text' => $Elements, ); $Block['element']['text'][1]['text'] []= $Element; return $Block; } } protected function paragraph($Line) { $Block = array( 'element' => array( 'name' => 'p', 'text' => $Line['text'], 'handler' => 'line', ), ); return $Block; } protected $InlineTypes = array( '"' => array('SpecialCharacter'), '!' => array('Image'), '&' => array('SpecialCharacter'), '*' => array('Emphasis'), ':' => array('Url'), '<' => array('UrlTag', 'EmailTag', 'Markup', 'SpecialCharacter'), '>' => array('SpecialCharacter'), '[' => array('Link'), '_' => array('Emphasis'), '`' => array('Code'), '~' => array('Strikethrough'), '\\' => array('EscapeSequence'), ); public function line($text) { $markup = ''; # $excerpt is based on the first occurrence of a marker while ($excerpt = strpbrk($text, $this->inlineMarkerList)) { $marker = $excerpt[0]; $markerPosition = strpos($text, $marker); $Excerpt = array('text' => $excerpt, 'context' => $text); foreach ($this->InlineTypes[$marker] as $inlineType) { $Inline = $this->{'inline'.$inlineType}($Excerpt); if (! isset($Inline)) { continue; } # makes sure that the inline belongs to "our" marker if (isset($Inline['position']) and $Inline['position'] > $markerPosition) { continue; } # sets a default inline position if (! isset($Inline['position'])) { $Inline['position'] = $markerPosition; } # the text that comes before the inline $unmarkedText = substr($text, 0, $Inline['position']); # compile the unmarked text $markup .= $this->unmarkedText($unmarkedText); # compile the inline $markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']); # remove the examined text $text = substr($text, $Inline['position'] + $Inline['extent']); continue 2; } # the marker does not belong to an inline $unmarkedText = substr($text, 0, $markerPosition + 1); $markup .= $this->unmarkedText($unmarkedText); $text = substr($text, $markerPosition + 1); } $markup .= $this->unmarkedText($text); return $markup; } protected function inlineCode($Excerpt) { $marker = $Excerpt['text'][0]; if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(?<!'.$marker.')\1(?!'.$marker.')/s', $Excerpt['text'], $matches)) { $text = $matches[2]; $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8'); $text = preg_replace("/[ ]*\n/", ' ', $text); return array( 'extent' => strlen($matches[0]), 'element' => array( 'name' => 'code', 'text' => $text, ), ); } } protected function inlineEmailTag($Excerpt) { if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<((mailto:)?\S+?@\S+?)>/i', $Excerpt['text'], $matches)) { $url = $matches[1]; if (! isset($matches[2])) { $url = 'mailto:' . $url; } return array( 'extent' => strlen($matches[0]), 'element' => array( 'name' => 'a', 'text' => $matches[1], 'attributes' => array( 'href' => $url, ), ), ); } } protected function inlineEmphasis($Excerpt) { if (! isset($Excerpt['text'][1])) { return; } $marker = $Excerpt['text'][0]; if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches)) { $emphasis = 'strong'; } elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches)) { $emphasis = 'em'; } else { return; } return array( 'extent' => strlen($matches[0]), 'element' => array( 'name' => $emphasis, 'handler' => 'line', 'text' => $matches[1], ), ); } protected function inlineEscapeSequence($Excerpt) { if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters)) { return array( 'markup' => $Excerpt['text'][1], 'extent' => 2, ); } } protected function inlineImage($Excerpt) { if (! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[') { return; } $Excerpt['text']= substr($Excerpt['text'], 1); $Link = $this->inlineLink($Excerpt); if ($Link === null) { return; } $Inline = array( 'extent' => $Link['extent'] + 1, 'element' => array( 'name' => 'img', 'attributes' => array( 'src' => $Link['element']['attributes']['href'], 'alt' => $Link['element']['text'], ), ), ); $Inline['element']['attributes'] += $Link['element']['attributes']; unset($Inline['element']['attributes']['href']); return $Inline; } protected function inlineLink($Excerpt) { $Element = array( 'name' => 'a', 'handler' => 'line', 'text' => null, 'attributes' => array( 'href' => null, 'title' => null, ), ); $extent = 0; $remainder = $Excerpt['text']; if (preg_match('/\[((?:[^][]|(?R))*)\]/', $remainder, $matches)) { $Element['text'] = $matches[1]; $extent += strlen($matches[0]); $remainder = substr($remainder, $extent); } else { return; } if (preg_match('/^[(]((?:[^ ()]|[(][^ )]+[)])+)(?:[ ]+("[^"]*"|\'[^\']*\'))?[)]/', $remainder, $matches)) { $Element['attributes']['href'] = $matches[1]; if (isset($matches[2])) { $Element['attributes']['title'] = substr($matches[2], 1, - 1); } $extent += strlen($matches[0]); } else { if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches)) { $definition = strlen($matches[1]) ? $matches[1] : $Element['text']; $definition = strtolower($definition); $extent += strlen($matches[0]); } else { $definition = strtolower($Element['text']); } if (! isset($this->DefinitionData['Reference'][$definition])) { return; } $Definition = $this->DefinitionData['Reference'][$definition]; $Element['attributes']['href'] = $Definition['url']; $Element['attributes']['title'] = $Definition['title']; } $Element['attributes']['href'] = str_replace(array('&', '<'), array('&amp;', '&lt;'), $Element['attributes']['href']); return array( 'extent' => $extent, 'element' => $Element, ); } protected function inlineMarkup($Excerpt) { if ($this->markupEscaped or strpos($Excerpt['text'], '>') === false) { return; } if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches)) { return array( 'markup' => $matches[0], 'extent' => strlen($matches[0]), ); } if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?[^-])*-->/s', $Excerpt['text'], $matches)) { return array( 'markup' => $matches[0], 'extent' => strlen($matches[0]), ); } if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches)) { return array( 'markup' => $matches[0], 'extent' => strlen($matches[0]), ); } } protected function inlineSpecialCharacter($Excerpt) { if ($Excerpt['text'][0] === '&' and ! preg_match('/^&#?\w+;/', $Excerpt['text'])) { return array( 'markup' => '&amp;', 'extent' => 1, ); } $SpecialCharacter = array('>' => 'gt', '<' => 'lt', '"' => 'quot'); if (isset($SpecialCharacter[$Excerpt['text'][0]])) { return array( 'markup' => '&'.$SpecialCharacter[$Excerpt['text'][0]].';', 'extent' => 1, ); } } protected function inlineStrikethrough($Excerpt) { if (! isset($Excerpt['text'][1])) { return; } if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches)) { return array( 'extent' => strlen($matches[0]), 'element' => array( 'name' => 'del', 'text' => $matches[1], 'handler' => 'line', ), ); } } protected function inlineUrl($Excerpt) { if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/') { return; }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
true
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/Image.php
inc/core/lib/Image.php
<?php /** * Image * * Easy image handling using PHP 5 and the GDlib * * @copyright Copyright 2010-2011, ushi <ushi@porkbox.net> * @link https://github.com/ushis/PHP-Image-Class * @license DBAD License (http://philsturgeon.co.uk/code/dbad-license) */ namespace Inc\Core\Lib; /** * Image processor */ class Image { /** * Image resource * * @var resource * @access private */ private $image; /** * Type of image * * @var string * @access private */ private $type = 'png'; /** * Width of the image in pixel * * @var integer * @access private */ private $width; /** * Height of the image in pixel * * @var integer * @access private */ private $height; /** * Return infos about the image * * @return array image infos * @access public */ public function getInfos($what = null) { if ($what !== null && in_array($what, ['width', 'height', 'type'])) { return $this->{$what}; } return array( 'width' => $this->width, 'height' => $this->height, 'type' => $this->type, 'resource' => $this->image, ); } /** * Get color in rgb * * @param string $hex Color in hexadecimal code * @return array Color in rgb * @access public */ private function hex2rgb($hex) { $hex = str_replace('#', '', $hex); $hex = (preg_match('/^([a-fA-F0-9]{3})|([a-fA-F0-9]{6})$/', $hex)) ? $hex : '000'; switch (strlen($hex)) { case 3: $rgb['r'] = hexdec(substr($hex, 0, 1).substr($hex, 0, 1)); $rgb['g'] = hexdec(substr($hex, 1, 1).substr($hex, 1, 1)); $rgb['b'] = hexdec(substr($hex, 2, 1).substr($hex, 2, 1)); break; case 6: $rgb['r'] = hexdec(substr($hex, 0, 2)); $rgb['g'] = hexdec(substr($hex, 2, 2)); $rgb['b'] = hexdec(substr($hex, 4, 2)); break; } return $rgb; } /** * Creates image resource from file * * @param string $path Path to an image * @return boolean true if resource was created * @access public */ public function load($path) { if (empty($path)) { return false; } $file = @fopen($path, 'r'); if (!$file) { return false; } fclose($file); $info = getimagesize($path); switch ($info[2]) { case 1: $this->image = imagecreatefromgif($path); $this->type = 'gif'; break; case 2: $this->image = imagecreatefromjpeg($path); $this->type = 'jpg'; break; case 3: $this->image = imagecreatefrompng($path); $this->type = 'png'; imagealphablending($this->image, false); imagesavealpha($this->image, true); break; default: return false; } $this->width = $info[0]; $this->height = $info[1]; return true; } /** * Creates image resource with background * * @param integer $width Width of the image * @param integer $height Height of the image * @param string $background Background color in hexadecimal code * @return boolean true if resource was created * @access public */ public function create($width, $height, $background = null) { if ($width > 0 && $height > 0) { $this->image = imagecreatetruecolor($width, $height); $this->width = $width; $this->height = $height; if (preg_match('/^([a-fA-F0-9]{3})|([a-fA-F0-9]{6})$/', $background)) { $rgb = $this->hex2rgb($background); $background = imagecolorallocate($this->image, $rgb['r'], $rgb['g'], $rgb['b']); imagefill($this->image, 0, 0, $background); } else { imagealphablending($this->image, false); $black = imagecolorallocate($this->image, 0, 0, 0); imagefilledrectangle($this->image, 0, 0, $this->width, $this->height, $black); imagecolortransparent($this->image, $black); imagealphablending($this->image, true); } return true; } return false; } /** * Resizes the image * * @param integer $width New width * @param integer $height New height * @return boolean true if image was resized * @access public */ public function resize($width, $height = 0) { if ($width <= 0 && $height <= 0) { return false; } elseif ($width > 0 && $height <= 0) { $height = $this->height*$width/$this->width; } elseif ($width <= 0 && $height > 0) { $width = $this->width*$height/$this->height; } $image = imagecreatetruecolor($width, $height); imagealphablending($image, false); imagesavealpha($image, true); imagecopyresampled($image, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height); $this->image = $image; $this->width = $width; $this->height = $height; return true; } /** * Crops a part of the image * * @param integer $x X-coordinate * @param integer $y Y-coordinate * @param integer $width Width of cutout * @param integer $height Height of cutout * @access public */ public function crop($x, $y, $width, $height) { $image = imagecreatetruecolor($width, $height); imagealphablending($image, false); imagesavealpha($image, true); imagecopyresampled($image, $this->image, 0, 0, $x, $y, $width, $height, $width, $height); $this->image = $image; $this->width = $width; $this->height = $height; } /** * Resizes and crops image to specified size * * @param int $width New width * @param int $height New height * @access public * @return void */ public function fit($width, $height) { if ($this->width > $this->height) { $this->resize(0, $height); $this->crop(($this->width - $width) / 2, 0, $width, $height); } else { $this->resize($width); $this->crop(0, ($this->height - $height) / 2, $width, $height); } } /** * Rotates image * * @param integer $angle in degree * @access public */ public function rotate($angle) { $this->image = imagerotate($this->image, $angle, 0); } /** * Creates rectangle * * @param integer $x1 X1-coordinate * @param integer $y1 Y1-coordinate * @param integer $x2 X2-coordinate * @param integer $y2 Y2-coordinate * @param string $color Color in hexadecimal code * @access public */ public function rectangle($x1, $y1, $x2, $y2, $color) { $rgb = $this->hex2rgb($color); $color = imagecolorallocate($this->image, $rgb['r'], $rgb['g'], $rgb['b']); imagefilledrectangle($this->image, $x1, $y1, $x2, $y2, $color); } /** * Creates ellipse * * @param integer $x X-coordinate * @param integer $y Y-coordinate * @param integer $width Width of ellipse * @param integer $height Height of ellipse * @param string $color Color in hexadecimal code * @access public */ public function ellipse($x, $y, $width, $height, $color) { $rgb = $this->hex2rgb($color); $color = imagecolorallocate($this->image, $rgb['r'], $rgb['g'], $rgb['b']); imagefilledellipse($this->image, $x, $y, $width, $height, $color); } /** * Creates polygon * * @param array $points Coordinates of the vertices * @param string $color Color in hexadecimal code * @access public */ public function polygon($points, $color) { $rgb = $this->hex2rgb($color); $color = imagecolorallocate($this->image, $rgb['r'], $rgb['g'], $rgb['b']); $num = count($points)/2; imagefilledpolygon($this->image, $points, $num, $color); } /** * Draws a line * * @param array $points Coordinates of the vertices * @param string $color Color in hexadecimal code * @access public */ public function line($points, $color) { $rgb = $this->hex2rgb($color); $color = imagecolorallocate($this->image, $rgb['r'], $rgb['g'], $rgb['b']); imageline($this->image, $points[0], $points[1], $points[2], $points[3], $color); } /** * Writes on image * * @param integer $x X-coordinate * @param integer $y Y-coordinate * @param string $font Path to ttf * @param integer $size Font size * @param integer $angle in degree * @param string $color Color in hexadecimal code * @param string $text Text * @access public */ public function write($x, $y, $font, $size, $angle, $color, $text) { $rgb = $this->hex2rgb($color); $color = imagecolorallocate($this->image, $rgb['r'], $rgb['g'], $rgb['b']); imagettftext($this->image, $size, $angle, $x, $y, $color, $font, $text); } /** * Merges image with another * * @param Image $img object * @param mixed $x X-coordinate * @param mixed $y Y-coordinate * @access public */ public function merge($img, $x, $y) { $infos = $img->getInfos(); switch ($x) { case 'left': $x = 0; break; case 'right': $x = $this->width-$infos['width']; break; default: $x = $x; } switch ($y) { case 'top': $y = 0; break; case 'bottom': $y = $this->height-$infos['height']; break; default: $y = $y; } imagealphablending($this->image, true); imagecopy($this->image, $infos['resource'], $x, $y, 0, 0, $infos['width'], $infos['height']); } /** * Shows image * * @param string $type Filetype * @access public */ public function show($type = 'png') { $type = ($type != 'gif' && $type != 'jpeg' && $type != 'png') ? $this->type : $type; switch ($type) { case 'gif': header('Content-type: image/gif'); imagegif($this->image); break; case 'jpeg': header('Content-type: image/jpeg'); imagejpeg($this->image, '', 100); break; default: header('Content-type: image/png'); imagepng($this->image); } } /** * Saves image * * @param string $path Path to location * @param string $type Filetype * @return boolean true if image was saved * @access public */ public function save($path, $quality = 90) { $dir = dirname($path); $type = pathinfo($path, PATHINFO_EXTENSION); if (!file_exists($dir) || !is_dir($dir)) { return false; } if (!is_writable($dir)) { return false; } if ($type != 'gif' && $type != 'jpeg' && $type != 'jpg' && $type != 'png') { $type = $this->type; $path .= '.'.$type; } switch ($type) { case 'gif': imagegif($this->image, $path); break; case 'jpeg': case 'jpg': imagejpeg($this->image, $path, $quality); break; default: imagepng($this->image, $path); } return true; } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/Settings.php
inc/core/lib/Settings.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core\Lib; /** * Batflat modules settings */ class Settings { /** * Instance of core class * * @var \Inc\Core\Main */ protected $core; /** * Cached settings variables * * @var array */ protected $cache = []; /** * Settings constructor * * @param \Inc\Core\Main $core */ public function __construct(\Inc\Core\Main $core) { $this->core = $core; $this->reload(); } /** * Get all settings * * @return array */ public function all() { return $this->cache; } /** * Fetch fresh data from database * * @return void */ public function reload() { $results = $this->core->db('settings')->toArray(); foreach ($results as $result) { $this->cache[$result['module']][$result['field']] = $result['value']; } } /** * Get specified field * * @param string $module Example 'module' or shorter 'module.field' * @param string $field OPTIONAL * @return string */ public function get($module, $field = false) { if (substr_count($module, '.') == 1) { list($module, $field) = explode('.', $module); } if (empty($field)) { return $this->cache[$module]; } return $this->cache[$module][$field]; } /** * Save specified settings value * * @param string $module Example 'module' or shorter 'module.field' * @param string $field If module has field it contains value * @param string $value OPTIONAL * @return bool */ public function set($module, $field, $value = false) { if (substr_count($module, '.') == 1) { $value = $field; list($module, $field) = explode('.', $module); } if ($value === false) { throw new \Exception('Value cannot be empty'); } if ($this->core->db('settings')->where('module', $module)->where('field', $field)->save(['value' => $value])) { $this->cache[$module][$field] = $value; return true; } return false; } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/Autoloader.php
inc/core/lib/Autoloader.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ require_once('functions.php'); /** * Batflat autoloader */ class Autoloader { /** * Autoload initialization * * @param string $className * @return void */ public static function init($className) { // Convert directories to lowercase and process uppercase for class files $className = explode('\\', $className); $file = array_pop($className); $file = strtolower(implode('/', $className)).'/'.$file.'.php'; if (strpos($_SERVER['SCRIPT_NAME'], '/'.ADMIN.'/') !== false) { $file = '../'.$file; } if (is_readable($file)) { require_once($file); } } } header(gz64_decode("eNqL0HUuSk0sSU3Rdaq0UnBKLEnLSSxRsEmCMPTyi9LtANXtDCw")); spl_autoload_register('Autoloader::init'); // Autoload vendors if exist if (file_exists(BASE_DIR.'/vendor/autoload.php')) { require_once(BASE_DIR.'/vendor/autoload.php'); }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/HttpRequest.php
inc/core/lib/HttpRequest.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core\Lib; /** * HttpRequest Class */ class HttpRequest { /** * Status of latest request * * @var string */ protected static $lastStatus = null; /** * GET method request * * @param string $url * @param array $datafields * @param array $headers * @return string Output */ public static function get($url, $datafields = [], $headers = []) { return self::request('GET', $url, $datafields, $headers); } /** * POST method request * * @param string $url * @param array $datafields * @param array $headers * @return string Output */ public static function post($url, $datafields = [], $headers = []) { return self::request('POST', $url, $datafields, $headers); } /** * Get last request status * * @return string */ public static function getStatus() { return self::$lastStatus; } /** * Universal request method * * @param string $type GET, POST, PUT, DELETE, UPDATE * @param string $url * @param array $datafields * @param array $headers * @return string */ protected static function request($type, $url, $datafields, $headers) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type); if (!empty($datafields)) { curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datafields)); } if (!empty($headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 3); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); self::$lastStatus = curl_error($ch); curl_close($ch); return $output; } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/ModulesCollection.php
inc/core/lib/ModulesCollection.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core\Lib; /** * Batflat modules collection */ class ModulesCollection { /** * List of loaded modules * * @var array */ protected $modules = []; /** * ModulesCollection constructor * * @param \Inc\Core\Main $core */ public function __construct($core) { $modules = array_column($core->db('modules')->asc('sequence')->toArray(), 'dir'); if ($core instanceof \Inc\Core\Admin) { $clsName = 'Admin'; } else { $clsName = 'Site'; } foreach ($modules as $dir) { $file = MODULES.'/'.$dir.'/'.$clsName.'.php'; if (file_exists($file)) { $namespace = 'inc\modules\\'.$dir.'\\'.$clsName; $this->modules[$dir] = new $namespace($core); } } // Init loop $this->initLoop(); // Routes loop for Site if ($clsName != 'Admin') { $this->routesLoop(); } } /** * Executes all init methods * * @return void */ protected function initLoop() { foreach ($this->modules as $module) { $module->init(); } } /** * Executes all routes methods * * @return void */ protected function routesLoop() { foreach ($this->modules as $module) { $module->routes(); } } /** * Executes all finish methods * * @return void */ public function finishLoop() { foreach ($this->modules as $module) { $module->finish(); } } /** * Get list of modules as array * * @return array */ public function getArray() { return $this->modules; } /** * Check if collection has loaded module * * @param string $name * @return bool */ public function has($name) { return array_key_exists($name, $this->modules); } /** * Get specified module by magic method * * @param string $module * @return \Inc\Core\BaseModule */ public function __get($module) { if (isset($this->modules[$module])) { return $this->modules[$module]; } else { return null; } } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/functions.php
inc/core/lib/functions.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ /** * check if array have an empty values * * @param array $keys * @param array $array * * @return boolean */ function checkEmptyFields(array $keys, array $array) { foreach ($keys as $field) { if (empty($array[$field])) { return true; } } return false; } /** * delte dir with files * * @param string $path * * @return boolean */ function deleteDir($path) { return !empty($path) && is_file($path) ? @unlink($path) : (array_reduce(glob($path.'/*'), function ($r, $i) { return $r && deleteDir($i); }, true)) && @rmdir($path); } /** * remove special chars from string * * @param string $text * * @return string */ function createSlug($text) { setlocale(LC_ALL, 'pl_PL'); $text = str_replace(' ', '-', trim($text)); $text = str_replace('.', '-', trim($text)); $text = iconv('utf-8', 'ascii//translit', $text); $text = preg_replace('#[^a-z0-9\-]#si', '', $text); $text = str_replace('\'', '', $text); return strtolower($text ? $text : '-'); } /** * convert special chars from array * * @param array $array * * @return array */ function htmlspecialchars_array(array $array) { foreach ($array as $key => $value) { if (is_array($value)) { $array[$key] = htmlspecialchars_array($value); } else { $array[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8'); } } return $array; } /** * convert all characters to HTML entities from array * * @param array $array * * @return array */ function htmlentities_array(array $array) { foreach ($array as $key => $value) { if (is_array($value)) { $array[$key] = htmlentities_array($value); } else { $array[$key] = htmlentities($value, ENT_QUOTES | ENT_HTML5, 'UTF-8'); } } return $array; } /** * redirect to URL * * @param string $url * @param array $data * * @return void */ function redirect($url, array $data = []) { if ($data) { $_SESSION['REDIRECT_DATA'] = $data; } header("Location: $url"); exit(); } /** * get data from session * * @return array or null */ function getRedirectData() { if (isset($_SESSION['REDIRECT_DATA'])) { $tmp = $_SESSION['REDIRECT_DATA']; unset($_SESSION['REDIRECT_DATA']); return $tmp; } return null; } /** * Returns current url * * @param boolean $query * * @return string */ function currentURL($query = false) { if (isset_or($GLOBALS['core'], null) instanceof \Inc\Core\Admin) { $url = url(ADMIN.'/'.implode('/', parseURL())); } else { $url = url(implode('/', parseURL())); } if ($query) { return $url.'?'.$_SERVER['QUERY_STRING']; } else { return $url; } } /** * parse URL * * @param int $key * * @return mixed array, string or false */ function parseURL($key = null) { $url = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/'); $url = trim(str_replace($url, '', $_SERVER['REQUEST_URI']), '/'); $url = explode('?', $url); $array = explode('/', $url[0]); if ($key) { return isset_or($array[$key - 1], false); } else { return $array; } } /** * add token to URL * * @param string $url * * @return string */ function addToken($url) { if (isset($_SESSION['token'])) { if (parse_url($url, PHP_URL_QUERY)) { return $url.'&t='.$_SESSION['token']; } else { return $url.'?t='.$_SESSION['token']; } } return $url; } /** * create URL * * @param string / array $data * * @return string */ function url($data = null) { if (filter_var($data, FILTER_VALIDATE_URL) !== false) { return $data; } if (!is_array($data) && strpos($data, '#') === 0) { return $data; } if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || isset_or($_SERVER['SERVER_PORT'], null) == 443 || isset_or($_SERVER['HTTP_X_FORWARDED_PORT'], null) == 443 || isset_or($_SERVER['HTTP_X_FORWARDED_PROTO'], null) == 'https' ) { $protocol = 'https://'; } else { $protocol = 'http://'; } $url = trim($protocol.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']), '/\\'); $url = str_replace('/'.ADMIN, '', $url); if (is_array($data)) { $url = $url.'/'.implode('/', $data); } elseif ($data) { $data = str_replace(BASE_DIR.'/', null, $data); $url = $url.'/'.trim($data, '/'); } if (strpos($url, '/'.ADMIN.'/') !== false) { $url = addToken($url); } return $url; } /** * Current domain name * * @return string */ function domain($with_protocol = true, $cut_www = false) { $url = parse_url(url()); if ($cut_www && strpos($url['host'], 'www.') === 0) { $host = str_replace('www.', null, $url['host']); } else { $host = $url['host']; } if ($with_protocol) { return $url['scheme'].'://'.$host; } return $host; } /** * Batflat dir name * * @return string */ function batflat_dir() { return dirname(str_replace(ADMIN, null, $_SERVER['SCRIPT_NAME'])); } /** * toggle empty variable * * @param mixed $var * @param mixed $alternate * * @return mixed */ function isset_or(&$var, $alternate = null) { return (isset($var)) ? $var : $alternate; } /** * compares two version number strings * * @param string $a * @param string $b * * @return int */ function cmpver($a, $b) { $a = explode(".", $a); $b = explode(".", $b); foreach ($a as $depth => $aVal) { if (isset($b[$depth])) { $bVal = $b[$depth]; } else { $bVal = "0"; } list($aLen, $bLen) = [strlen($aVal), strlen($bVal)]; if ($aLen > $bLen) { $bVal = str_pad($bVal, $aLen, "0"); } elseif ($bLen > $aLen) { $aVal = str_pad($aVal, $bLen, "0"); } if ($aVal == $bVal) { continue; } if ($aVal > $bVal) { return 1; } if ($aVal < $bVal) { return -1; } } return 0; } /** * Limits string to specified length and appends with $end value * * @param string $text Input text * @param integer $limit String max length * @param string $end Appending variable if text is longer than limit * * @return string Limited string */ function str_limit($text, $limit = 100, $end = '...') { if (mb_strlen($text, 'UTF-8') > $limit) { return mb_substr($text, 0, $limit, 'UTF-8').$end; } return $text; } /** * Get response headers list * * @param string $key * * @return mixed Array of headers or specified header by $key */ function get_headers_list($key = null) { $headers_list = headers_list(); $headers = []; foreach ($headers_list as $header) { $e = explode(":", $header); $headers[strtolower(array_shift($e))] = trim(implode(":", $e)); } if ($key) { return isset_or($headers[strtolower($key)], false); } return $headers; } /** * Generating random hash from specified characters * * @param int $length Hash length * @param string $characters Characters for hash * * @return string Generated random string */ function str_gen($length, $characters = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") { $return = null; if (is_string($characters)) { $characters = str_split($characters); } for ($i = 0; $i < $length; $i++) { $return .= $characters[rand(0, count($characters) - 1)]; } return $return; } /** * Compressed base64_encode * * @param strin $string * * @return string */ function gz64_encode($string) { return str_replace(['+', '/'], ['_', '-'], trim(base64_encode(gzcompress($string, 9)), "=")); } /** * Decompress base64_decode * * @param string $string * * @return string */ function gz64_decode($string) { return gzuncompress(base64_decode(str_replace(['_', '-'], ['+', '/'], $string))); } /** * Call variable which can be callback or other type. * If it is anonymous function it will be executed, otherwise $variable will be returned. * * @param mixed $variable * * @return mixed */ function cv($variable) { if (!is_string($variable) && is_callable($variable)) { return $variable(); } return $variable; }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/Widget.php
inc/core/lib/Widget.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core\Lib; /** * Widgets class */ class Widget { /** @var array Widgets collection */ protected static $widgets = []; /** * Add widget to collection * * @param string $name * @param callable $callback * @return void */ public static function add($name, callable $callback) { static::$widgets[$name][] = $callback; } /** * Execute all widgets and get content * * @param string $name * @param array $params * @return string */ public static function call($name, $params = []) { $result = []; foreach (isset_or(static::$widgets[$name], []) as $widget) { $content = call_user_func_array($widget, $params); if (is_string($content)) { $result[] = $content; } } return implode("\n", $result); } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/Event.php
inc/core/lib/Event.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core\Lib; /** * Events class */ class Event { /** @var array */ protected static $events = []; /** * Add new event handler * * @param string $name * @param callable $callback * @return void */ public static function add($name, callable $callback) { static::$events[$name][] = $callback; } /** * Execute registered event handlers * * @param string $name * @param array $params * @return bool */ public static function call($name, array $params = []) { $return = true; foreach (isset_or(static::$events[$name], []) as $value) { $return = $return && (call_user_func_array($value, $params) !== false); } return $return; } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/License.php
inc/core/lib/License.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core\Lib; /** * Batflat License class * By removing or modifing these procedures you break license. */ class License { const FREE = 1; const COMMERCIAL = 2; const ERROR = 3; const INVALID_DOMAIN = 4; const TIME_OUT = 5; private static $feedURL = 'http://feed.sruu.pl'; public static function verify($license) { $license = self::unpack($license); if ($license[0] === false && $license[1] === false && $license[2] === false && $license[3] === false && $license[4] === false) { return License::FREE; } if ($license[0] == md5($license[1].$license[2].$license[3].domain(false, true))) { if (time() < $license[4] || strtotime("-48 hours") > $license[4]) { if (self::remoteCheck($license)) { self::update($license); return License::COMMERCIAL; } elseif (strpos(HttpRequest::getStatus(), 'timed out') !== false) { return License::TIME_OUT; } else { return License::ERROR; } } else { return License::COMMERCIAL; } } return License::ERROR; } public static function getLicenseData($domainCode) { $response = json_decode(HttpRequest::post(self::$feedURL.'/batflat/commercial/license/data', ['code' => $domainCode, 'domain' => domain(false)]), true); if (isset_or($response['status'], false) == 'verified') { return $response['data']; } return false; } private static function unpack($code) { $code = base64_decode($code); $code = empty($code) ? [] : json_decode($code, true); $code = array_replace(array_fill(0, 5, false), $code); array_walk($code, function (&$value) { $value = is_numeric($value) ? intval($value) : $value; }); return $code; } private static function update($license) { $license[4] = time(); $core = $GLOBALS['core']; $core->db('settings')->where('module', 'settings')->where('field', 'license')->save(['value' => base64_encode(json_encode($license))]); } private static function remoteCheck($license) { $output = HttpRequest::post(self::$feedURL.'/batflat/commercial/license/verify', ['pid' => $license[1], 'code' => $license[2], 'domain' => domain(false), 'domainCode' => $license[3]]); $output = json_decode($output, true); if (isset_or($output['status'], false) == 'verified') { return true; } return false; } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/QueryBuilder.php
inc/core/lib/QueryBuilder.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core\Lib; /** * Batflat QueryBuilder class */ class QueryBuilder { protected static $db = null; protected static $last_sqls = []; protected static $options = []; protected $table = null; protected $columns = []; protected $joins = []; protected $conditions = []; protected $condition_binds = []; protected $sets = []; protected $set_binds = []; protected $orders = []; protected $group_by = []; protected $having = []; protected $limit = ''; protected $offset = ''; /** * constructor * * @param string $table */ public function __construct($table = null) { if ($table) { $this->table = $table; } } /** * PDO instance * * @return PDO */ public static function pdo() { return static::$db; } /** * last SQL queries * * @return array SQLs array */ public static function lastSqls() { return static::$last_sqls; } /** * creates connection with database * * Qb::connect($dsn); // default user, password and options * Qb::connect($dsn, $user); // default password and options * Qb::connect($dsn, $user, $pass); // default options * Qb::connect($dsn, $user, $pass, $options); * Qb::connect($dsn, $options); * Qb::connect($dsn, $user, $options); * * @param string $dsn * @param string $user * @param string $pass * @param array $options * primary_key: primary column name, default: 'id' * error_mode: default: \PDO::ERRMODE_EXCEPTION * json_options: default: JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT */ public static function connect($dsn, $user = '', $pass = '', $options = []) { if (is_array($user)) { $options = $user; $user = ''; $pass = ''; } elseif (is_array($pass)) { $options = $pass; $pass = ''; } static::$options = array_merge([ 'primary_key' => 'id', 'error_mode' => \PDO::ERRMODE_EXCEPTION, 'json_options' => JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT, ], $options); static::$db = new \PDO($dsn, $user, $pass); static::$db->setAttribute(\PDO::ATTR_ERRMODE, static::$options['error_mode']); if (strpos($dsn, 'sqlite') !== false) { static::$db->exec("pragma synchronous = off;"); } } /** * close connection with database */ public static function close() { static::$db = null; } /** * get or set options * * @param string $name * @param mixed $value */ public static function config($name, $value = null) { if ($value === null) { return static::$options[$name]; } else { static::$options[$name] = $value; } } /** * SELECT * * select('column1')->select('column2') // SELECT column1, column2 * select(['column1', 'column2', ...]) // SELECT column1, column2, ... * select(['alias1' => 'column1', 'column2', ...]) // SELECT column1 AS alias1, column2, ... * * @param string|array $columns * * @return \Inc\Core\Lib\QueryBuilder */ public function select($columns) { if (!is_array($columns)) { $columns = array($columns); } foreach ($columns as $alias => $column) { if (!is_numeric($alias)) { $column .= " AS $alias"; } array_push($this->columns, $column); } return $this; } /** * INNER JOIN * * @param string $table * @param string $condition * * @return \Inc\Core\Lib\QueryBuilder */ public function join($table, $condition) { array_push($this->joins, "INNER JOIN $table ON $condition"); return $this; } /** * LEFT OUTER JOIN * * @param string $table * @param string $condition * * @return \Inc\Core\Lib\QueryBuilder */ public function leftJoin($table, $condition) { array_push($this->joins, "LEFT JOIN $table ON $condition"); return $this; } /** * HAVING * * having(aggregate_function, operator, value) // HAVING aggregate_function (=, <, >, <=, >=, <>) value * having(aggregate_function, value) // HAVING aggregate_function = value * * @param string $aggregate_function * @param mixed $value * * @return \Inc\Core\Lib\QueryBuilder */ public function having($aggregate_function, $operator, $value = null, $ao = 'AND') { if ($value === null) { $value = $operator; $operator = '='; } if (is_array($value)) { $qs = '(' . implode(',', array_fill(0, count($value), '?')) . ')'; if (empty($this->having)) { array_push($this->having, "$aggregate_function $operator $qs"); } else { array_push($this->having, "$ao $aggregate_function $operator $qs"); } foreach ($value as $v) { array_push($this->condition_binds, $v); } } else { if (empty($this->having)) { array_push($this->having, "$aggregate_function $operator ?"); } else { array_push($this->having, "$ao $aggregate_function $operator ?"); } array_push($this->condition_binds, $value); } return $this; } public function orHaving($aggregate_function, $operator, $value = null) { return $this->having($aggregate_function, $operator, $value, 'OR'); } /** * WHERE * * where(column, operator, value) // WHERE column (=, <, >, <=, >=, <>) value * where(column, value) // WHERE column = value * where(value) // WHERE id = value * where(function($st) { * $st->where()... * }) * * @param mixed $column * @param mixed $value * * @return \Inc\Core\Lib\QueryBuilder */ public function where($column, $operator = null, $value = null, $ao = 'AND') { // Where group if (!is_string($column) && is_callable($column)) { if (empty($this->conditions) || strpos(end($this->conditions), '(') !== false) { array_push($this->conditions, '('); } else { array_push($this->conditions, $ao.' ('); } call_user_func($column, $this); array_push($this->conditions, ')'); return $this; } if ($operator === null) { $value = $column; $column = static::$options['primary_key']; $operator = '='; } elseif ($value === null) { $value = $operator; $operator = '='; } if (is_array($value)) { foreach ($value as $v) { array_push($this->condition_binds, $v); } $value = '(' . implode(',', array_fill(0, count($value), '?')) . ')'; } else { array_push($this->condition_binds, $value); $value = "?"; } if (empty($this->conditions) || strpos(end($this->conditions), '(') !== false) { array_push($this->conditions, "$column $operator $value"); } else { array_push($this->conditions, "$ao $column $operator $value"); } return $this; } /** * OR WHERE * * orWhere(column, operator, value) // WHERE column (=, <, >, <=, >=, <>) value * orWhere(column, value) // WHERE column = value * orWhere(value) // WHERE id = value * orWhere(function($st) { * $st->where()... * }) * * @param mixed $column * @param mixed $value * * @return \Inc\Core\Lib\QueryBuilder */ public function orWhere($column, $operator = null, $value = null) { return $this->where($column, $operator, $value, 'OR'); } /** * WHERE IS NULL * * @param string $column * @param string $ao * @return \Inc\Core\Lib\QueryBuilder */ public function isNull($column, $ao = 'AND') { if (is_array($column)) { foreach ($column as $c) { $this->isNull($c, $ao); } return $this; } if (empty($this->conditions) || strpos(end($this->conditions), '(') !== false) { array_push($this->conditions, "$column IS NULL"); } else { array_push($this->conditions, "$ao $column IS NULL"); } return $this; } /** * WHERE IS NOT NULL * * @param string $column * @param string $ao * @return \Inc\Core\Lib\QueryBuilder */ public function isNotNull($column, $ao = 'AND') { if (is_array($column)) { foreach ($column as $c) { $this->isNotNull($c, $ao); } return $this; } if (empty($this->conditions) || strpos(end($this->conditions), '(') !== false) { array_push($this->conditions, "$column IS NOT NULL"); } else { array_push($this->conditions, "$ao $column IS NOT NULL"); } return $this; } /** * OR WHERE IS NULL * * @param string $column * @return \Inc\Core\Lib\QueryBuilder */ public function orIsNull($column) { return $this->isNull($column, 'OR'); } /** * OR WHERE IS NOT NULL * * @param string $column * @return \Inc\Core\Lib\QueryBuilder */ public function orIsNotNull($column) { return $this->isNotNull($column, 'OR'); } /** * WHERE LIKE * * @param string $column * @param mixed $value * * @return \Inc\Core\Lib\QueryBuilder */ public function like($column, $value) { $this->where($column, 'LIKE', $value); return $this; } /** * WHERE OR LIKE * * @param string $column * @param mixed $value * * @return \Inc\Core\Lib\QueryBuilder */ public function orLike($column, $value) { $this->where($column, 'LIKE', $value, 'OR'); return $this; } /** * WHERE NOT LIKE * * @param string $column * @param mixed $value * * @return \Inc\Core\Lib\QueryBuilder */ public function notLike($column, $value) { $this->where($column, 'NOT LIKE', $value); return $this; } /** * WHERE OR NOT LIKE * * @param string $column * @param mixed $value * * @return \Inc\Core\Lib\QueryBuilder */ public function orNotLike($column, $value) { $this->where($column, 'NOT LIKE', $value, 'OR'); return $this; } /** * WHERE IN * * @param string $column * @param array $values * * @return \Inc\Core\Lib\QueryBuilder */ public function in($column, $values) { $this->where($column, 'IN', $values); return $this; } /** * WHERE OR IN * * @param string $column * @param array $values * * @return \Inc\Core\Lib\QueryBuilder */ public function orIn($column, $values) { $this->where($column, 'IN', $values, 'OR'); return $this; } /** * WHERE NOT IN * * @param string $column * @param array $values * * @return \Inc\Core\Lib\QueryBuilder */ public function notIn($column, $values) { $this->where($column, 'NOT IN', $values); return $this; } /** * WHERE OR NOT IN * * @param string $column * @param array $values * * @return \Inc\Core\Lib\QueryBuilder */ public function orNotIn($column, $values) { $this->where($column, 'NOT IN', $values, 'OR'); return $this; } /** * get or set column value * * @param string $column * @param mixed $value * * @return \Inc\Core\Lib\QueryBuilder */ public function set($column, $value = null) { if (is_array($column)) { $sets = $column; } else { $sets = [$column => $value]; } $this->sets += $sets; return $this; } /** * UPDATE or INSERT * * @param string $column * @param mixed $value * * @return integer / boolean */ public function save($column = null, $value = null) { if ($column) { $this->set($column, $value); } $st = $this->_build(); if ($lid = static::$db->lastInsertId()) { return $lid; } else { return $st; } } /** * UPDATE * * @param string $column * @param mixed $value * * @return boolean */ public function update($column = null, $value = null) { if ($column) { $this->set($column, $value); } return $this->_build(['only_update' => true]); } /** * ORDER BY ASC * * @param string $column * * @return \Inc\Core\Lib\QueryBuilder */ public function asc($column) { array_push($this->orders, "$column ASC"); return $this; } /** * ORDER BY DESC * * @param string $column * * @return \Inc\Core\Lib\QueryBuilder */ public function desc($column) { array_push($this->orders, "$column DESC"); return $this; } /** * GROUP BY * * @param mixed $column * * @return \Inc\Core\Lib\QueryBuilder */ public function group($columns) { if (is_array($columns)) { foreach ($columns as $column) { array_push($this->group_by, "$column"); } } else { array_push($this->group_by, "$columns"); } return $this; } /** * LIMIT * * @param integer $num * * @return \Inc\Core\Lib\QueryBuilder */ public function limit($num) { $this->limit = " LIMIT $num"; return $this; } /** * OFFSET * * @param integer $num * * @return \Inc\Core\Lib\QueryBuilder */ public function offset($num) { $this->offset = " OFFSET $num"; return $this; } /** * create array with all rows * * @return array */ public function toArray() { $st = $this->_build(); return $st->fetchAll(\PDO::FETCH_ASSOC); } /** * create object with all rows * * @return \stdObject[] */ public function toObject() { $st = $this->_build(); return $st->fetchAll(\PDO::FETCH_OBJ); } /** * create JSON array with all rows * * @return string */ public function toJson() { $rows = $this->toArray(); return json_encode($rows, static::$options['json_options']); } /** * create array with one row * * @param string $column * @param mixed $value * * @return array */ public function oneArray($column = null, $value = null) { if ($column !== null) { $this->where($column, $value); } $st = $this->_build(); return $st->fetch(\PDO::FETCH_ASSOC); } /** * create object with one row * * @param string $column * @param mixed $value * * @return \stdObject */ public function oneObject($column = null, $value = null) { if ($column !== null) { $this->where($column, $value); } $st = $this->_build(); return $st->fetch(\PDO::FETCH_OBJ); } /** * create JSON array with one row * * @param string $column * @param mixed $value * * @return string */ public function oneJson($column = null, $value = null) { if ($column !== null) { $this->where($column, $value); } $row = $this->oneArray(); return json_encode($row, static::$options['json_options']); } /** * returns rows count * * @return integer */ public function count() { $st = $this->_build('count'); return $st->fetchColumn(); } /** * Last inserted id * * @return integer */ public function lastInsertId() { return static::$db->lastInsertId(); } /** * DELETE * * @param string $column * @param mixed $value */ public function delete($column = null, $value = null) { if ($column !== null) { $this->where($column, $value); } $st = $this->_build('delete'); return $st->rowCount(); } /** * Create SQL query * * @param $type `default`, `delete`, `count` * * @return string */ public function toSql($type = 'default') { $sql = ''; $sql_where = ''; $sql_having = ''; // build conditions $conditions = implode(' ', $this->conditions); $conditions = str_replace(['( ', ' )'], ['(', ')'], $conditions); if ($conditions) { $sql_where .= " WHERE $conditions"; } // build having $having = implode(' ', $this->having); if ($having) { $sql_having .= " HAVING $having"; } // if some columns have set value then UPDATE or INSERT if ($this->sets) { // get table columns $table_cols = $this->_getColumns(); // Update updated_at column if exists if (in_array('updated_at', $table_cols) && !array_key_exists('updated_at', $this->sets)) { $this->set('updated_at', time()); } // if there are some conditions then UPDATE if (!empty($this->conditions)) { $insert = false; $columns = implode('=?,', array_keys($this->sets)) . '=?'; $this->set_binds = array_values($this->sets); $sql = "UPDATE $this->table SET $columns"; $sql .= $sql_where; return $sql; } // if there aren't conditions, then INSERT else { // Update created_at column if exists if (in_array('created_at', $table_cols) && !array_key_exists('created_at', $this->sets)) { $this->set('created_at', time()); } $columns = implode(',', array_keys($this->sets)); $this->set_binds = array_values($this->sets); $qs = implode(',', array_fill(0, count($this->sets), '?')); $sql = "INSERT INTO $this->table($columns) VALUES($qs)"; $this->condition_binds = array(); return $sql; } } else { if ($type == 'delete') { // DELETE $sql = "DELETE FROM $this->table"; $sql .= $sql_where; return $sql; } else { // SELECT $columns = implode(',', $this->columns); if (!$columns) { $columns = '*'; } if ($type == 'count') { $columns = "COUNT($columns) AS count"; } $sql = "SELECT $columns FROM $this->table"; $joins = implode(' ', $this->joins); if ($joins) { $sql .= " $joins"; } $order = ''; if (count($this->orders) > 0) { $order = ' ORDER BY ' . implode(',', $this->orders); } $group_by = ''; if (count($this->group_by) > 0) { $group_by = ' GROUP BY ' . implode(',', $this->group_by); } $sql .= $sql_where . $group_by . $order . $sql_having . $this->limit . $this->offset; return $sql; } } return null; } /** * build SQL query * * @param array $type `default`, `delete`, `count` * * @return PDOStatement */ protected function _build($type = 'default') { return $this->_query($this->toSql($type)); } /** * execute SQL query * * @param string $sql * * @return PDOStatement */ protected function _query($sql) { $binds = array_merge($this->set_binds, $this->condition_binds); $st = static::$db->prepare($sql); foreach ($binds as $key => $bind) { $pdo_param = \PDO::PARAM_STR; if (is_int($bind)) { $pdo_param = \PDO::PARAM_INT; } $st->bindValue($key+1, $bind, $pdo_param); } $st->execute(); static::$last_sqls[] = $sql; return $st; } /** * Get current table columns * * @return array */ protected function _getColumns() { $q = $this->pdo()->query("PRAGMA table_info(".$this->table.")")->fetchAll(); return array_column($q, 'name'); } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/Router.php
inc/core/lib/Router.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core\Lib; /** * Batflat Router class */ class Router { /** * Declared routes * * @var array */ private $routes = array(); /** * Route patterns that converts to regexp style * * @var array */ private $patterns = array( ':any' => '.*', ':int' => '[0-9]+', ':str' => '[a-zA-Z0-9_-]+', ); /** * Set route * * @param string $pattern * @param callable $callback * @return void */ public function set($pattern, $callback) { $pattern = str_replace('/', '\/', $pattern); $this->routes[$pattern] = $callback; } /** * Executes routing and parse matches * * @param boolean $returnPath * @return mixed */ public function execute($returnPath = false) { if (empty($path) && empty($_SERVER['PATH_INFO'])) { $_SERVER['PATH_INFO'] = explode("?", $_SERVER['REQUEST_URI'])[0]; } $url = rtrim(dirname($_SERVER["SCRIPT_NAME"]), '/'); $url = trim(preg_replace('#'.$url.'#', '', $_SERVER['PATH_INFO'], 1), '/'); if ($returnPath) { return $url; } $patterns = '/('.implode('|', array_keys($this->patterns)).')/'; uksort($this->routes, function ($a, $b) use ($patterns) { $pointsA = preg_match_all('/(\/)/', $a); $pointsB = preg_match_all('/(\/)/', $b); if ($pointsA == $pointsB) { $pointsA = preg_match_all($patterns, $a); $pointsB = preg_match_all($patterns, $b); } return $pointsA > $pointsB; }); foreach ($this->routes as $pattern => $callback) { if (strpos($pattern, ':') !== false) { $pattern = str_replace(array_keys($this->patterns), array_values($this->patterns), $pattern); } if (preg_match('#^'.$pattern.'$#', $url, $params) === 1) { array_shift($params); array_walk($params, function (&$val) { $val = $val ?: null; }); return call_user_func_array($callback, array_values($params)); } } Event::call('router.notfound'); } /** * Change current "path" to custom * * @param string $path * @return void */ public function changeRoute($path) { $_SERVER['PATH_INFO'] = $path; } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
sruupl/batflat
https://github.com/sruupl/batflat/blob/f64373702f9589cd02d203a1cae505f6668c51c5/inc/core/lib/Templates.php
inc/core/lib/Templates.php
<?php /** * This file is part of Batflat ~ the lightweight, fast and easy CMS * * @author Paweł Klockiewicz <klockiewicz@sruu.pl> * @author Wojciech Król <krol@sruu.pl> * @copyright 2017 Paweł Klockiewicz, Wojciech Król <Sruu.pl> * @license https://batflat.org/license * @link https://batflat.org */ namespace Inc\Core\Lib; /** * Templates class */ class Templates { /** * Variables for template usage * * @var array */ private $data = []; /** * Temporary directory for Templates cache * * @var string */ private $tmp = 'tmp/'; /** * Template tags list * * @var array */ private $tags = [ '{\*(.*?)\*}' => 'self::comment', '{noparse}(.*?){\/noparse}' => 'self::noParse', '{if: ([^}]*)}' => '<?php if ($1): ?>', '{else}' => '<?php else: ?>', '{elseif: ([^}]*)}' => '<?php elseif ($1): ?>', '{\/if}' => '<?php endif; ?>', '{loop: ([^}]*) as ([^}]*)=>([^}]*)}' => '<?php $counter = 0; foreach (%%$1 as $2=>$3): ?>', '{loop: ([^}]*) as ([^}]*)}' => '<?php $counter = 0; foreach (%%$1 as $key => $2): ?>', '{loop: ([^}]*)}' => '<?php $counter = 0; foreach (%%$1 as $key => $value): ?>', '{\/loop}' => '<?php $counter++; endforeach; ?>', '{\?(\=){0,1}([^}]*)\?}' => '<?php if(strlen("$1")) echo $2; else $2; ?>', '{(\$[a-zA-Z\-\._\[\]\'"0-9]+)}' => '<?php echo %%$1; ?>', '{(\$[a-zA-Z\-\._\[\]\'"0-9]+)\|e}' => '<?php echo htmlspecialchars(%%$1, ENT_QUOTES | ENT_HTML5, "UTF-8"); ?>', '{(\$[a-zA-Z\-\._\[\]\'"0-9]+)\|cut:([0-9]+)}' => '<?php echo str_limit(strip_tags(%%$1), $2); ?>', '{widget: ([\.\-a-zA-Z0-9]+)}' => '<?php echo \Inc\Core\Lib\Widget::call(\'$1\'); ?>', '{include: (.+?\.[a-z]{2,4})}' => '<?php include_once(str_replace(url()."/", null, "$1")); ?>', '{template: (.+?\.[a-z]{2,4})}' => '<?php include_once(str_replace(url()."/", null, $bat["theme"]."/$1")); ?>', '{lang: ([a-z]{2}_[a-z]+)}' => '<?php if($bat["lang"] == "$1"): ?>', '{/lang}' => '<?php endif; ?>', ]; /** * Instance of Batflat core class * * @var \Inc\Core\Main */ public $core; /** * Templates constructor * * @param Inc\Core\Main $object */ public function __construct($object) { $this->core = $object; if (!file_exists($this->tmp)) { mkdir($this->tmp); } } /** * set variable * @param string $name * @param mixed $value * @return Templates $this */ public function set($name, $value) { $this->data[$name] = $value; return $this; } /** * append array variable * @param string $name * @param mixed $value * @return void */ public function append($name, $value) { $this->data[$name][] = $value; } /** * content parsing * @param string $content * @return string */ private function parse($content) { // replace tags with PHP foreach ($this->tags as $regexp => $replace) { if (strpos($replace, 'self') !== false) { $content = preg_replace_callback('#'.$regexp.'#s', $replace, $content); } else { $content = preg_replace('#'.$regexp.'#', $replace, $content); } } // replace variables if (preg_match_all('/(\$(?:[a-zA-Z0-9_-]+)(?:\.(?:(?:[a-zA-Z0-9_-][^\s]+)))*)/', $content, $matches)) { $matches = $this->organize_array($matches); usort($matches, function ($a, $b) { return strlen($a[0]) < strlen($b[0]); }); foreach ($matches as $match) { // $a.b to $a["b"] $rep = $this->replaceVariable($match[1]); $content = str_replace($match[0], $rep, $content); } } // remove spaces betweend %% and $ $content = preg_replace('/\%\%\s+/', '%%', $content); // call cv() for signed variables if (preg_match_all('/\%\%(.)([a-zA-Z0-9_-]+)/', $content, $matches)) { $matches = $this->organize_array($matches); usort($matches, function ($a, $b) { return strlen($a[2]) < strlen($b[2]); }); foreach ($matches as $match) { if ($match[1] == '$') { $content = str_replace($match[0], 'cv($'.$match[2].')', $content); } else { $content = str_replace($match[0], $match[1].$match[2], $content); } } } return $content; } /** * Organize preg_match_all matches array * * @param array $input * @return array */ protected function organize_array($input) { for ($z = 0; $z < count($input); $z++) { for ($x = 0; $x < count($input[$z]); $x++) { $rt[$x][$z] = $input[$z][$x]; } } return $rt; } /** * execute PHP code * @param string $file * @return string */ private function execute($file, $counter = 0) { $pathInfo = pathinfo($file); $tmpFile = $this->tmp.$pathInfo['basename']; if (!is_file($file)) { echo "Template '$file' not found."; } else { $content = file_get_contents($file); if ($this->searchTags($content) && ($counter < 3)) { file_put_contents($tmpFile, $content); $content = $this->execute($tmpFile, ++$counter); } file_put_contents($tmpFile, $this->parse($content)); extract($this->data, EXTR_SKIP); ob_start(); include($tmpFile); if (!DEV_MODE) { unlink($tmpFile); } return ob_get_clean(); } } /** * display compiled code * @param string $file * @param bool $last * @return string */ public function draw($file, $last = false) { if (preg_match('#inc(\/modules\/[^"]*\/)view\/([^"]*.'.pathinfo($file, PATHINFO_EXTENSION).')#', $file, $m)) { $themeFile = THEMES.'/'.$this->core->settings->get('settings.theme').$m[1].$m[2]; if (is_file($themeFile)) { $file = $themeFile; } } $result = $this->execute($file); if (!$last) { return $result; } else { $result = str_replace(['*bracket*','*/bracket*'], ['{', '}'], $result); $result = str_replace('*dollar*', '$', $result); if (HTML_BEAUTY) { $tidyHTML = new Indenter; return $tidyHTML->indent($result); } return $result; } } /** * replace signs {,},$ in string with *words* * @param string $content * @return string */ public function noParse($content) { if (is_array($content)) { $content = $content[1]; } $content = str_replace(['{', '}'], ['*bracket*', '*/bracket*'], $content); return str_replace('$', '*dollar*', $content); } /** * replace signs {,},$ in array with *words* * @param arry $array * @return array */ public function noParse_array($array) { foreach ($array as $key => $value) { if (is_array($value)) { $array[$key] = $this->noParse_array($value); } else { $array[$key] = $this->noParse($value); } } return $array; } /** * remove selected content from source code * @param string $content * @return null */ public function comment($content) { return null; } /** * search tags in content * @param string $content * @return bool */ private function searchTags($content) { foreach ($this->tags as $regexp => $replace) { if (preg_match('#'.$regexp.'#sU', $content, $matches)) { return true; } } return false; } /** * Replace dot based variable to PHP version * $a.b => $a['b'] * * @param string $var * @return string */ private function replaceVariable($var) { if (strpos($var, '.') === false) { return $var; } return preg_replace('/\.([a-zA-Z\-_0-9]*(?![a-zA-Z\-_0-9]*(\'|\")))/', "['$1']", $var); } }
php
MIT
f64373702f9589cd02d203a1cae505f6668c51c5
2026-01-05T04:56:05.555415Z
false
davmixcool/php-sentiment-analyzer
https://github.com/davmixcool/php-sentiment-analyzer/blob/b8bdc463643a9093e1cbf9b01de2fd7cddd27f24/src/Analyzer.php
src/Analyzer.php
<?php namespace Sentiment; use Sentiment\Config\Config; use Sentiment\Procedures\SentiText; /* Give a sentiment intensity score to sentences. */ class Analyzer { private $lexicon_file = ""; private $lexicon = ""; private $current_sentitext = null; public function __construct($lexicon_file = "Lexicons/vader_sentiment_lexicon.txt",$emoji_lexicon='Lexicons/emoji_utf8_lexicon.txt') { //Not sure about this as it forces lexicon file to be in the same directory as executing script $this->lexicon_file = __DIR__ . DIRECTORY_SEPARATOR . $lexicon_file; $this->lexicon = $this->make_lex_dict(); $this->emoji_lexicon = __DIR__ . DIRECTORY_SEPARATOR .$emoji_lexicon; $this->emojis = $this->make_emoji_dict(); } /* Determine if input contains negation words */ public function IsNegated($wordToTest, $include_nt = true) { $wordToTest = strtolower($wordToTest); if (in_array($wordToTest, Config::NEGATE)) { return true; } if ($include_nt) { if (strpos($wordToTest, "n't")) { return true; } } return false; } /* Convert lexicon file to a dictionary */ public function make_lex_dict() { $lex_dict = []; $fp = fopen($this->lexicon_file, "r"); if (!$fp) { die("Cannot load lexicon file"); } while (($line = fgets($fp, 4096)) !== false) { list($word, $measure) = explode("\t", trim($line)); //.strip().split('\t')[0:2] $lex_dict[$word] = $measure; //lex_dict[word] = float(measure) } return $lex_dict; } public function make_emoji_dict() { $emoji_dict = []; $fp = fopen($this->emoji_lexicon, "r"); if (!$fp) { die("Cannot load emoji lexicon file"); } while (($line = fgets($fp, 4096)) !== false) { list($emoji, $description) = explode("\t", trim($line)); //.strip().split('\t')[0:2] $emoji_dict[$emoji] = $description; //lex_dict[word] = float(measure) } return $emoji_dict; } public function updateLexicon($arr) { if(!is_array($arr)) return []; $lexicon = []; foreach ($arr as $word => $valence) { $this->lexicon[strtolower($word)] = is_numeric($valence)? $valence : 0; } } private function IsKindOf($firstWord, $secondWord) { return "kind" === strtolower($firstWord) && "of" === strtolower($secondWord); } private function IsBoosterWord($word) { return array_key_exists(strtolower($word), Config::BOOSTER_DICT); } private function getBoosterScaler($word) { return Config::BOOSTER_DICT[strtolower($word)]; } private function IsInLexicon($word) { $lowercase = strtolower($word); return array_key_exists($lowercase, $this->lexicon); } private function IsUpperCaseWord($word) { return ctype_upper($word); } private function getValenceFromLexicon($word) { return $this->lexicon[strtolower($word)]; } private function getTargetWordFromContext($wordInContext) { return $wordInContext[count($wordInContext)-1]; } /* Gets the precedding two words to check for emphasis */ private function getWordInContext($wordList, $currentWordPosition) { $precedingWordList =[]; //push the actual word on to the context list array_unshift($precedingWordList, $wordList[$currentWordPosition]); //If the word position is greater than 2 then we know we are not going to overflow if (($currentWordPosition-1)>=0) { array_unshift($precedingWordList, $wordList[$currentWordPosition-1]); } else { array_unshift($precedingWordList, ""); } if (($currentWordPosition-2)>=0) { array_unshift($precedingWordList, $wordList[$currentWordPosition-2]); } else { array_unshift($precedingWordList, ""); } if (($currentWordPosition-3)>=0) { array_unshift($precedingWordList, $wordList[$currentWordPosition-3]); } else { array_unshift($precedingWordList, ""); } return $precedingWordList; } /* Return a float for sentiment strength based on the input text. Positive values are positive valence, negative value are negative valence. */ public function getSentiment($text) { $text_no_emoji = ''; $prev_space = true; foreach($this->str_split_unicode($text) as $unichr ) { if (array_key_exists($unichr, $this->emojis)) { $description = $this->emojis[$unichr]; if (!($prev_space)) { $text_no_emoji .= ' '; } $text_no_emoji .= $description; $prev_space = false; } else { $text_no_emoji .= $unichr; $prev_space = ($unichr == ' '); } } $text = trim($text_no_emoji); $this->current_sentitext = new SentiText($text); $sentiments = []; $words_and_emoticons = $this->current_sentitext->words_and_emoticons; for ($i=0; $i<=count($words_and_emoticons)-1; $i++) { $valence = 0.0; $wordBeingTested = $words_and_emoticons[$i]; //If this is a booster word add a 0 valances then go to next word as it does not express sentiment directly /* if ($this->IsBoosterWord($wordBeingTested)){ echo "\t\tThe word is a booster word: setting sentiment to 0.0\n"; }*/ //var_dump($i); //If the word is not in the Lexicon then it does not express sentiment. So just ignore it. if ($this->IsInLexicon($wordBeingTested)) { //Special case because kind is in the lexicon so the modifier kind of needs to be skipped if ("kind" !=$words_and_emoticons[$i] && "of" != $words_and_emoticons[$i]) { $valence = $this->getValenceFromLexicon($wordBeingTested); $wordInContext = $this->getWordInContext($words_and_emoticons, $i); //If we are here then we have a word that enhance booster words $valence = $this->adjustBoosterSentiment($wordInContext, $valence); } } array_push($sentiments, $valence); } //Once we have a sentiment for each word adjust the sentimest if but is present $sentiments = $this->_but_check($words_and_emoticons, $sentiments); return $this->score_valence($sentiments, $text); } private function str_split_unicode($str, $l = 0) { if ($l > 0) { $ret = array(); $len = mb_strlen($str, "UTF-8"); for ($i = 0; $i < $len; $i += $l) { $ret[] = mb_substr($str, $i, $l, "UTF-8"); } return $ret; } return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY); } private function applyValenceCapsBoost($targetWord, $valence) { if ($this->IsUpperCaseWord($targetWord) && $this->current_sentitext->is_cap_diff) { if ($valence > 0) { $valence += Config::C_INCR; } else { $valence -= Config::C_INCR; } } return $valence; } /* Check if the preceding words increase, decrease, or negate/nullify the valence */ private function boosterScaleAdjustment($word, $valence) { $scalar = 0.0; if (!$this->IsBoosterWord($word)) { return $scalar; } $scalar = $this->getBoosterScaler($word); if ($valence < 0) { $scalar *= -1; } //check if booster/dampener word is in ALLCAPS (while others aren't) $scalar = $this->applyValenceCapsBoost($word, $scalar); return $scalar; } // dampen the scalar modifier of preceding words and emoticons // (excluding the ones that immediately preceed the item) based // on their distance from the current item. private function dampendBoosterScalerByPosition($booster, $position) { if (0===$booster) { return $booster; } if (1==$position) { return $booster*0.95; } if (2==$position) { return $booster*0.9; } return $booster; } private function adjustBoosterSentiment($wordInContext, $valence) { //The target word is always the last word $targetWord = $this->getTargetWordFromContext($wordInContext); //check if sentiment laden word is in ALL CAPS (while others aren't) and apply booster $valence = $this->applyValenceCapsBoost($targetWord, $valence); $valence = $this->modifyValenceBasedOnContext($wordInContext, $valence); return $valence; } private function modifyValenceBasedOnContext($wordInContext, $valence) { $wordToTest = $this->getTargetWordFromContext($wordInContext); //if($this->IsInLexicon($wordToTest)){ // continue; //} for ($i=0; $i<count($wordInContext)-1; $i++) { $scalarValue = $this->boosterScaleAdjustment($wordInContext[$i], $valence); $scalarValue = $this->dampendBoosterScalerByPosition($scalarValue, $i); $valence = $valence+$scalarValue; } $valence = $this->_never_check($wordInContext, $valence); $valence = $this->_idioms_check($wordInContext, $valence); // future work: consider other sentiment-laden idioms // other_idioms = // {"back handed": -2, "blow smoke": -2, "blowing smoke": -2, // "upper hand": 1, "break a leg": 2, // "cooking with gas": 2, "in the black": 2, "in the red": -2, // "on the ball": 2,"under the weather": -2} $valence = $this->_least_check($wordInContext, $valence); return $valence; } public function _least_check($wordInContext, $valence) { // check for negation case using "least" //if the previous word is least" if (strtolower($wordInContext[2]) == "least") { //but not "at least {word}" "very least {word}" if (strtolower($wordInContext[1]) != "at" && strtolower($wordInContext[1]) != "very") { $valence = $valence*Config::N_SCALAR; } } return $valence; } public function _but_check($words_and_emoticons, $sentiments) { // check for modification in sentiment due to contrastive conjunction 'but' $bi = array_search("but", $words_and_emoticons); if (!$bi) { $bi = array_search("BUT", $words_and_emoticons); } if ($bi) { for ($si=0; $si<count($sentiments); $si++) { if ($si<$bi) { $sentiments[$si] = $sentiments[$si]*0.5; } else if ($si>$bi) { $sentiments[$si] = $sentiments[$si]*1.5; } } } return $sentiments; } public function _idioms_check($wordInContext, $valence) { $onezero = sprintf("%s %s", $wordInContext[2], $wordInContext[3]); $twoonezero = sprintf("%s %s %s", $wordInContext[1], $wordInContext[2], $wordInContext[3]); $twoone = sprintf("%s %s", $wordInContext[1], $wordInContext[2]); $threetwoone = sprintf("%s %s %s", $wordInContext[0], $wordInContext[1], $wordInContext[2]); $threetwo = sprintf("%s %s", $wordInContext[0], $wordInContext[1]); $zeroone = sprintf("%s %s", $wordInContext[3], $wordInContext[2]); $zeroonetwo = sprintf("%s %s %s", $wordInContext[3], $wordInContext[2], $wordInContext[1]); $sequences = [$onezero, $twoonezero, $twoone, $threetwoone, $threetwo]; foreach ($sequences as $seq) { $key = strtolower($seq); if (array_key_exists($key, Config::SPECIAL_CASE_IDIOMS)) { $valence = Config::SPECIAL_CASE_IDIOMS[$key]; break; } /* Positive idioms check. Not implementing it yet if(count($words_and_emoticons)-1 > $i){ $zeroone = sprintf("%s %s",$words_and_emoticons[$i], $words_and_emoticons[$i+1]); if (in_array($zeroone, Config::SPECIAL_CASE_IDIOMS)){ $valence = Config::SPECIAL_CASE_IDIOMS[$zeroone]; } } if(count($words_and_emoticons)-1 > $i+1){ $zeroonetwo = sprintf("%s %s %s",$words_and_emoticons[$i], $words_and_emoticons[$i+1], $words_and_emoticons[$i+2]); if (in_array($zeroonetwo, Config::SPECIAL_CASE_IDIOMS)){ $valence = Config::SPECIAL_CASE_IDIOMS[$zeroonetwo]; } } */ // check for booster/dampener bi-grams such as 'sort of' or 'kind of' if ($this->IsBoosterWord($threetwo) || $this->IsBoosterWord($twoone)) { $valence = $valence+Config::B_DECR; } } return $valence; } public function _never_check($wordInContext, $valance) { //If the sentiment word is preceded by never so/this we apply a modifier $neverModifier = 0; if ("never" == $wordInContext[0]) { $neverModifier = 1.25; } else if ("never" == $wordInContext[1]) { $neverModifier = 1.5; } if ("so" == $wordInContext[1] || "so"== $wordInContext[2] || "this" == $wordInContext[1] || "this" == $wordInContext[2]) { $valance *= $neverModifier; } //if any of the words in context are negated words apply negative scaler foreach ($wordInContext as $wordToCheck) { if ($this->IsNegated($wordToCheck)) { $valance *= Config::B_DECR; } } return $valance; } public function _sentiment_laden_idioms_check($valence, $senti_text_lower){ # Future Work # check for sentiment laden idioms that don't contain a lexicon word $idioms_valences = []; foreach (Config::SENTIMENT_LADEN_IDIOMS as $idiom) { if(in_array($idiom, $senti_text_lower)){ //print($idiom, $senti_text_lower) $valence = Config::SENTIMENT_LADEN_IDIOMS[$idiom]; $idioms_valences[] = $valence; } } if ((strlen($idioms_valences) > 0)) { $valence = ( array_sum( explode( ',', $idioms_valences ) ) / floatval(strlen($idioms_valences))); } return $valence; } public function _punctuation_emphasis($sum_s, $text) { // add emphasis from exclamation points and question marks $ep_amplifier = $this->_amplify_ep($text); $qm_amplifier = $this->_amplify_qm($text); $punct_emph_amplifier = $ep_amplifier+$qm_amplifier; return $punct_emph_amplifier; } public function _amplify_ep($text) { // check for added emphasis resulting from exclamation points (up to 4 of them) $ep_count = substr_count($text, "!"); if ($ep_count > 4) { $ep_count = 4; } # (empirically derived mean sentiment intensity rating increase for # exclamation points) $ep_amplifier = $ep_count*0.292; return $ep_amplifier; } public function _amplify_qm($text) { # check for added emphasis resulting from question marks (2 or 3+) $qm_count = substr_count($text, "?"); $qm_amplifier = 0; if ($qm_count > 1) { if ($qm_count <= 3) { # (empirically derived mean sentiment intensity rating increase for # question marks) $qm_amplifier = $qm_count*0.18; } else { $qm_amplifier = 0.96; } } return $qm_amplifier; } public function _sift_sentiment_scores($sentiments) { # want separate positive versus negative sentiment scores $pos_sum = 0.0; $neg_sum = 0.0; $neu_count = 0; foreach ($sentiments as $sentiment_score) { if ($sentiment_score > 0) { $pos_sum += $sentiment_score +1; # compensates for neutral words that are counted as 1 } if ($sentiment_score < 0) { $neg_sum += $sentiment_score -1; # when used with math.fabs(), compensates for neutrals } if ($sentiment_score == 0) { $neu_count += 1; } } return [$pos_sum, $neg_sum, $neu_count]; } public function score_valence($sentiments, $text) { if ($sentiments) { $sum_s = array_sum($sentiments); # compute and add emphasis from punctuation in text $punct_emph_amplifier = $this->_punctuation_emphasis($sum_s, $text); if ($sum_s > 0) { $sum_s += $punct_emph_amplifier; } elseif ($sum_s < 0) { $sum_s -= $punct_emph_amplifier; } $compound = Config::normalize($sum_s); # discriminate between positive, negative and neutral sentiment scores list($pos_sum, $neg_sum, $neu_count) = $this->_sift_sentiment_scores($sentiments); if ($pos_sum > abs($neg_sum)) { $pos_sum += $punct_emph_amplifier; } elseif ($pos_sum < abs($neg_sum)) { $neg_sum -= $punct_emph_amplifier; } $total = $pos_sum + abs($neg_sum) + $neu_count; $pos =abs($pos_sum / $total); $neg = abs($neg_sum / $total); $neu = abs($neu_count / $total); } else { $compound = 0.0; $pos = 0.0; $neg = 0.0; $neu = 0.0; } $sentiment_dict = ["neg" => round($neg, 3), "neu" => round($neu, 3), "pos" => round($pos, 3), "compound" => round($compound, 4)]; return $sentiment_dict; } }
php
MIT
b8bdc463643a9093e1cbf9b01de2fd7cddd27f24
2026-01-05T04:56:11.759318Z
false
davmixcool/php-sentiment-analyzer
https://github.com/davmixcool/php-sentiment-analyzer/blob/b8bdc463643a9093e1cbf9b01de2fd7cddd27f24/src/Config/Config.php
src/Config/Config.php
<?php namespace Sentiment\Config; /** * Class Config. */ class Config { // (empirically derived mean sentiment intensity rating increase for booster words) const B_INCR = 0.293; const B_DECR = -0.293; // (empirically derived mean sentiment intensity rating increase for using // ALLCAPs to emphasize a word) const C_INCR = 0.733; const N_SCALAR = -0.74; // for removing punctuation //const REGEX_REMOVE_PUNCTUATION = re.compile('[%s]' % re.escape(string.punctuation)) const NEGATE = ["aint", "arent", "cannot", "cant", "couldnt", "darent", "didnt", "doesnt", "ain't", "aren't", "can't", "couldn't", "daren't", "didn't", "doesn't", "dont", "hadnt", "hasnt", "havent", "isnt", "mightnt", "mustnt", "neither", "don't", "hadn't", "hasn't", "haven't", "isn't", "mightn't", "mustn't", "neednt", "needn't", "never", "none", "nope", "nor", "not", "nothing", "nowhere", "oughtnt", "shant", "shouldnt", "uhuh", "wasnt", "werent", "oughtn't", "shan't", "shouldn't", "uh-uh", "wasn't", "weren't", "without", "wont", "wouldnt", "won't", "wouldn't", "rarely", "seldom", "despite"]; //booster/dampener 'intensifiers' or 'degree adverbs' //http://en.wiktionary.org/wiki/Category:English_degree_adverbs const BOOSTER_DICT = ["absolutely"=> self::B_INCR, "amazingly"=> self::B_INCR, "awfully"=> self::B_INCR, "completely"=> self::B_INCR, "considerably"=> self::B_INCR, "decidedly"=> self::B_INCR, "deeply"=> self::B_INCR, "effing"=> self::B_INCR,"enormous"=> self::B_INCR, "enormously"=> self::B_INCR, "entirely"=> self::B_INCR, "especially"=> self::B_INCR, "exceptionally"=> self::B_INCR, "extremely"=> self::B_INCR, "fabulously"=> self::B_INCR, "flipping"=> self::B_INCR, "flippin"=> self::B_INCR, "fricking"=> self::B_INCR, "frickin"=> self::B_INCR, "frigging"=> self::B_INCR, "friggin"=> self::B_INCR, "fully"=> self::B_INCR, "fucking"=> self::B_INCR, "greatly"=> self::B_INCR, "hella"=> self::B_INCR, "highly"=> self::B_INCR, "hugely"=> self::B_INCR, "incredibly"=> self::B_INCR, "intensely"=> self::B_INCR, "majorly"=> self::B_INCR, "more"=> self::B_INCR, "most"=> self::B_INCR, "particularly"=> self::B_INCR, "purely"=> self::B_INCR, "quite"=> self::B_INCR, "seemingly" => self::B_INCR, "really"=> self::B_INCR, "remarkably"=> self::B_INCR, "so"=> self::B_INCR, "substantially"=> self::B_INCR, "thoroughly"=> self::B_INCR, "totally"=> self::B_INCR, "tremendous"=> self::B_INCR, "tremendously"=> self::B_INCR, "uber"=> self::B_INCR, "unbelievably"=> self::B_INCR, "unusually"=> self::B_INCR, "utterly"=> self::B_INCR, "very"=> self::B_INCR, "almost"=> self::B_DECR, "barely"=> self::B_DECR, "hardly"=> self::B_DECR, "just enough"=> self::B_DECR, "kind of"=> self::B_DECR, "kinda"=> self::B_DECR, "kindof"=> self::B_DECR, "kind-of"=> self::B_DECR, "less"=> self::B_DECR, "little"=> self::B_DECR, "marginally"=> self::B_DECR, "occasional"=> self::B_DECR, "occasionally"=> self::B_DECR, "partly"=> self::B_DECR, "scarcely"=> self::B_DECR, "slightly"=> self::B_DECR, "somewhat"=> self::B_DECR, "sort of"=> self::B_DECR, "sorta"=> self::B_DECR, "sortof"=> self::B_DECR, "sort-of"=> self::B_DECR]; # check for sentiment laden idioms that do not contain lexicon words (future work, not yet implemented) const SENTIMENT_LADEN_IDIOMS = ["cut the mustard"=> 2, "hand to mouth"=> -2, "back handed"=> -2, "blow smoke"=> -2, "blowing smoke"=> -2, "upper hand"=> 1, "break a leg"=> 2, "cooking with gas"=> 2, "in the black"=> 2, "in the red"=> -2, "on the ball"=> 2, "under the weather"=> -2]; // check for special case idioms using a sentiment-laden keyword known to SAGE const SPECIAL_CASE_IDIOMS = ["the shit"=> 3, "the bomb"=> 3, "bad ass"=> 1.5, "bus stop"=> 0.0, "yeah right"=> -2, "cut the mustard"=> 2, "kiss of death"=> -1.5, "hand to mouth"=> -2, "beating heart"=> 3.1,"broken heart"=> -2.9, "to die for"=> 3]; ##Static methods## /* Normalize the score to be between -1 and 1 using an alpha that approximates the max expected value */ public static function normalize($score, $alpha = 15) { $norm_score = $score/sqrt(($score*$score) + $alpha); return $norm_score; } }
php
MIT
b8bdc463643a9093e1cbf9b01de2fd7cddd27f24
2026-01-05T04:56:11.759318Z
false
davmixcool/php-sentiment-analyzer
https://github.com/davmixcool/php-sentiment-analyzer/blob/b8bdc463643a9093e1cbf9b01de2fd7cddd27f24/src/Procedures/SentiText.php
src/Procedures/SentiText.php
<?php namespace Sentiment\Procedures; /* Identify sentiment-relevant string-level properties of input text. */ class SentiText { private $text = ""; public $words_and_emoticons = null; public $is_cap_diff = null; const PUNC_LIST = [".", "!", "?", ",", ";", ":", "-", "'", "\"", "!!", "!!!", "??", "???", "?!?", "!?!", "?!?!", "!?!?"]; function __construct($text) { //checking that is string //if (!isinstance(text, str)){ // text = str(text.encode('utf-8')); //} $this->text = $text; $this->words_and_emoticons = $this->_words_and_emoticons(); // doesn't separate words from\ // adjacent punctuation (keeps emoticons & contractions) $this->is_cap_diff = $this->allcap_differential($this->words_and_emoticons); } /* Remove all punctation from a string */ function strip_punctuation($string) { //$string = strtolower($string); return preg_replace("/[[:punct:]]+/", "", $string); } function array_count_values_of($haystack, $needle) { if (!in_array($needle, $haystack, true)) { return 0; } $counts = array_count_values($haystack); return $counts[$needle]; } /* Check whether just some words in the input are ALL CAPS :param list words: The words to inspect :returns: `True` if some but not all items in `words` are ALL CAPS */ private function allcap_differential($words) { $is_different = false; $allcap_words = 0; foreach ($words as $word) { //ctype is affected by the local of the processor see manual for more details if (ctype_upper($word)) { $allcap_words += 1; } } $cap_differential = count($words) - $allcap_words; if ($cap_differential > 0 && $cap_differential < count($words)) { $is_different = true; } return $is_different; } function _words_only() { $text_mod = $this->strip_punctuation($this->text); // removes punctuation (but loses emoticons & contractions) $words_only = preg_split('/\s+/', $text_mod); # get rid of empty items or single letter "words" like 'a' and 'I' $works_only = array_filter($words_only, function ($word) { return strlen($word) > 1; }); return $words_only; } function _words_and_emoticons() { $wes = preg_split('/\s+/', $this->text); # get rid of residual empty items or single letter words $wes = array_filter($wes, function ($word) { return strlen($word) > 1; }); //Need to remap the indexes of the array $wes = array_values($wes); $words_only = $this->_words_only(); foreach ($words_only as $word) { foreach (self::PUNC_LIST as $punct) { //replace all punct + word combinations with word $pword = $punct .$word; $x1 = $this->array_count_values_of($wes, $pword); while ($x1 > 0) { $i = array_search($pword, $wes, true); unset($wes[$i]); array_splice($wes, $i, 0, $word); $x1 = $this->array_count_values_of($wes, $pword); } //Do the same as above but word then punct $wordp = $word . $punct; $x2 = $this->array_count_values_of($wes, $wordp); while ($x2 > 0) { $i = array_search($wordp, $wes, true); unset($wes[$i]); array_splice($wes, $i, 0, $word); $x2 = $this->array_count_values_of($wes, $wordp); } } } return $wes; } }
php
MIT
b8bdc463643a9093e1cbf9b01de2fd7cddd27f24
2026-01-05T04:56:11.759318Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/LogToDbCustomLoggingHandler.php
src/LogToDbCustomLoggingHandler.php
<?php namespace danielme85\LaravelLogToDB; use danielme85\LaravelLogToDB\Models\DBLogException; use Monolog\Formatter\LineFormatter; use Monolog\Handler\AbstractProcessingHandler; use Monolog\Handler\ErrorLogHandler; use Monolog\LogRecord; /** * Class LogToDbHandler * * @package danielme85\LaravelLogToDB */ class LogToDbCustomLoggingHandler extends AbstractProcessingHandler { /** * Logging configuration * * @var array */ private $config; /** * LogToDbHandler constructor. * * @param array $config Logging configuration from logging.php * @param array $processors collection of log processors * @param bool $bubble Whether the messages that are handled can bubble up the stack or not */ function __construct(array $config, array $processors, bool $bubble = true) { $this->config = $config; //Set default level debug $level = $config['level'] ?? 'debug'; //Set the processors if (!empty($processors)) { foreach ($processors as $processor) { $this->pushProcessor($processor); } } parent::__construct($level, $bubble); } /** * Write the Log * * @param \Monolog\LogRecord $record * @throws DBLogException */ protected function write(LogRecord $record): void { try { $log = new LogToDB($this->config); $log->newFromMonolog($record); } catch (\Exception $e) { LogToDB::emergencyLog(new LogRecord( datetime: new \Monolog\DateTimeImmutable(true), channel: '', level: \Monolog\Level::Critical, message: 'There was an error while trying to write the log to a DB, log record pushed to error_log()', context: LogToDB::parseIfException(['exception' => $e]), extra: [] )); LogToDB::emergencyLog($record); } } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/LogToDB.php
src/LogToDB.php
<?php namespace danielme85\LaravelLogToDB; use danielme85\LaravelLogToDB\Jobs\SaveNewLogEvent; use danielme85\LaravelLogToDB\Models\DBLog; use danielme85\LaravelLogToDB\Models\DBLogMongoDB; use Monolog\Formatter\LineFormatter; use Monolog\Handler\ErrorLogHandler; use Monolog\LogRecord; /** * Class LogToDb * * @package danielme85\LaravelLogToDB */ class LogToDB { /** * Connection reference in databases config. * @var string */ public $connection; /** * @var string */ public $collection; /** * The DB config details * @var null */ public $database; /** * @var string */ protected $model; /** * @var array */ protected $config; /** * LogToDB constructor. * * @param array $loggingConfig config values;. */ function __construct($loggingConfig = []) { //Log default config if present $this->config = $loggingConfig + (config('logtodb') ?? []); $this->collection = $this->config['collection'] ?? 'log'; $this->model = $this->config['model'] ?? null; //Get the DB connections $dbconfig = config('database.connections'); if (!empty($this->config['connection'])) { if (!empty($dbconfig[$this->config['connection']])) { $this->connection = $this->config['connection']; } } //set the actual connection instead of default if ($this->connection === 'default' or empty($this->connection)) { $this->connection = config('database.default'); } if (isset($dbconfig[$this->connection])) { $this->database = $dbconfig[$this->connection]; } } /** * Return a new LogToDB Module instance. * * If specifying 'channel, 'connection' and 'collection' would not be needed (they will be extracted from channel). * If specifying 'connection' and 'collection', 'channel' is not needed. * * @param string|null $channel * @param string|null $connection * @param string|null $collection * * @return DBLog|DBLogMongoDB */ public static function model(?string $channel = null, string $connection = 'default', ?string $collection = null) { $conn = null; $coll = null; if (!empty($channel)) { $channels = config('logging.channels'); if (!empty($channels[$channel])) { if (!empty($channels[$channel]['connection'])) { $conn = $channels[$channel]['connection']; } if (!empty($channels[$channel]['collection'])) { $coll = $channels[$channel]['collection']; } } } else { $conn = $connection; if (!empty($collection)) { $coll = $collection; } } //Return new instance of this model $model = new self(['connection' => $conn, 'collection' => $coll]); return $model->getModel(); } /** * @return DBLogMongoDB | DBLog; */ public function getModel() { //Use custom model if (!empty($this->model)) { return new $this->model; } else if (isset($this->database['driver']) && $this->database['driver'] === 'mongodb') { //MongoDB has its own Model $mongo = new DBLogMongoDB(); $mongo->bind($this->connection, $this->collection); return $mongo; } else { //Use the default Laravel Eloquent Model $sql = new DBLog(); $sql->bind($this->connection, $this->collection); return $sql; } } /** * Create a Eloquent Model * * @param \Monolog\LogRecord $record * @return bool success */ public function newFromMonolog(LogRecord $record) { $detailed = $this->getConfig('detailed'); if (!empty($this->connection)) { if ($detailed && !empty($record['context']) && !empty($record['context']['exception'])) { $record = new LogRecord( $record->datetime, $record->channel, $record->level, $record->message, self::parseIfException($record->context, true), $record->extra ); } else if (!$detailed) { $record = new LogRecord( $record->datetime, $record->channel, $record->level, $record->message, [], $record->extra ); } if (!empty($this->config['queue'])) { if (empty($this->config['queue_name']) && empty($this->config['queue_connection'])) { dispatch(new SaveNewLogEvent($record)); } else if (!empty($this->config['queue_name']) && !empty($this->config['queue_connection'])) { dispatch(new SaveNewLogEvent($record)) ->onConnection($this->config['queue_connection']) ->onQueue($this->config['queue_name']); } else if (!empty($this->config['queue_connection'])) { dispatch(new SaveNewLogEvent($record)) ->onConnection($this->config['queue_connection']); } else if (!empty($this->config['queue_name'])) { dispatch(new SaveNewLogEvent($record)) ->onQueue($this->config['queue_name']); } } else { $this->safeWrite($record); return true; } } return false; } public function safeWrite(LogRecord $record) { try { $model = $this->getModel(); $log = $model->generate( $record ); $log->save(); } catch (\Throwable $e) { self::emergencyLog(new LogRecord( datetime: new \Monolog\DateTimeImmutable(true), channel: '', level: \Monolog\Level::Critical, message: 'There was an error while trying to write the log to a DB, log record pushed to error_log()', context: LogToDB::parseIfException(['exception' => $e]), extra: [] )); self::emergencyLog($record); } } public static function emergencyLog(LogRecord $record) { $errorHandler = new ErrorLogHandler(); $errorHandler->setFormatter(new LineFormatter('%level_name%: %message% %context%')); $errorHandler->handle($record); } /** * Get config value * * @param string $config * @return mixed|null */ public function getConfig(string $config) { return $this->config[$config] ?? null; } /** * Parse the exception class * * @param array $context * @param bool $trace * @return array */ public static function parseIfException(array $context, bool $trace = false) { if (!empty($context['exception'])) { $exception = $context['exception']; if (is_object($exception)) { if (get_class($exception) === \Exception::class || get_class($exception) === \Throwable::class || is_subclass_of($exception, \Exception::class) || is_subclass_of($exception, \Throwable::class) || strpos(get_class($exception), "Exception") !== false || strpos(get_class($exception), "Throwable") !== false) { $newexception = []; if (method_exists($exception, 'getMessage')) { $newexception['message'] = $exception->getMessage(); } if (method_exists($exception, 'getCode')) { $newexception['code'] = $exception->getCode(); } if (method_exists($exception, 'getFile')) { $newexception['file'] = $exception->getFile(); } if (method_exists($exception, 'getLine')) { $newexception['line'] = $exception->getLine(); } if ($trace && method_exists($exception, 'getTraceAsString')) { $newexception['trace'] = $exception->getTraceAsString(); } if (method_exists($exception, 'getSeverity')) { $newexception['severity'] = $exception->getSeverity(); } $context['exception'] = $newexception; } } } return $context; } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/LogToDbHandler.php
src/LogToDbHandler.php
<?php namespace danielme85\LaravelLogToDB; use Monolog\Logger; /** * Class LogToDbHandler * * @package danielme85\LaravelLogToDB */ class LogToDbHandler { /** * Create a custom Monolog instance. * * @param array $config * @return \Monolog\Logger */ public function __invoke(array $config) { $processors = []; if (isset($config['processors']) && !empty($config['processors']) && is_array($config['processors'])) { foreach ($config['processors'] as $processorName) { if (class_exists($processorName)) { $processors[] = new $processorName; } } } return new Logger($config['name'] ?? 'LogToDB', [ new LogToDbCustomLoggingHandler($config, $processors) ], $processors ); } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/ServiceProvider.php
src/ServiceProvider.php
<?php namespace danielme85\LaravelLogToDB; use danielme85\LaravelLogToDB\Commands\LogCleanerUpper; use Illuminate\Support\ServiceProvider as Provider; /** * Class ServiceProvider * * @package danielme85\LaravelLogToDB */ class ServiceProvider extends Provider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application services. * * @return void */ public function boot() { //config path is missing in Lumen //https://gist.github.com/mabasic/21d13eab12462e596120 if (!function_exists('config_path') && !function_exists('danielme85\LaravelLogToDB\config_path')) { function config_path($path = '') { return app()->basePath() . '/config' . ($path ? '/' . $path : $path); } } //Merge config first, then keep a publish option $this->mergeConfigFrom(__DIR__.'/config/logtodb.php', 'logtodb'); $this->publishes([ __DIR__.'/config/logtodb.php' => config_path('logtodb.php'), ], 'config'); //Publish the migration $this->publishes([ __DIR__.'/migrations/' => database_path('migrations') ], 'migrations'); if ($this->app->runningInConsole()) { $this->commands([ LogCleanerUpper::class, ]); } } /** * Register the application services. * * @return void */ public function register() { $this->app->bind('laravel-log-to-db', function() { return new LogToDB(); }); } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/Jobs/SaveNewLogEvent.php
src/Jobs/SaveNewLogEvent.php
<?php namespace danielme85\LaravelLogToDB\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Monolog\LogRecord; class SaveNewLogEvent implements ShouldQueue { use InteractsWithQueue, Queueable; /** * Create a new job instance. * * @param \Monolog\LogRecord $record * @return void */ public function __construct(protected LogRecord $record) { } /** * Execute the job. * * @return void */ public function handle() { app('laravel-log-to-db')->safeWrite($this->record); } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/Processors/AuthenticatedUserProcessor.php
src/Processors/AuthenticatedUserProcessor.php
<?php namespace danielme85\LaravelLogToDB\Processors; use Illuminate\Support\Facades\Auth; use Monolog\Processor\ProcessorInterface; class AuthenticatedUserProcessor implements ProcessorInterface { /** * @return array The processed record */ public function __invoke(array $record) { $record['extra']['user'] = Auth::user(); return $record; } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/Processors/PhpVersionProcessor.php
src/Processors/PhpVersionProcessor.php
<?php namespace danielme85\LaravelLogToDB\Processors; use Monolog\LogRecord; use Monolog\Processor\ProcessorInterface; /** * Class PhpVersionProcessor * @package danielme85\LaravelLogToDB\Processors */ class PhpVersionProcessor implements ProcessorInterface { /** * @return \Monolog\LogRecord The processed record */ public function __invoke(LogRecord $record) { $record['extra']['php_version'] = phpversion(); return $record; } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/migrations/2018_08_11_003343_create_log_table.php
src/migrations/2018_08_11_003343_create_log_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateLogTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (Schema::connection(config('logtodb.connection'))->hasTable(config('logtodb.collection')) === false) { Schema::connection(config('logtodb.connection'))->create(config('logtodb.collection'), function (Blueprint $table) { $table->increments('id'); $table->text('message')->nullable(); $table->string('channel')->nullable(); $table->integer('level')->default(0); $table->string('level_name', 20); $table->integer('unix_time'); $table->string('datetime')->nullable(); $table->longText('context')->nullable(); $table->text('extra')->nullable(); $table->timestamps(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::connection(config('logtodb.connection'))->dropIfExists(config('logtodb.collection')); } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/Facades/LogToDB.php
src/Facades/LogToDB.php
<?php namespace danielme85\LaravelLogToDB\Facades; use Illuminate\Support\Facades\Facade; class LogToDB extends Facade { /** * @return string */ protected static function getFacadeAccessor() { return 'laravel-log-to-db'; } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/Models/DBLog.php
src/Models/DBLog.php
<?php namespace danielme85\LaravelLogToDB\Models; use Illuminate\Database\Eloquent\Model; /** * Class DbLog * * @package danielme85\LaravelLogToDB */ class DBLog extends Model { use LogToDbCreateObject; use BindsDynamically; }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/Models/LogToDbCreateObject.php
src/Models/LogToDbCreateObject.php
<?php namespace danielme85\LaravelLogToDB\Models; use Monolog\LogRecord; /** * Trait LogToDbCreateObject * * @package danielme85\LaravelLogToDB */ trait LogToDbCreateObject { /** * Create a new log object * * @param \Monolog\LogRecord $record * * @return mixed */ public function generate(LogRecord $record) { $this->message = $record->message; $this->context = $record->context; $this->level = $record->level->value; $this->level_name = $record->level->getName(); $this->channel = $record->channel; $this->datetime = $record->datetime; $this->extra = $record->extra; $this->unix_time = time(); return $this; } /** * Context Accessor * * @param $value * @return null|array */ public function getContextAttribute($value) { return $this->jsonDecodeIfNotEmpty($value); } /** * Extra Accessor * * @param $value * @return null|array */ public function getExtraAttribute($value) { return $this->jsonDecodeIfNotEmpty($value); } /** * DateTime Mutator * * @param object $value */ public function setDatetimeAttribute(object $value) { $this->attributes['datetime'] = $value->format(config('logtodb.datetime_format')); } /** * Context Mutator * * @param array $value */ public function setContextAttribute($value) { $this->attributes['context'] = $this->jsonEncodeIfNotEmpty($value); } /** * Extra Mutator * * @param array $value */ public function setExtraAttribute($value) { $this->attributes['extra'] = $this->jsonEncodeIfNotEmpty($value); } /** * Encode to json if not empty/null * * @param $value * @return string */ private function jsonEncodeIfNotEmpty($value) { if (!empty($value)) { return @json_encode($value) ?? null; } } /** * Decode from json if not empty/null * * @param $value * @param bool $arraymode * @return mixed */ private function jsonDecodeIfNotEmpty($value, $arraymode = true) { if (!empty($value)) { return json_decode($value, $arraymode); } return $value; } /** * Delete the oldest records based on unix_time, silly spelling version. * * @param int $max amount of records to keep * @return bool */ public function removeOldestIfMoreThen(int $max) { return $this->removeOldestIfMoreThan($max); } /** * Delete the oldest records based on unix_time * * @param int $max amount of records to keep * @return bool success */ public function removeOldestIfMoreThan(int $max) { $current = $this->count(); if ($current > $max) { $keepers = $this->orderBy('unix_time', 'DESC')->take($max)->pluck($this->primaryKey)->toArray(); if ($this->whereNotIn($this->primaryKey, $keepers)->delete()) { return true; } } return false; } /** * Delete records based on date, silly spelling version. * * @param string $datetime date supported by strtotime: http://php.net/manual/en/function.strtotime.php * @return bool success */ public function removeOlderThen(string $datetime) { return $this->removeOlderThan($datetime); } /** * Delete records based on date. * * @param string $datetime date supported by strtotime: http://php.net/manual/en/function.strtotime.php * @return bool success */ public function removeOlderThan(string $datetime) { $unixtime = strtotime($datetime); $count = $this->where('unix_time', '<=', $unixtime)->delete(); return $count > 0; } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/Models/BindsDynamically.php
src/Models/BindsDynamically.php
<?php /** * Created by Daniel Mellum <mellum@gmail.com> * Date: 3/5/2019 * Time: 10:42 PM * * Source: https://stackoverflow.com/a/45914381 */ namespace danielme85\LaravelLogToDB\Models; trait BindsDynamically { protected $connection = null; protected $table = null; public function bind(string $connection, string $table) { $this->setConnection($connection); $this->setTable($table); } public function newInstance($attributes = [], $exists = false) { // Overridden in order to allow for late table binding. $model = parent::newInstance($attributes, $exists); $model->setTable($this->table); return $model; } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/Models/DBLogException.php
src/Models/DBLogException.php
<?php namespace danielme85\LaravelLogToDB\Models; /** * Class DBLogException * @package danielme85\LaravelLogToDB\Models */ class DBLogException extends \Exception { }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/Models/DBLogMongoDB.php
src/Models/DBLogMongoDB.php
<?php namespace danielme85\LaravelLogToDB\Models; use MongoDB\Laravel\Eloquent\Model as Eloquent; /** * Class DbLog * * @package danielme85\LaravelLogToDB */ class DBLogMongoDB extends Eloquent { use LogToDbCreateObject; use BindsDynamically; }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/Commands/LogCleanerUpper.php
src/Commands/LogCleanerUpper.php
<?php /** * Created by PhpStorm. * User: dmellum * Date: 2/2/20 * Time: 10:38 PM */ namespace danielme85\LaravelLogToDB\Commands; use Carbon\Carbon; use danielme85\LaravelLogToDB\LogToDbHandler; use danielme85\LaravelLogToDB\LogToDB; use Illuminate\Console\Command; class LogCleanerUpper extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'log:delete'; /** * The console command description. * * @var string */ protected $description = 'Cleanup/delete/prune/trim log records.'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * */ public function handle() { $config = config('logtodb'); $channels = $this->getLogToDbChannels(); if (!empty($channels)) { foreach ($channels as $name => $channel) { $maxRecords = $channel['max_records'] ?? $config['purge_log_when_max_records'] ?? false; $maxHours = $channel['max_hours'] ?? $config['purge_log_when_max_records'] ?? false; //delete based on numbers of records if (!empty($maxRecords) && $maxRecords > 0) { if (LogToDB::model($name)->removeOldestIfMoreThan($maxRecords)) { $this->warn("Deleted oldest records on log channel: {$name}, keep max number of records: {$maxRecords}"); } } //delete based on age if (!empty($maxHours) && $maxHours > 0) { $time = Carbon::now()->subHours($maxHours)->toDateTimeString(); if (LogToDB::model($name)->removeOlderThan($time)) { $this->warn("Deleted oldest records on log channel: {$name}, older than: {$time}"); } } } } } /** * @return array */ private function getLogToDbChannels() { $list = []; $logging = config('logging'); if (!empty($logging) && isset($logging['channels']) && !empty($logging['channels'])) { foreach ($logging['channels'] as $name => $channel) { //Only look for the relevant logging class in the config. if (isset($channel['via']) && $channel['via'] === LogToDbHandler::class) { $list[$name] = $channel; } } } return $list; } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/src/config/logtodb.php
src/config/logtodb.php
<?php /* |-------------------------------------------------------------------------- | Default Config for Laravel Log-To-DB |-------------------------------------------------------------------------- | | These settings are ONLY USED if they are not specified per channel | in the config/logging.php file. | */ return [ /* |-------------------------------------------------------------------------- | DB Connection |-------------------------------------------------------------------------- | | Set the default database connection to use. This is only used if no connection | is specified in config/logging.php. Matches connections in the config/database.php. | The default is: 'default', this will use whatever is default in the Laravel DB | config file. To use a different or separate connection set the connection name here. | Ex: 'connection' => 'mysql' wil use the connection 'mysql' in database.php. | Ex: 'connection' => 'mongodb' wil use the connection 'mongodb' in database.php* | | Supported connections should be same as Laravel since the Laravel DB/Eloquent | Supported DB engines as of this writing: [MySQL] [PostgreSQL] [SQLite] [SQL Server] | | *MongoDB is supported with: "jenssegers/laravel-mongodb". | https://github.com/jenssegers/laravel-mongodb | laravel-mongodb is required to use the mongodb option for logging. */ 'connection' => env('LOG_DB_CONNECTION', ''), /* |-------------------------------------------------------------------------- | DB Collection |-------------------------------------------------------------------------- | | Set the default database table (sql) or collection (mongodb) to use. */ 'collection' => env('LOG_DB_COLLECTION', 'log'), /* |-------------------------------------------------------------------------- | Detailed log |-------------------------------------------------------------------------- | | Set detailed log. Detailed log means the inclusion of a context (stack trace). | This will usually require quite a bit more DB storage space, and is probably | only useful in development/debugging. You can still have this enabled in production | environments if more detailed error logs are proffered. */ 'detailed' => env('LOG_DB_DETAILED', true), /* |-------------------------------------------------------------------------- | Model class |-------------------------------------------------------------------------- | | You can specify your own custom Eloquent model to be used when saving | and getting log events. */ 'model' => env('LOG_DB_MODEL', false), /* |-------------------------------------------------------------------------- | Enable Queue |-------------------------------------------------------------------------- | | It might be a good idea to save log events with the queue helper. | This way the requests going to your sever does not have to wait for the Log | event to be saved. */ 'queue' => env('LOG_DB_QUEUE', false), /* |-------------------------------------------------------------------------- | Name of Queue |-------------------------------------------------------------------------- | | Set to a string like: 'queue_db_name' => 'logWorker', | and make sure to run the queue worker. Leave empty for default queue. */ 'queue_name' => env('LOG_DB_QUEUE_NAME', ''), /* |-------------------------------------------------------------------------- | Queue Connection |-------------------------------------------------------------------------- | | If you are working with multiple queue connections, you may specify which | connection to push a job to. | This relates yto your queue settings in the config/queue.php file. | Leave blank to use the default connection. | */ 'queue_connection' => env('LOG_DB_QUEUE_CONNECTION', ''), /* |-------------------------------------------------------------------------- | Log record purging |-------------------------------------------------------------------------- | | Automatically purge db log records based on time and/or max number of records. | | Number of records: should be an integer that represents the max number of records | stored before the oldest is removed. | When older than: records older than a give number of hours will be removed. | */ 'max_records' => env('LOG_DB_MAX_COUNT', false), //Ex: 1000 records 'max_hours' => env('LOG_DB_MAX_HOURS', false), //Ex: 24 for 24 hours. Or 24*7 = 1 week. /* | | Specify the datetime format storing into the log record | */ 'datetime_format' => env('LOG_DB_DATETIME_FORMAT', 'Y-m-d H:i:s:ms') ];
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/tests/LogToDbTest.php
tests/LogToDbTest.php
<?php use danielme85\LaravelLogToDB\Jobs\SaveNewLogEvent; use danielme85\LaravelLogToDB\LogToDB; use danielme85\LaravelLogToDB\LogToDbHandler; use danielme85\LaravelLogToDB\Models\DBLogException; use danielme85\LaravelLogToDB\Processors\PhpVersionProcessor; use Dotenv\Dotenv; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Queue; use TestModels\CustomEloquentModel; use TestModels\LogMongo; use TestModels\LogSql; use Monolog\LogRecord; use Monolog\Processor\HostnameProcessor; use Monolog\Processor\MemoryUsageProcessor; use Orchestra\Testbench\TestCase; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; class LogToDbTest extends TestCase { /** * Setup the test environment. */ protected function setUp(): void { parent::setUp(); $this->loadMigrationsFrom(__DIR__.'/../src/migrations'); } /** * Define database migrations. * * @return void */ protected function defineDatabaseMigrations() { $this->artisan('migrate', ['--database' => 'mysql'])->run(); } /** * Define environment setup. * * @param \Illuminate\Foundation\Application $app * * @return void */ protected function defineEnvironment($app) { $dotenv = Dotenv::createImmutable(__DIR__.'/../', '.env.testing'); $dotenv->load(); $app['config']->set('database.default', 'mysql'); $app['config']->set('database.connections', ['mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', 3306), 'database' => env('DB_DATABASE', 'testing'), 'username' => env('DB_USERNAME', 'root'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', ], 'mongodb' => [ 'driver' => 'mongodb', 'host' => env('MDB_HOST', '127.0.0.1'), 'port' => env('MDB_PORT', 27017), 'database' => env('MDB_DATABASE', 'testing'), 'username' => env('MDB_USER', ''), 'password' => env('MDB_PASSWORD', ''), 'options' => [ 'database' => 'admin' // sets the authentication database required by mongo 3 ] ], ]); $app['config']->set('logging.default', 'stack'); $app['config']->set('logging.channels', [ 'stack' => [ 'driver' => 'stack', 'channels' => ['database', 'mongodb'], ], 'database' => [ 'driver' => 'custom', 'via' => LogToDbHandler::class, 'level' => 'debug', 'connection' => 'default', 'collection' => 'log', 'max_records' => 10, 'max_hours' => 1, 'processors' => [ HostnameProcessor::class, MemoryUsageProcessor::class, PhpVersionProcessor::class ] ], 'mongodb' => [ 'driver' => 'custom', 'via' => LogToDbHandler::class, 'level' => 'debug', 'connection' => 'mongodb', 'collection' => 'log', 'max_records' => 10, 'max_hours' => 1, 'processors' => [ HostnameProcessor::class ] ], 'limited' => [ 'driver' => 'custom', 'via' => LogToDbHandler::class, 'level' => 'warning', 'detailed' => false, 'max_records' => false, 'max_hours' => false, 'name' => 'limited', ] ]); $app['config']->set('logtodb', include __DIR__.'/../src/config/logtodb.php'); } /** * Get package providers. At a minimum this is the package being tested, but also * would include packages upon which our package depends, e.g. Cartalyst/Sentry * In a normal app environment these would be added to the 'providers' array in * the config/app.php8 file. * * @param \Illuminate\Foundation\Application $app * * @return array */ protected function getPackageProviders($app) { return [ \danielme85\LaravelLogToDB\ServiceProvider::class, \MongoDB\Laravel\MongoDBServiceProvider::class, ]; } /** * Basic test to see if class can be instanced. * * @group basic */ public function testClassInit() { $this->assertInstanceOf(LogToDB::class, app('laravel-log-to-db')); $this->assertInstanceOf(LogToDB::class, new LogToDB()); //Class works, now lets cleanup possible failed test LogToDB::model()->truncate(); LogToDB::model('mongodb')->truncate(); } /** * Run basic log levels * * @group basic */ public function testLogLevels() { Log::debug("This is an test DEBUG log event"); Log::info("This is an test INFO log event"); Log::notice("This is an test NOTICE log event"); Log::warning("This is an test WARNING log event"); Log::error("This is an test ERROR log event"); Log::critical("This is an test CRITICAL log event"); Log::alert("This is an test ALERT log event"); Log::emergency("This is an test EMERGENCY log event"); //Check mysql $logReader = LogToDB::model()->get()->toArray(); $logReaderMongoDB = LogToDB::model('mongodb')->get()->toArray(); $logReaderSpecific = LogToDB::model('database', 'mysql', 'LogSql')->get()->toArray(); $this->assertCount(8, $logReader); $this->assertCount(8, $logReaderMongoDB); $this->assertCount(8, $logReaderSpecific); } /** * @group context */ public function testContext() { Log::error("Im trying to add some context", ['whatDis?' => 'dis some context, should always be array']); $log = LogToDB::model()->where('message', '=' , 'Im trying to add some context')->first(); $this->assertNotEmpty($log); $this->assertStringContainsString("Im trying to add some context", $log->message); $this->assertIsArray($log->context); } /** * Check to see if processors are adding extra content. * * @group basic */ public function testProcessors() { Log::info("hello"); $log = LogToDB::model()->orderBy('created_at', 'desc')->first()->toArray(); $this->assertNotEmpty($log['extra']); $this->assertNotEmpty($log['extra']['memory_usage']); $this->assertNotEmpty($log['extra']['php_version']); $this->assertNotEmpty($log['extra']['hostname']); } /** * Test logging to specific channels * * @group advanced */ public function testLoggingToChannels() { //Test limited config, with limited rows and level Log::channel('limited')->debug("This message should not be stored because DEBUG is LOWER then WARNING"); $this->assertEmpty(LogToDB::model('limited')->where('channel', 'limited')->where('level_name', 'DEBUG')->get()); //Test limited config, with limited rows and level Log::channel('limited')->warning("This message should be stored because WARNING = WARNING"); $this->assertNotEmpty(LogToDB::model('limited')->where('channel', 'limited')->where('level_name', 'WARNING')->get()); } /** * Test an exception error. * * @group exception */ public function testException() { $e = new BadRequestHttpException("This is a fake 500 error", null, 500, ['fake-header' => 'value']); Log::warning("Error", ['exception' => $e, 'more' => 'infohere']); $log = LogToDB::model()->where('message', 'Error')->first(); $this->assertNotEmpty($log->context); $empty = new \Mockery\Exception(); Log::warning("Error", ['exception' => $empty]); $log = LogToDB::model()->where('message', 'Error')->orderBy('id', 'DESC')->first(); $this->assertNotEmpty($log); $this->expectException(DBLogException::class); throw new DBLogException('Dont log this'); } /** * Test exception when expected format is wrong. * * @group exception */ public function testExceptionWrongFormat() { $e = [ 'message' => 'Array instead exception', 'code' => 0, 'file' => __FILE__, 'line' => __LINE__, 'trace' => debug_backtrace(), ]; Log::warning("Error", ['exception' => $e, 'more' => 'infohere']); $log = LogToDB::model()->where('message', 'Error')->first(); $this->assertNotEmpty($log->context); } /** * * @group exception */ public function testExceptionIgnore() { $this->assertCount(0, LogToDB::model()->where('message', '=', 'Dont log this')->get()->toArray()); } /** * Test queuing the log events. * * @group queue */ public function testQueue() { Queue::fake(); config()->set('logtodb.queue', true); Log::info("I'm supposed to be added to the queue..."); Log::warning("I'm supposed to be added to the queue..."); Log::debug("I'm supposed to be added to the queue..."); Queue::assertPushed(SaveNewLogEvent::class, 6); config()->set('logtodb.queue_name', 'logHandler'); Log::info("I'm supposed to be added to the queue..."); Log::warning("I'm supposed to be added to the queue..."); Log::debug("I'm supposed to be added to the queue..."); config()->set('logtodb.queue_name', null); config()->set('logtodb.queue_connection', 'default'); Log::info("I'm supposed to be added to the queue..."); Log::warning("I'm supposed to be added to the queue..."); Log::debug("I'm supposed to be added to the queue..."); config()->set('logtodb.queue_name', 'logHandler'); Log::info("I'm supposed to be added to the queue..."); Log::warning("I'm supposed to be added to the queue..."); Log::debug("I'm supposed to be added to the queue..."); Queue::assertPushed(SaveNewLogEvent::class, 24); config()->set('logtodb.queue', false); } /** * Test save new log event job * * @group job */ public function testSaveNewLogEventJob() { $logToDb = new LogToDB(); $record = new LogRecord( datetime: new \Monolog\DateTimeImmutable(true), channel: 'local', level: \Monolog\Level::Info, message: 'job-test', context: [], extra: [], formatted: "[2019-10-04T17:26:38.446827+00:00] local.INFO: test [] []\n", ); $job = new SaveNewLogEvent($record); $job->handle(); $this->assertNotEmpty($logToDb->model()->where('message', '=', 'job-test')->get()); } /** * Test model interaction * * @group model */ public function testModelInteraction() { LogToDB::model()->truncate(); LogToDB::model('mongodb')->truncate(); for ($i=1; $i<=10; $i++) { Log::debug("This is debug log message..."); } for ($i=1; $i<=10; $i++) { Log::info("This is info log message..."); } $model = LogToDB::model(); $log = $model->first(); $this->assertIsNumeric($log->id); $this->assertIsString($log->message); $this->assertIsString($log->channel); $this->assertIsNumeric($log->level); $this->assertIsString($log->level_name); $this->assertIsNumeric($log->unix_time); $this->assertIsString($log->datetime); $this->assertIsArray($log->extra); $this->assertNotEmpty($log->created_at); $this->assertNotEmpty($log->updated_at); $this->assertDatabaseCount('log', 20); //Get all $all = $model->get(); $this->assertNotEmpty($all->toArray()); //Get Debug $logs = $model->where('level_name', '=', 'DEBUG')->get()->toArray(); $this->assertNotEmpty($logs); $this->assertEquals('DEBUG', $logs[0]['level_name']); $this->assertCount(10, $logs); $model = LogToDB::model('database'); //Get all $all = $model->get(); $this->assertNotEmpty($all->toArray()); //Get Debug $logs = $model->where('level_name', '=', 'DEBUG')->get()->toArray(); $this->assertNotEmpty($logs); $this->assertEquals('DEBUG', $logs[0]['level_name']); $this->assertCount(10, $logs); $model = LogToDB::model(null, 'mysql'); //Get all $all = $model->get(); $this->assertNotEmpty($all->toArray()); //Get Debug $logs = $model->where('level_name', '=', 'DEBUG')->get()->toArray(); $this->assertNotEmpty($logs); $this->assertEquals('DEBUG', $logs[0]['level_name']); $model = LogToDB::model('database', 'mysql', 'log'); //Get all $all = $model->get(); $this->assertNotEmpty($all->toArray()); //Get Debug $logs = $model->where('level_name', '=', 'DEBUG')->get()->toArray(); $this->assertNotEmpty($logs); $this->assertEquals('DEBUG', $logs[0]['level_name']); $this->assertCount(10, $logs); //Same tests for mongoDB $modelMongo = LogToDB::model('mongodb'); //Get all $all = $modelMongo->get(); $this->assertNotEmpty($all->toArray()); //Get Debug $logs = $modelMongo->where('level_name', '=', 'DEBUG')->get()->toArray(); $this->assertNotEmpty($logs); $this->assertEquals('DEBUG', $logs[0]['level_name']); $this->assertCount(10, $logs); //Same tests for mongoDB $modelMongo = LogToDB::model('mongodb', 'mongodb', 'log'); //Get all $all = $modelMongo->get(); $this->assertNotEmpty($all->toArray()); //Get Debug $logs = $modelMongo->where('level_name', '=', 'DEBUG')->get()->toArray(); $this->assertNotEmpty($logs); $this->assertEquals('DEBUG', $logs[0]['level_name']); $this->assertCount(10, $logs); //Same tests for mongoDB $modelMongo = LogToDB::model(null, 'mongodb'); //Get all $all = $modelMongo->get(); $this->assertNotEmpty($all->toArray()); //Get Debug $logs = $modelMongo->where('level_name', '=', 'DEBUG')->get()->toArray(); $this->assertNotEmpty($logs); $this->assertEquals('DEBUG', $logs[0]['level_name']); $this->assertCount(10, $logs); } /** * $group model */ public function testStandAloneModels() { Log::info("This is a info log message..."); $modelMongo = LogToDB::model(null, 'mongodb'); $this->assertNotEmpty(LogSql::get()->toArray()); $this->assertNotEmpty($modelMongo->get()->toArray()); } /** * @group model */ public function testCustomModel() { config()->set('logtodb.model', CustomEloquentModel::class); Log::info('This is on a custom model class'); $this->assertStringContainsString('This is on a custom model class', LogToDB::model()->latest('id')->first()->message); } /** * Test the cleanup functions. * * @group cleanup */ public function testRemoves() { $this->assertFalse(LogToDB::model()->removeOldestIfMoreThan(1000)); Log::debug("This is an test DEBUG log event"); Log::info("This is an test INFO log event"); Log::notice("This is an test NOTICE log event"); //sleep to pass time for record cleanup testing based on time next. sleep(1); $this->assertTrue(LogToDB::model()->removeOldestIfMoreThan(2)); $this->assertEquals(2, LogToDB::model()->count()); $this->assertTrue(LogToDB::model()->removeOlderThan(date('Y-m-d H:i:s'))); $this->assertEquals(0, LogToDB::model()->count()); //Same tests on mongodb $this->assertTrue(LogToDB::model('mongodb')->removeOldestIfMoreThan(2)); $this->assertEquals(2, LogToDB::model('mongodb')->count()); $this->assertTrue(LogToDB::model('mongodb')->removeOlderThan(date('Y-m-d H:i:s'))); $this->assertEquals(0, LogToDB::model('mongodb')->count()); //test wrappers for silly spelling Log::debug("This is an test DEBUG log event"); Log::info("This is an test INFO log event"); Log::notice("This is an test NOTICE log event"); //sleep to pass time for record cleanup testing based on time next. sleep(1); $this->assertTrue(LogToDB::model()->removeOldestIfMoreThen(2)); $this->assertEquals(2, LogToDB::model()->count()); $this->assertTrue(LogToDB::model()->removeOlderThen(date('Y-m-d H:i:s'))); $this->assertEquals(0, LogToDB::model()->count()); //Same tests on mongodb $this->assertTrue(LogToDB::model('mongodb')->removeOldestIfMoreThen(2)); $this->assertEquals(2, LogToDB::model('mongodb')->count()); $this->assertTrue(LogToDB::model('mongodb')->removeOlderThen(date('Y-m-d H:i:s'))); $this->assertEquals(0, LogToDB::model('mongodb')->count()); } /** * Test the CleanerUpper * * @group cleanerUpper */ public function testCleanerUpper() { //Add bunch of old records for ($i = 0; $i < 20; $i++) { $log = LogToDB::model(); $thePast = \Carbon\Carbon::now()->subHours(24); $log->message = "This is fake test number: {$i}"; $log->channel = 'test'; $log->level = 100; $log->level_name = 'DEBUG'; $log->unix_time = $thePast->unix(); $log->datetime = new \Monolog\DateTimeImmutable(time()); $log->created_at = $thePast->toDateTimeString(); $log->updated_at = $thePast->toDateTimeString(); $log->save(); } //Add bunch of old records for ($i = 0; $i < 20; $i++) { $log = LogToDB::model('mongodb'); $thePast = \Carbon\Carbon::now()->subHours(24); $log->message = "This is fake test number: {$i}"; $log->channel = 'test'; $log->level = 100; $log->level_name = 'DEBUG'; $log->unix_time = $thePast->unix(); $log->datetime = new \Monolog\DateTimeImmutable(time()); $log->created_at = $thePast->toDateTimeString(); $log->updated_at = $thePast->toDateTimeString(); $log->save(); } //Add 5 new records for ($i = 0; $i < 5; $i++) { Log::debug("This is an test DEBUG log event number: {$i}"); } $this->assertEquals(25, LogToDB::model()->count()); $this->assertEquals(25, LogToDB::model('mongodb')->count()); //Run cleanup command $this->artisan('log:delete')->assertExitCode(0); $this->assertEquals(5, LogToDB::model()->count()); $this->assertEquals(5, LogToDB::model('mongodb')->count()); //Add 10 new records for ($i = 0; $i < 10; $i++) { Log::debug("This is an test DEBUG log event number: {$i}"); } //Run cleanup command $this->artisan('log:delete')->assertExitCode(0); $this->assertEquals(10, LogToDB::model()->count()); $this->assertEquals(10, LogToDB::model('mongodb')->count()); } /** * Clear all data from the test. * * @group cleanerUpper */ public function testFinalCleanup() { LogToDB::model()->truncate(); LogToDB::model('mongodb')->truncate(); $this->assertEmpty(LogToDB::model()->get()->toArray()); $this->assertEmpty(LogToDB::model('mongodb')->get()->toArray()); $this->assertEmpty(LogToDB::model('limited')->get()->toArray()); $this->assertEmpty(LogToDB::model('database')->get()->toArray()); $this->artisan('migrate:rollback', ['--database' => 'mysql']); } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/tests/FailureTest.php
tests/FailureTest.php
<?php /** * Created by Daniel Mellum <mellum@gmail.com> * Date: 9/28/2021 * Time: 4:29 AM */ use Illuminate\Support\Facades\Log; class FailureTest extends Orchestra\Testbench\TestCase { protected function getEnvironmentSetUp($app) { $dotenv = Dotenv\Dotenv::createImmutable(__DIR__.'/../', '.env.testing'); $dotenv->load(); $app['config']->set('logging.default', 'database'); $app['config']->set('logging.channels', [ 'database' => [ 'driver' => 'custom', 'via' => danielme85\LaravelLogToDB\LogToDbHandler::class, 'level' => 'debug', 'connection' => 'default', 'collection' => 'log', 'max_records' => 10, 'max_hours' => 1, 'processors' => [ Monolog\Processor\HostnameProcessor::class, Monolog\Processor\MemoryUsageProcessor::class, danielme85\LaravelLogToDB\Processors\PhpVersionProcessor::class ] ], ]); $app['config']->set('logtodb', include __DIR__.'/../src/config/logtodb.php'); } public function testEmergencyFailure() { $capture = tmpfile(); $backup = ini_set('error_log', stream_get_meta_data($capture)['uri']); Log::info('what?'); $result = stream_get_contents($capture); ini_set('error_log', $backup); $this->assertStringContainsString( 'CRITICAL: There was an error while trying to write the log to a DB', $result ); $this->assertStringContainsString( 'INFO: what?', $result ); } }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/tests/TestModels/CustomEloquentModel.php
tests/TestModels/CustomEloquentModel.php
<?php namespace TestModels; use danielme85\LaravelLogToDB\Models\LogToDbCreateObject; use Illuminate\Database\Eloquent\Model; /** * Class CustomEloquentModel * * @package danielme85\LaravelLogToDB */ class CustomEloquentModel extends Model { use LogToDbCreateObject; protected $connection = 'mysql'; protected $table = 'log'; }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/tests/TestModels/LogMongo.php
tests/TestModels/LogMongo.php
<?php /** * Created by PhpStorm. * User: dmellum * Date: 4/11/19 * Time: 2:35 PM */ namespace TestModels; use MongoDB\Laravel\Eloquent\Model as Eloquent; class LogMongo extends Eloquent { protected $collection = 'log'; protected $connection = 'mongodb'; }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
danielme85/laravel-log-to-db
https://github.com/danielme85/laravel-log-to-db/blob/5ccfde1c3a418290bb60a3573f525d080a08ef6d/tests/TestModels/LogSql.php
tests/TestModels/LogSql.php
<?php /** * Created by PhpStorm. * User: dmellum * Date: 4/11/19 * Time: 2:35 PM */ namespace TestModels; use Illuminate\Database\Eloquent\Model; class LogSql extends Model { protected $table = 'log'; }
php
MIT
5ccfde1c3a418290bb60a3573f525d080a08ef6d
2026-01-05T04:56:28.405515Z
false
yvoronoy/magento2-bash-completion
https://github.com/yvoronoy/magento2-bash-completion/blob/5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a/src/registration.php
src/registration.php
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Voronoy_BashCompletion', __DIR__ );
php
MIT
5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a
2026-01-05T04:56:33.762687Z
false
yvoronoy/magento2-bash-completion
https://github.com/yvoronoy/magento2-bash-completion/blob/5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a/src/Model/CommandCollection.php
src/Model/CommandCollection.php
<?php namespace Voronoy\BashCompletion\Model; use Symfony\Component\Console\Command\Command; class CommandCollection implements \Countable { private $commands = []; public function add(Command $command) { $this->commands[$command->getName()] = $command; } public function getItems() { return $this->commands; } public function getItem($commandName) { if (isset($this->commands[$commandName])) { return $this->commands[$commandName]; } } public function count() { return count($this->commands); } /** * Set Items * * @param array $commands */ public function setItems(array $commands) { $this->commands = $commands; } }
php
MIT
5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a
2026-01-05T04:56:33.762687Z
false
yvoronoy/magento2-bash-completion
https://github.com/yvoronoy/magento2-bash-completion/blob/5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a/src/Model/BashCompletion.php
src/Model/BashCompletion.php
<?php namespace Voronoy\BashCompletion\Model; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Filesystem; use Voronoy\BashCompletion\Model\BashCompletion\Generator; class BashCompletion { private $name = 'magento2-bash-completion'; private $filesystem; private $generator; public function __construct( Filesystem $filesystem, Generator $generator ) { $this->filesystem = $filesystem; $this->generator = $generator; } public function generateCompletionList($name = null) { if (!$name) { $name = $this->getName(); } $directoryWrite = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); $directoryWrite->writeFile($name, $this->generator->generate()); return 'Magento2 Bash Completion generated in var/' . $name; } public function getName() { return $this->name; } }
php
MIT
5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a
2026-01-05T04:56:33.762687Z
false
yvoronoy/magento2-bash-completion
https://github.com/yvoronoy/magento2-bash-completion/blob/5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a/src/Model/BashCompletion/Generator.php
src/Model/BashCompletion/Generator.php
<?php namespace Voronoy\BashCompletion\Model\BashCompletion; use Symfony\Component\Console\Command\Command; use Voronoy\BashCompletion\Model\CommandCollection; class Generator { private $commandCollection; public function __construct(CommandCollection $commandCollection) { $this->commandCollection = $commandCollection; } public function generate() { $template = $this->getTemplate(); return $template; } private function getAllCommands() { $commandCollection = $this->commandCollection; $commands = array_keys($commandCollection->getItems()); $commands = implode(' ', $commands); return $commands; } private function getTemplate() { return <<<TEMPLATE _magento2() { local cur opts first_word COMPREPLY=() _get_comp_words_by_ref -n : cur words for word in \${words[@]:1}; do if [[ \$word != -* ]]; then first_word=\$word break fi done opts="{$this->getAllCommands()}" case "\$first_word" in {$this->getDefinitions()} esac COMPREPLY=( $(compgen -W "\${opts}" -- \${cur}) ) __ltrim_colon_completions "\$cur" } complete -o default -F _magento2 magento TEMPLATE; } private function getDefinitions() { $definitions = ''; foreach ($this->commandCollection->getItems() as $name => $cmd) { /** @var Command $cmd */ if (!$cmd->getDefinition()->getOptions()) { continue; } $options = array_keys($cmd->getDefinition()->getOptions()); foreach ($options as &$option) { $option = sprintf('--%s', $option); } $options = implode(' ', $options); $definitions .= <<<TEMPLATE {$name}) opts="{$options}" ;; TEMPLATE; } return $definitions; } }
php
MIT
5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a
2026-01-05T04:56:33.762687Z
false
yvoronoy/magento2-bash-completion
https://github.com/yvoronoy/magento2-bash-completion/blob/5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a/src/Console/Command/BashCompletionCommand.php
src/Console/Command/BashCompletionCommand.php
<?php namespace Voronoy\BashCompletion\Console\Command; use Magento\Framework\App\ObjectManager; use Magento\Framework\Filesystem; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Descriptor\ApplicationDescription; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Voronoy\BashCompletion\Model\BashCompletion; use Voronoy\BashCompletion\Model\CommandCollection; class BashCompletionCommand extends Command { const COMMAND_NAME = 'bash:completion:generate'; const INPUT_ARG_NAME = 'name'; private $commandCollection; private $bashCompletion; public function __construct( CommandCollection $commandCollection, BashCompletion $bashCompletion ) { $this->commandCollection = $commandCollection; $this->bashCompletion = $bashCompletion; parent::__construct(); } protected function configure() { $this->setName(self::COMMAND_NAME) ->setDescription('Generate Bash Completion List.'); $this->setDefinition([new InputArgument( self::INPUT_ARG_NAME, InputArgument::OPTIONAL, 'Bash Completion File Name' )]); } protected function execute(InputInterface $input, OutputInterface $output) { $description = new ApplicationDescription($this->getApplication()); $commands = $description->getCommands(); foreach ($commands as $command) { if ($command->getName() == self::COMMAND_NAME) { continue; } $this->commandCollection->add($command); } $result = $this->bashCompletion->generateCompletionList( $input->getArgument(self::INPUT_ARG_NAME) ); return $output->writeln($result); } }
php
MIT
5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a
2026-01-05T04:56:33.762687Z
false
yvoronoy/magento2-bash-completion
https://github.com/yvoronoy/magento2-bash-completion/blob/5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a/spec/Model/BashCompletionSpec.php
spec/Model/BashCompletionSpec.php
<?php namespace spec\Voronoy\BashCompletion\Model; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Filesystem; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Symfony\Component\Console\Command\Command; use Voronoy\BashCompletion\Model\BashCompletion; use Voronoy\BashCompletion\Model\BashCompletion\Generator; use Voronoy\BashCompletion\Model\CommandCollection; class BashCompletionSpec extends ObjectBehavior { function let( Filesystem $filesystem, Generator $bashCompleteGenerator ) { $this->beConstructedWith( $filesystem, $bashCompleteGenerator ); } function it_is_initializable() { $this->shouldHaveType('Voronoy\BashCompletion\Model\BashCompletion'); } function it_should_generate_bash_completion_file( Filesystem $filesystem, Filesystem\Directory\WriteInterface $write, Generator $bashCompleteGenerator ) { $bashCompleteGenerator->generate()->shouldBeCalled()->willReturn('abc'); $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR) ->willReturn($write) ->shouldBeCalled(1); $write->writeFile('magento2-bash-completion', 'abc')->willReturn(3); $this->generateCompletionList() ->shouldReturn('Magento2 Bash Completion generated in var/magento2-bash-completion'); } function it_should_return_entered_name( Filesystem $filesystem, Generator $bashCompleteGenerator, Filesystem\Directory\WriteInterface $write ) { $bashCompleteGenerator->generate()->shouldBeCalled()->willReturn('abc'); $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR) ->willReturn($write) ->shouldBeCalled(1); $write->writeFile('custom-name', 'abc')->willReturn(3); $this->generateCompletionList('custom-name') ->shouldReturn('Magento2 Bash Completion generated in var/custom-name'); } }
php
MIT
5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a
2026-01-05T04:56:33.762687Z
false
yvoronoy/magento2-bash-completion
https://github.com/yvoronoy/magento2-bash-completion/blob/5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a/spec/Model/CommandCollectionSpec.php
spec/Model/CommandCollectionSpec.php
<?php namespace spec\Voronoy\BashCompletion\Model; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Symfony\Component\Console\Command\Command; use Voronoy\BashCompletion\Model\CommandCollection; class CommandCollectionSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Voronoy\BashCompletion\Model\CommandCollection'); } function it_should_be_able_add_command(Command $command) { $command->getName()->willReturn('abc'); $this->add($command); $this->getItems()->shouldBeArray(); $this->getItems()->shouldContain($command); $this->getItem('abc')->shouldReturn($command); } function it_should_be_countable(Command $command1, Command $command2) { $command1->getName()->willReturn('abc'); $command2->getName()->willReturn('cba'); $this->add($command1); $this->add($command2); $this->count()->shouldBe(2); } function it_can_add_multiple_items_to_collection(Command $command1, Command $command2) { $this->setItems([$command1, $command2]); $this->count()->shouldBe(2); } }
php
MIT
5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a
2026-01-05T04:56:33.762687Z
false
yvoronoy/magento2-bash-completion
https://github.com/yvoronoy/magento2-bash-completion/blob/5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a/spec/Model/BashCompletion/GeneratorSpec.php
spec/Model/BashCompletion/GeneratorSpec.php
<?php namespace spec\Voronoy\BashCompletion\Model\BashCompletion; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputOption; use Voronoy\BashCompletion\Model\CommandCollection; class GeneratorSpec extends ObjectBehavior { function let( CommandCollection $collection, Command $command1, Command $command2, InputDefinition $inputDefinition, InputDefinition $inputDefinition2, InputOption $inputOption, InputOption $inputOption2 ) { $inputDefinition->getOptions()->willReturn([ 'option1' => $inputOption, 'option2' => $inputOption2 ]); $command1->getName()->willReturn('test:command'); $command1->getDefinition()->willReturn($inputDefinition); $inputDefinition2->getOptions()->willReturn([]); $command2->getName()->willReturn('other-command'); $command2->getDefinition()->willReturn($inputDefinition2); $collection->getItems()->willReturn([ 'test:command' => $command1, 'other-command' => $command2 ]); $this->beConstructedWith($collection); } function it_is_initializable() { $this->shouldHaveType('Voronoy\BashCompletion\Model\BashCompletion\Generator'); } function it_there_is_generate_method() { $expected = <<<'TEMPLATE' _magento2() { local cur opts first_word COMPREPLY=() _get_comp_words_by_ref -n : cur words for word in ${words[@]:1}; do if [[ $word != -* ]]; then first_word=$word break fi done opts="test:command other-command" case "$first_word" in test:command) opts="--option1 --option2" ;; esac COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) __ltrim_colon_completions "$cur" } complete -o default -F _magento2 magento TEMPLATE; $this->generate()->shouldBe($expected); } }
php
MIT
5ad70d90d1a4bc37b1582cd5e7d142bb3cff990a
2026-01-05T04:56:33.762687Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/functions.php
functions.php
<?php /* * This file is the main entry point for WordPress functions. * The top set of files generally require edits. */ // Builds Vue router include_once get_template_directory() . '/functions/router.php'; // Sets up custom Gutenberg blocks include_once get_template_directory() . '/functions/blocks.php'; // Custom Rest-Easy filters include_once get_template_directory() . '/functions/rest-easy-filters.php'; // Misc WordPress functions include_once get_template_directory() . '/functions/wp-functions.php'; // Handles what image sizes WordPress should generate server side include_once get_template_directory() . '/functions/images.php'; // Handles the server side processing of WordPress shortcodes include_once get_template_directory() . '/functions/shortcodes.php'; // Provides list of custom Vue Templates that the user can select from a drop-down menu include_once get_template_directory() . '/functions/custom-vuehaus-templates.php'; // Defines the UI for custom meta boxes in WordPress include_once get_template_directory() . '/functions/meta-boxes.php'; //Add additional ACF functionality include_once get_template_directory() . '/acf/acf-imports.php'; /* * Generally you don't have to edit any of the files below */ // Handles vh functions and plugin dependencies (Rest-Easy and recommended Nested Pages) include_once get_template_directory() . '/functions/vh-functions.php'; // Handles Developer role include_once get_template_directory() . '/functions/developer-role.php'; // Add fonts to admin area function include_vp_fonts(){ echo get_template_part('parts/font-loader'); } add_action( 'admin_head', 'include_vp_fonts' );
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/index.php
index.php
<!-- ███████╗██╗ ██╗███╗ ██╗██╗ ██╗██╗ ██╗ █████╗ ██╗ ██╗███████╗ ██╔════╝██║ ██║████╗ ██║██║ ██╔╝██║ ██║██╔══██╗██║ ██║██╔════╝ █████╗ ██║ ██║██╔██╗ ██║█████╔╝ ███████║███████║██║ ██║███████╗ ██╔══╝ ██║ ██║██║╚██╗██║██╔═██╗ ██╔══██║██╔══██║██║ ██║╚════██║ ██║ ╚██████╔╝██║ ╚████║██║ ██╗██║ ██║██║ ██║╚██████╔╝███████║ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝ www.funkhaus.us --> <!DOCTYPE html> <html <?php language_attributes(); ?> prefix="og: http://ogp.me/ns#"> <head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <title><?php wp_title(); ?></title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link rel="stylesheet" type="text/css" media="all" href="<?php echo get_template_directory_uri(); ?>/static/bundle.css?ver=<?php echo custom_latest_timestamp(); ?>" /> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" /> <link rel="shortcut icon" href="<?php echo get_template_directory_uri(); ?>/static/images/favicon.png" /> <link rel="apple-touch-icon" href="<?php echo get_template_directory_uri(); ?>/static/images/icon-touch.png"/> <?php get_template_part('parts/ga-tracking'); ?> <?php get_template_part('parts/og-tags'); ?> <?php get_template_part('parts/schema'); ?> <?php get_template_part('parts/font-loader'); ?> <?php wp_head();?> </head> <body <?php body_class(); ?>> <div id="app"></div> <?php wp_footer();?> </body> </html>
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/acf/acf-imports.php
acf/acf-imports.php
<?php // Locations // Adds Page Gandparent to rule locations include_once get_template_directory() . '/acf/locations/page-grandparent.php';
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/acf/locations/page-grandparent.php
acf/locations/page-grandparent.php
<?php // ACF Custom Rules // Add custom page grandparent location to ACF function acf_location_rules_page_grandparent($choices) { $choices['Page']['page_grandparent'] = 'Page Grandparent'; return $choices; } add_filter('acf/location/rule_values/page_grandparent', 'acf_location_rules_values_page_grandparent'); function acf_location_rules_values_page_grandparent($choices) { // this code is copied directly from // render_location_values() // case "page" $groups = acf_get_grouped_posts(array( 'post_type' => 'page' )); if (!empty($groups)) { foreach(array_keys($groups) as $group_title) { $posts = acf_extract_var($groups, $group_title); foreach(array_keys($posts) as $post_id) { $posts[$post_id] = acf_get_post_title($posts[$post_id]); }; $choices = $posts; } } // end of copy from ACF return $choices; } add_filter('acf/location/rule_types', 'acf_location_rules_page_grandparent'); function acf_location_rules_match_page_grandparent($match, $rule, $options) { // this code is with inspiration from // acf_location::rule_match_page_parent() // with addition of adding grandparent check if(!$options['post_id']) { return false; } $post_grandparent = 0; $post = get_post($options['post_id']); if ($post->post_parent) { $parent = get_post($post->post_parent); if ($parent->post_parent) { $post_grandparent = $parent->post_parent; } } if (isset($options['page_parent']) && $options['page_parent']) { $parent = get_post($options['page_parent']); if ($parent->post_parent) { $post_grandparent = $parent->post_parent; } } if (!$post_grandparent) { return false; } if ($rule['operator'] == "==") { $match = ($post_grandparent == $rule['value']); } elseif ($rule['operator'] == "!=") { $match = ($post_grandparent != $rule['value']); } return $match; } add_filter('acf/location/rule_match/page_grandparent', 'acf_location_rules_match_page_grandparent', 10, 3);
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/parts/og-tags.php
parts/og-tags.php
<?php the_post(); /* * Build the image URL */ $use_png = file_exists(dirname(__FILE__) . '/../screenshot.png'); $extension = $use_png ? 'png' : 'jpg'; $shared_image = get_template_directory_uri() . "/screenshot." . $extension; if( is_single() || is_page() ) { // If page or is single, set the shared image to the post thumbnail. $image_id = get_post_thumbnail_id(); if( !empty($image_id) ) { $image_url = wp_get_attachment_image_src($image_id, 'social-preview'); $shared_image = $image_url[0]; } } /* * This builds the summary text. */ $summary = get_bloginfo('description'); if( is_single() || is_page() ) { // If page has no children or is single, set the summary to the excerpt. $summary = get_the_excerpt(); if( empty($summary) ) { $summary = wp_trim_excerpt( strip_shortcodes($post->post_content) ); } } // Remove any links, tags or line breaks from summary $summary = strip_tags($summary); $summary = esc_attr($summary); $summary = preg_replace('!\s+!', ' ', $summary); /* * Build permalink URL */ $url = get_permalink($post->ID); if( is_front_page() ) { $url = get_bloginfo('url'); } ?> <meta name="description" content="<?php echo empty($summary) ? get_bloginfo('description') : $summary; ?>" /> <!-- Start Open Graph Meta Tags --> <meta property="og:title" content="<?php wp_title(''); ?>" /> <meta property="og:type" content="website" /> <meta property="og:url" content="<?php echo get_permalink($post->ID); ?>" /> <meta property="og:image" content="<?php echo $shared_image; ?>" /> <meta property="og:description" content="<?php echo empty($summary) ? get_bloginfo('description') : $summary; ?>" /> <meta property="og:site_name" content="<?php bloginfo('name'); ?>" /> <!-- End Open Graph Meta Tags -->
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/parts/ga-tracking.php
parts/ga-tracking.php
<?php // Get options out of General Setting panel $tracking_names = array('ga_tracking_code_1', 'ga_tracking_code_2'); $tracking_ids = array(); foreach($tracking_names as $name) { $option = get_option($name); if( !empty($option) ) { $tracking_ids[] = $option; } } ?> <?php if( !empty($tracking_ids) and !current_user_can('administrator') ) : ?> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo $tracking_ids[0]; ?>"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); <?php foreach($tracking_ids as $id) : ?> gtag('config', '<?php echo $id; ?>'); <?php endforeach; ?> </script> <?php endif; ?>
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/parts/schema.php
parts/schema.php
<?php // abort if no post to work off of if ( ! $post = get_post() ) return; the_post(); // schema defaults $use_png = file_exists(dirname(__FILE__) . '/../screenshot.png'); $extension = $use_png ? 'png' : 'jpg'; $schema = array( '@context' => 'http://schema.org', '@type' => 'WebPage', 'headline' => get_bloginfo('description'), 'url' => get_bloginfo('url'), 'thumbnailUrl' => get_template_directory_uri() . '/screenshot.' . $extension ); // helper to generate schema Person object function schema_generate_person($name){ return array( '@type' => 'Person', 'name' => $name ); } // helper to generate schema Organization object function schema_generate_org($name = null, $logo = null){ return array( '@type' => 'Organization', 'name' => $name ? $name : get_bloginfo('name'), 'logo' => $logo ? $logo : get_template_directory_uri() . '/images/logo.svg' ); } // set some helpful vars $image_id = false; $image_url = false; $image = wp_get_attachment_image_src($image_id, 'social-preview'); if( $image ){ $image_id = get_post_thumbnail_id( $post ); $image_url = reset( $image ); } $author = get_user_by('ID', $post->post_author); $queried_object = get_queried_object(); $excerpt = get_the_excerpt($post); // build on schema conditionally switch (true) { // is non-home page case !is_front_page() and is_page(): $schema['headline'] = get_the_title($post); $schema['url'] = get_the_permalink($post); $schema['thumbnailUrl'] = $image_url; $schema['description'] = $excerpt ? $excerpt : get_bloginfo('description'); break; // is single post case is_single(): $schema['@type'] = 'NewsArticle'; $schema['headline'] = get_the_title($post); $schema['url'] = get_the_permalink($post); $schema['thumbnailUrl'] = $image_url; $schema['image'] = $image_url; $schema['dateCreated'] = get_the_date('Y-m-d'); $schema['datePublished'] = get_the_date('Y-m-d'); $schema['articleSection'] = ''; $schema['description'] = get_the_excerpt($post); $schema['creator'] = $author ? schema_generate_person($author->display_name) : schema_generate_org(); $schema['author'] = $author ? schema_generate_person($author->display_name) : schema_generate_org(); $schema['publisher'] = schema_generate_org(); $schema['keywords'] = wp_get_post_categories($post->ID, array( 'fields' => 'names' )); break; // all archive pages case is_archive(): $schema['@type'] = 'Blog'; // is a term archive if ( property_exists($queried_object, 'term_id') ){ $schema['headline'] = term_description($queried_object->term_id); $schema['url'] = get_term_link($queried_object->term_id); $schema['articleSection'] = $queried_object->name; } break; // blog archive, if different than front page case is_home() and !is_front_page(): $schema['@type'] = 'Blog'; $schema['url'] = get_the_permalink(get_option('page_for_posts')); break; } ?> <!-- start schema.org definition --> <script type="application/ld+json"> <?php echo json_encode($schema); ?> </script> <!-- end schema.org -->
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/parts/font-loader.php
parts/font-loader.php
<script> WebFontConfig = { // google: { // families: [] // }, // typekit: { // id: '' // }, // custom: { // families: [], // urls: ['<?php echo get_template_directory_uri(); ?>/static/fonts/fonts.css'] // } }; (function(d) { var wf = d.createElement('script'), s = d.scripts[0]; wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js'; wf.async = true; s.parentNode.insertBefore(wf, s); })(document); </script>
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/functions/images.php
functions/images.php
<?php /* * Setup image sizes that WordPress should generate on the server. */ function custom_image_sizes(){ // Enable post thumbnail support add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 960, 540, true ); // Normal post thumbnails //add_image_size( 'banner-thumb', 566, 250, true ); // Small thumbnail size add_image_size( 'social-preview', 600, 315, true ); // Square thumbnail used by sharethis and facebook add_image_size( 'fullscreen', 1920, 1080, false ); // Fullscreen image size } add_action( 'after_setup_theme', 'custom_image_sizes' );
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/functions/developer-role.php
functions/developer-role.php
<?php // Add Developer role function custom_theme_switch(){ global $wp_roles; if ( ! isset( $wp_roles ) ){ $wp_roles = new WP_Roles(); } $admin_role = $wp_roles->get_role('administrator'); add_role( 'developer', __('Developer'), $admin_role->capabilities ); // set initial user to Developer $user = new WP_User(1); $user->set_role('developer'); } add_action('after_switch_theme', 'custom_theme_switch'); /* * Disable Rich Editor on certain pages */ function disabled_rich_editor($allow_rich_editor) { global $post; if($post->_custom_hide_richedit === 'on') { return false; } return true; } add_filter( 'user_can_richedit', 'disabled_rich_editor'); /* * Deactivate attachment serialization on certain pages */ function deactivate_attachment_serialization($allow_attachment_serialization) { global $post; if($post->_custom_deactivate_attachment_serialization === 'on') { return false; } return true; } add_filter( 'rez-serialize-attachments', 'deactivate_attachment_serialization'); /* * Add developer metaboxes to the new/edit page */ function custom_add_developer_metaboxes($post_type, $post){ if( !user_is_developer() ) return; add_meta_box('custom_dev_meta', 'Developer Meta', 'custom_dev_meta', 'page', 'normal', 'low'); } add_action('add_meta_boxes', 'custom_add_developer_metaboxes', 10, 2); // Build dev meta box (only for users with Developer role) function custom_dev_meta($post) { ?> <div class="custom-meta"> <label for="custom-developer-id">Enter the Developer ID for this page:</label> <input id="custom-developer-id" class="short" title="Developer ID" name="custom_developer_id" type="text" value="<?php echo $post->custom_developer_id; ?>"> <br/> <label for="custom-lock">Prevent non-dev deletion:</label> <input id="custom-lock" class="short" title="Prevent deletion" name="_custom_lock" type="checkbox" <?php if( $post->_custom_lock ) echo 'checked'; ?>> <br/> <label for="custom-richedit">Hide rich editor:</label> <input id="custom-richedit" class="short" title="Hide rich editor" name="_custom_hide_richedit" type="checkbox" <?php if( $post->_custom_hide_richedit === 'on' ) echo 'checked'; ?>> <br/> <label for="custom-attachment-serialize">Prevent attachment serialization:</label> <input id="custom-attachment-serialize" class="short" title="Prevent attachment serialization" name="_custom_deactivate_attachment_serialization" type="checkbox" <?php if( $post->_custom_deactivate_attachment_serialization === 'on' ) echo 'checked'; ?>> <br/> </div> <?php } // Prevent non-dev from deleting locked pages/posts function check_custom_post_lock( $target_post ){ $target_post = get_post($target_post); if( !user_is_developer() and $target_post->_custom_lock ){ echo 'Only a user with the Developer role can delete this page.<br/><br/>'; echo '<a href="javascript:history.back()">Back</a>'; exit; } } add_action('wp_trash_post', 'check_custom_post_lock', 10, 1); add_action('before_delete_post', 'check_custom_post_lock', 10, 1); function custom_save_developer_metabox($post_id){ // check autosave if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) { return $post_id; } // these values will only be updated if the current user is a Developer if( !user_is_developer() ) return; if( isset($_POST['custom_developer_id']) ) { update_post_meta($post_id, 'custom_developer_id', $_POST['custom_developer_id']); } if( isset($_POST['_custom_lock']) ) { $value = $_POST['_custom_lock'] == 'on' ? 'on' : 0; update_post_meta($post_id, '_custom_lock', $value); } else { update_post_meta($post_id, '_custom_lock', 0); } if( isset($_POST['_custom_hide_richedit']) ){ $value = $_POST['_custom_hide_richedit'] == 'on' ? 'on' : 0; update_post_meta($post_id, '_custom_hide_richedit', $_POST['_custom_hide_richedit']); } else { update_post_meta($post_id, '_custom_hide_richedit', 0); } if( isset($_POST['_custom_deactivate_attachment_serialization']) ){ $value = $_POST['_custom_deactivate_attachment_serialization'] == 'on' ? 'on' : 0; update_post_meta($post_id, '_custom_deactivate_attachment_serialization', $_POST['_custom_deactivate_attachment_serialization']); } else { update_post_meta($post_id, '_custom_deactivate_attachment_serialization', 0); } } add_action('save_post', 'custom_save_developer_metabox'); function user_is_developer(){ $roles = wp_get_current_user()->roles; return in_array( 'developer', $roles ); } // Gets page by a given dev ID function get_page_by_dev_id( $dev_id ){ $args = array( 'posts_per_page' => 1, 'meta_key' => 'custom_developer_id', 'meta_value' => $dev_id, 'post_type' => 'page', ); return reset( get_posts($args) ); } // Convenience function - get relative path by dev ID function path_from_dev_id($dev_id, $after = ''){ $retrieved_page = get_page_by_dev_id($dev_id); if( !$retrieved_page ){ return '#404'; } $base_url = rtrim(wp_make_link_relative(get_permalink($retrieved_page)), '/'); return $base_url . $after; } // Convenience function - get slug by dev ID function slug_from_dev_id($dev_id){ $retrieved_page = get_page_by_dev_id($dev_id); if( !$retrieved_page ){ return ''; } return $retrieved_page->post_name; } // Gets the nth child of a page with a given Developer ID function get_child_of_dev_id($dev_id, $nth_child = 0){ $parent = get_page_by_dev_id($dev_id); $args = array( 'posts_per_page' => 1, 'offset' => $nth_child, 'orderby' => 'menu_order', 'order' => 'ASC', 'post_type' => 'page', 'post_parent' => $parent->ID, ); return reset(get_posts($args)); } // Gets the relative path of the nth child of a page with given Developer ID function get_child_of_dev_id_path($dev_id, $nth_child = 0, $after = ''){ $permalink = get_permalink(get_child_of_dev_id($dev_id, $nth_child)); return $base_url = rtrim($permalink, '/'); } // Gets the children of a page with the given Developer ID function get_children_of_dev_id($dev_id){ $parent = get_page_by_dev_id($dev_id); if( $parent === false ) { return false; } $args = array( 'posts_per_page' => -1, 'post_type' => 'page', 'orderby' => 'menu_order', 'order' => 'ASC', 'post_parent' => $parent->ID, ); return get_posts($args); } // Makes sure Developer role can sort Nested Pages automatically function give_developer_ordering_permissions(){ if( is_plugin_active('wp-nested-pages/nestedpages.php') ){ $allowed_to_sort = get_option('nestedpages_allowsorting'); if( !$allowed_to_sort ){ $allowed_to_sort = array(); } if( !in_array('developer', $allowed_to_sort) ){ $allowed_to_sort[] = 'developer'; update_option('nestedpages_allowsorting', $allowed_to_sort); } } } add_action('admin_init', 'give_developer_ordering_permissions', 1); // add 'is-developer' class to WP admin pages if we're a developer function add_developer_admin_body_class($classes){ if( user_is_developer() ){ $classes .= ' is-developer'; } return $classes; } add_filter('admin_body_class', 'add_developer_admin_body_class'); // add extra capabilities for common plugins function add_extra_vh_capabilities(){ global $wp_roles; // add desired developer capabilities here $caps_to_add = array( 'manage_woocommerce', 'view_woocommerce_reports' ); // woocommerce defaults // (https://github.com/woocommerce/woocommerce/blob/master/includes/class-wc-install.php#L981) $capability_types = array( 'product', 'shop_order', 'shop_coupon' ); foreach ( $capability_types as $capability_type ) { $wc_caps_to_add = array( // Post type. "edit_{$capability_type}", "read_{$capability_type}", "delete_{$capability_type}", "edit_{$capability_type}s", "edit_others_{$capability_type}s", "publish_{$capability_type}s", "read_private_{$capability_type}s", "delete_{$capability_type}s", "delete_private_{$capability_type}s", "delete_published_{$capability_type}s", "delete_others_{$capability_type}s", "edit_private_{$capability_type}s", "edit_published_{$capability_type}s", // Terms. "manage_{$capability_type}_terms", "edit_{$capability_type}_terms", "delete_{$capability_type}_terms", "assign_{$capability_type}_terms", ); foreach($wc_caps_to_add as $wc_cap_to_add){ $caps_to_add[] = $wc_cap_to_add; } } // get developer role $developer_role = get_role('developer'); // add desired caps to developer if they don't exist yet foreach($caps_to_add as $cap_to_add){ if( !$developer_role->has_cap($cap_to_add) ){ $wp_roles->add_cap( 'developer', $cap_to_add ); } } } // add permissions after any plugin activated add_action('activated_plugin', 'add_extra_vh_capabilities');
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/functions/vh-functions.php
functions/vh-functions.php
<?php /* * This file handles the required plugins of the vuehaus theme */ include_once get_template_directory() . '/functions/class-tgm-plugin-activation.php'; function vuehaus_register_required_plugins() { // Change these values to install new versions of FH plugins $latest_rest_easy = '1.48'; $latest_focushaus = '1.0.5'; $config = array( 'id' => 'vuehaus', // Unique ID for hashing notices for multiple instances of TGMPA. 'default_path' => '', // Default absolute path to bundled plugins. 'menu' => 'tgmpa-install-plugins', // Menu slug. 'parent_slug' => 'themes.php', // Parent menu slug. 'capability' => 'edit_theme_options', // Capability needed to view plugin install page, should be a capability associated with the parent menu used. 'has_notices' => true, // Show admin notices or not. 'dismissable' => true, // If false, a user cannot dismiss the nag message. 'dismiss_msg' => '', // If 'dismissable' is false, this message will be output at top of nag. 'is_automatic' => false, // Automatically activate plugins after installation or not. 'message' => '', // Message to output right before the plugins table. ); $plugins = array( array( 'name' => 'Rest-Easy', 'slug' => 'rest-easy', 'source' => 'https://github.com/funkhaus/Rest-Easy/archive/master.zip', 'version' => $latest_rest_easy ), array( 'name' => 'Nested Pages', 'slug' => 'wp-nested-pages', 'required' => false ), array( 'name' => 'Focushaus', 'slug' => 'focushaus', 'source' => 'https://github.com/funkhaus/focushaus/archive/master.zip', 'version' => $latest_focushaus ) ); tgmpa( $plugins, $config ); } // Register required & recommended plugins add_action( 'tgmpa_register', 'vuehaus_register_required_plugins' ); function get_custom_template_routes(){ // Find all pages with custom_vuehaus_template set $args = array( 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'ASC', 'meta_key' => 'custom_vuehaus_template', 'meta_value' => '', 'post_type' => array('post', 'page') ); $all_pages_with_custom_templates = get_posts($args); // Filter out pages with vuehaus custom template set to Default $filtered_pages_with_custom_templates = array_filter( $all_pages_with_custom_templates, function( $page ){ return $page->custom_vuehaus_template !== 'Default'; } ); // Build out router for pages with custom templates $custom_template_routes = array(); foreach( $filtered_pages_with_custom_templates as $page ){ $page_url = get_permalink($page); $custom_template_routes[wp_make_link_relative($page_url)] = $page->custom_vuehaus_template; } return $custom_template_routes; }
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/functions/custom-vuehaus-templates.php
functions/custom-vuehaus-templates.php
<?php function get_custom_vuehaus_templates(){ // Add vuehaus template names to this array. // The user will be able to select any of these templates for any page on the site, overriding the default template. // If a name is in this array, it should exist as a Vue template in src/views as well, using the name as it appears in this list. return array( 'Default' ); }
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/functions/class-tgm-plugin-activation.php
functions/class-tgm-plugin-activation.php
<?php /** * Plugin installation and activation for WordPress themes. * * Please note that this is a drop-in library for a theme or plugin. * The authors of this library (Thomas, Gary and Juliette) are NOT responsible * for the support of your plugin or theme. Please contact the plugin * or theme author for support. * * @package TGM-Plugin-Activation * @version 2.6.1 * @link http://tgmpluginactivation.com/ * @author Thomas Griffin, Gary Jones, Juliette Reinders Folmer * @copyright Copyright (c) 2011, Thomas Griffin * @license GPL-2.0+ */ /* Copyright 2011 Thomas Griffin (thomasgriffinmedia.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ if ( ! class_exists( 'TGM_Plugin_Activation' ) ) { /** * Automatic plugin installation and activation library. * * Creates a way to automatically install and activate plugins from within themes. * The plugins can be either bundled, downloaded from the WordPress * Plugin Repository or downloaded from another external source. * * @since 1.0.0 * * @package TGM-Plugin-Activation * @author Thomas Griffin * @author Gary Jones */ class TGM_Plugin_Activation { /** * TGMPA version number. * * @since 2.5.0 * * @const string Version number. */ const TGMPA_VERSION = '2.6.1'; /** * Regular expression to test if a URL is a WP plugin repo URL. * * @const string Regex. * * @since 2.5.0 */ const WP_REPO_REGEX = '|^http[s]?://wordpress\.org/(?:extend/)?plugins/|'; /** * Arbitrary regular expression to test if a string starts with a URL. * * @const string Regex. * * @since 2.5.0 */ const IS_URL_REGEX = '|^http[s]?://|'; /** * Holds a copy of itself, so it can be referenced by the class name. * * @since 1.0.0 * * @var TGM_Plugin_Activation */ public static $instance; /** * Holds arrays of plugin details. * * @since 1.0.0 * @since 2.5.0 the array has the plugin slug as an associative key. * * @var array */ public $plugins = array(); /** * Holds arrays of plugin names to use to sort the plugins array. * * @since 2.5.0 * * @var array */ protected $sort_order = array(); /** * Whether any plugins have the 'force_activation' setting set to true. * * @since 2.5.0 * * @var bool */ protected $has_forced_activation = false; /** * Whether any plugins have the 'force_deactivation' setting set to true. * * @since 2.5.0 * * @var bool */ protected $has_forced_deactivation = false; /** * Name of the unique ID to hash notices. * * @since 2.4.0 * * @var string */ public $id = 'tgmpa'; /** * Name of the query-string argument for the admin page. * * @since 1.0.0 * * @var string */ protected $menu = 'tgmpa-install-plugins'; /** * Parent menu file slug. * * @since 2.5.0 * * @var string */ public $parent_slug = 'themes.php'; /** * Capability needed to view the plugin installation menu item. * * @since 2.5.0 * * @var string */ public $capability = 'edit_theme_options'; /** * Default absolute path to folder containing bundled plugin zip files. * * @since 2.0.0 * * @var string Absolute path prefix to zip file location for bundled plugins. Default is empty string. */ public $default_path = ''; /** * Flag to show admin notices or not. * * @since 2.1.0 * * @var boolean */ public $has_notices = true; /** * Flag to determine if the user can dismiss the notice nag. * * @since 2.4.0 * * @var boolean */ public $dismissable = true; /** * Message to be output above nag notice if dismissable is false. * * @since 2.4.0 * * @var string */ public $dismiss_msg = ''; /** * Flag to set automatic activation of plugins. Off by default. * * @since 2.2.0 * * @var boolean */ public $is_automatic = false; /** * Optional message to display before the plugins table. * * @since 2.2.0 * * @var string Message filtered by wp_kses_post(). Default is empty string. */ public $message = ''; /** * Holds configurable array of strings. * * Default values are added in the constructor. * * @since 2.0.0 * * @var array */ public $strings = array(); /** * Holds the version of WordPress. * * @since 2.4.0 * * @var int */ public $wp_version; /** * Holds the hook name for the admin page. * * @since 2.5.0 * * @var string */ public $page_hook; /** * Adds a reference of this object to $instance, populates default strings, * does the tgmpa_init action hook, and hooks in the interactions to init. * * {@internal This method should be `protected`, but as too many TGMPA implementations * haven't upgraded beyond v2.3.6 yet, this gives backward compatibility issues. * Reverted back to public for the time being.}} * * @since 1.0.0 * * @see TGM_Plugin_Activation::init() */ public function __construct() { // Set the current WordPress version. $this->wp_version = $GLOBALS['wp_version']; // Announce that the class is ready, and pass the object (for advanced use). do_action_ref_array( 'tgmpa_init', array( $this ) ); /* * Load our text domain and allow for overloading the fall-back file. * * {@internal IMPORTANT! If this code changes, review the regex in the custom TGMPA * generator on the website.}} */ add_action( 'init', array( $this, 'load_textdomain' ), 5 ); add_filter( 'load_textdomain_mofile', array( $this, 'overload_textdomain_mofile' ), 10, 2 ); // When the rest of WP has loaded, kick-start the rest of the class. add_action( 'init', array( $this, 'init' ) ); } /** * Magic method to (not) set protected properties from outside of this class. * * {@internal hackedihack... There is a serious bug in v2.3.2 - 2.3.6 where the `menu` property * is being assigned rather than tested in a conditional, effectively rendering it useless. * This 'hack' prevents this from happening.}} * * @see https://github.com/TGMPA/TGM-Plugin-Activation/blob/2.3.6/tgm-plugin-activation/class-tgm-plugin-activation.php#L1593 * * @since 2.5.2 * * @param string $name Name of an inaccessible property. * @param mixed $value Value to assign to the property. * @return void Silently fail to set the property when this is tried from outside of this class context. * (Inside this class context, the __set() method if not used as there is direct access.) */ public function __set( $name, $value ) { return; } /** * Magic method to get the value of a protected property outside of this class context. * * @since 2.5.2 * * @param string $name Name of an inaccessible property. * @return mixed The property value. */ public function __get( $name ) { return $this->{$name}; } /** * Initialise the interactions between this class and WordPress. * * Hooks in three new methods for the class: admin_menu, notices and styles. * * @since 2.0.0 * * @see TGM_Plugin_Activation::admin_menu() * @see TGM_Plugin_Activation::notices() * @see TGM_Plugin_Activation::styles() */ public function init() { /** * By default TGMPA only loads on the WP back-end and not in an Ajax call. Using this filter * you can overrule that behaviour. * * @since 2.5.0 * * @param bool $load Whether or not TGMPA should load. * Defaults to the return of `is_admin() && ! defined( 'DOING_AJAX' )`. */ if ( true !== apply_filters( 'tgmpa_load', ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) ) { return; } // Load class strings. $this->strings = array( 'page_title' => __( 'Install Required Plugins', 'tgmpa' ), 'menu_title' => __( 'Install Plugins', 'tgmpa' ), /* translators: %s: plugin name. */ 'installing' => __( 'Installing Plugin: %s', 'tgmpa' ), /* translators: %s: plugin name. */ 'updating' => __( 'Updating Plugin: %s', 'tgmpa' ), 'oops' => __( 'Something went wrong with the plugin API.', 'tgmpa' ), 'notice_can_install_required' => _n_noop( /* translators: 1: plugin name(s). */ 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.', 'tgmpa' ), 'notice_can_install_recommended' => _n_noop( /* translators: 1: plugin name(s). */ 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.', 'tgmpa' ), 'notice_ask_to_update' => _n_noop( /* translators: 1: plugin name(s). */ 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.', 'tgmpa' ), 'notice_ask_to_update_maybe' => _n_noop( /* translators: 1: plugin name(s). */ 'There is an update available for: %1$s.', 'There are updates available for the following plugins: %1$s.', 'tgmpa' ), 'notice_can_activate_required' => _n_noop( /* translators: 1: plugin name(s). */ 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.', 'tgmpa' ), 'notice_can_activate_recommended' => _n_noop( /* translators: 1: plugin name(s). */ 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.', 'tgmpa' ), 'install_link' => _n_noop( 'Begin installing plugin', 'Begin installing plugins', 'tgmpa' ), 'update_link' => _n_noop( 'Begin updating plugin', 'Begin updating plugins', 'tgmpa' ), 'activate_link' => _n_noop( 'Begin activating plugin', 'Begin activating plugins', 'tgmpa' ), 'return' => __( 'Return to Required Plugins Installer', 'tgmpa' ), 'dashboard' => __( 'Return to the Dashboard', 'tgmpa' ), 'plugin_activated' => __( 'Plugin activated successfully.', 'tgmpa' ), 'activated_successfully' => __( 'The following plugin was activated successfully:', 'tgmpa' ), /* translators: 1: plugin name. */ 'plugin_already_active' => __( 'No action taken. Plugin %1$s was already active.', 'tgmpa' ), /* translators: 1: plugin name. */ 'plugin_needs_higher_version' => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'tgmpa' ), /* translators: 1: dashboard link. */ 'complete' => __( 'All plugins installed and activated successfully. %1$s', 'tgmpa' ), 'dismiss' => __( 'Dismiss this notice', 'tgmpa' ), 'notice_cannot_install_activate' => __( 'There are one or more required or recommended plugins to install, update or activate.', 'tgmpa' ), 'contact_admin' => __( 'Please contact the administrator of this site for help.', 'tgmpa' ), ); do_action( 'tgmpa_register' ); /* After this point, the plugins should be registered and the configuration set. */ // Proceed only if we have plugins to handle. if ( empty( $this->plugins ) || ! is_array( $this->plugins ) ) { return; } // Set up the menu and notices if we still have outstanding actions. if ( true !== $this->is_tgmpa_complete() ) { // Sort the plugins. array_multisort( $this->sort_order, SORT_ASC, $this->plugins ); add_action( 'admin_menu', array( $this, 'admin_menu' ) ); add_action( 'admin_head', array( $this, 'dismiss' ) ); // Prevent the normal links from showing underneath a single install/update page. add_filter( 'install_plugin_complete_actions', array( $this, 'actions' ) ); add_filter( 'update_plugin_complete_actions', array( $this, 'actions' ) ); if ( $this->has_notices ) { add_action( 'admin_notices', array( $this, 'notices' ) ); add_action( 'admin_init', array( $this, 'admin_init' ), 1 ); add_action( 'admin_enqueue_scripts', array( $this, 'thickbox' ) ); } } // If needed, filter plugin action links. add_action( 'load-plugins.php', array( $this, 'add_plugin_action_link_filters' ), 1 ); // Make sure things get reset on switch theme. add_action( 'switch_theme', array( $this, 'flush_plugins_cache' ) ); if ( $this->has_notices ) { add_action( 'switch_theme', array( $this, 'update_dismiss' ) ); } // Setup the force activation hook. if ( true === $this->has_forced_activation ) { add_action( 'admin_init', array( $this, 'force_activation' ) ); } // Setup the force deactivation hook. if ( true === $this->has_forced_deactivation ) { add_action( 'switch_theme', array( $this, 'force_deactivation' ) ); } } /** * Load translations. * * @since 2.6.0 * * (@internal Uses `load_theme_textdomain()` rather than `load_plugin_textdomain()` to * get round the different ways of handling the path and deprecated notices being thrown * and such. For plugins, the actual file name will be corrected by a filter.}} * * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA * generator on the website.}} */ public function load_textdomain() { if ( is_textdomain_loaded( 'tgmpa' ) ) { return; } if ( false !== strpos( __FILE__, WP_PLUGIN_DIR ) || false !== strpos( __FILE__, WPMU_PLUGIN_DIR ) ) { // Plugin, we'll need to adjust the file name. add_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10, 2 ); load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' ); remove_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10 ); } else { load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' ); } } /** * Correct the .mo file name for (must-use) plugins. * * Themese use `/path/{locale}.mo` while plugins use `/path/{text-domain}-{locale}.mo`. * * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA * generator on the website.}} * * @since 2.6.0 * * @param string $mofile Full path to the target mofile. * @param string $domain The domain for which a language file is being loaded. * @return string $mofile */ public function correct_plugin_mofile( $mofile, $domain ) { // Exit early if not our domain (just in case). if ( 'tgmpa' !== $domain ) { return $mofile; } return preg_replace( '`/([a-z]{2}_[A-Z]{2}.mo)$`', '/tgmpa-$1', $mofile ); } /** * Potentially overload the fall-back translation file for the current language. * * WP, by default since WP 3.7, will load a local translation first and if none * can be found, will try and find a translation in the /wp-content/languages/ directory. * As this library is theme/plugin agnostic, translation files for TGMPA can exist both * in the WP_LANG_DIR /plugins/ subdirectory as well as in the /themes/ subdirectory. * * This method makes sure both directories are checked. * * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA * generator on the website.}} * * @since 2.6.0 * * @param string $mofile Full path to the target mofile. * @param string $domain The domain for which a language file is being loaded. * @return string $mofile */ public function overload_textdomain_mofile( $mofile, $domain ) { // Exit early if not our domain, not a WP_LANG_DIR load or if the file exists and is readable. if ( 'tgmpa' !== $domain || false === strpos( $mofile, WP_LANG_DIR ) || @is_readable( $mofile ) ) { return $mofile; } // Current fallback file is not valid, let's try the alternative option. if ( false !== strpos( $mofile, '/themes/' ) ) { return str_replace( '/themes/', '/plugins/', $mofile ); } elseif ( false !== strpos( $mofile, '/plugins/' ) ) { return str_replace( '/plugins/', '/themes/', $mofile ); } else { return $mofile; } } /** * Hook in plugin action link filters for the WP native plugins page. * * - Prevent activation of plugins which don't meet the minimum version requirements. * - Prevent deactivation of force-activated plugins. * - Add update notice if update available. * * @since 2.5.0 */ public function add_plugin_action_link_filters() { foreach ( $this->plugins as $slug => $plugin ) { if ( false === $this->can_plugin_activate( $slug ) ) { add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_activate' ), 20 ); } if ( true === $plugin['force_activation'] ) { add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_deactivate' ), 20 ); } if ( false !== $this->does_plugin_require_update( $slug ) ) { add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_update' ), 20 ); } } } /** * Remove the 'Activate' link on the WP native plugins page if the plugin does not meet the * minimum version requirements. * * @since 2.5.0 * * @param array $actions Action links. * @return array */ public function filter_plugin_action_links_activate( $actions ) { unset( $actions['activate'] ); return $actions; } /** * Remove the 'Deactivate' link on the WP native plugins page if the plugin has been set to force activate. * * @since 2.5.0 * * @param array $actions Action links. * @return array */ public function filter_plugin_action_links_deactivate( $actions ) { unset( $actions['deactivate'] ); return $actions; } /** * Add a 'Requires update' link on the WP native plugins page if the plugin does not meet the * minimum version requirements. * * @since 2.5.0 * * @param array $actions Action links. * @return array */ public function filter_plugin_action_links_update( $actions ) { $actions['update'] = sprintf( '<a href="%1$s" title="%2$s" class="edit">%3$s</a>', esc_url( $this->get_tgmpa_status_url( 'update' ) ), esc_attr__( 'This plugin needs to be updated to be compatible with your theme.', 'tgmpa' ), esc_html__( 'Update Required', 'tgmpa' ) ); return $actions; } /** * Handles calls to show plugin information via links in the notices. * * We get the links in the admin notices to point to the TGMPA page, rather * than the typical plugin-install.php file, so we can prepare everything * beforehand. * * WP does not make it easy to show the plugin information in the thickbox - * here we have to require a file that includes a function that does the * main work of displaying it, enqueue some styles, set up some globals and * finally call that function before exiting. * * Down right easy once you know how... * * Returns early if not the TGMPA page. * * @since 2.1.0 * * @global string $tab Used as iframe div class names, helps with styling * @global string $body_id Used as the iframe body ID, helps with styling * * @return null Returns early if not the TGMPA page. */ public function admin_init() { if ( ! $this->is_tgmpa_page() ) { return; } if ( isset( $_REQUEST['tab'] ) && 'plugin-information' === $_REQUEST['tab'] ) { // Needed for install_plugin_information(). require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; wp_enqueue_style( 'plugin-install' ); global $tab, $body_id; $body_id = 'plugin-information'; // @codingStandardsIgnoreStart $tab = 'plugin-information'; // @codingStandardsIgnoreEnd install_plugin_information(); exit; } } /** * Enqueue thickbox scripts/styles for plugin info. * * Thickbox is not automatically included on all admin pages, so we must * manually enqueue it for those pages. * * Thickbox is only loaded if the user has not dismissed the admin * notice or if there are any plugins left to install and activate. * * @since 2.1.0 */ public function thickbox() { if ( ! get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) { add_thickbox(); } } /** * Adds submenu page if there are plugin actions to take. * * This method adds the submenu page letting users know that a required * plugin needs to be installed. * * This page disappears once the plugin has been installed and activated. * * @since 1.0.0 * * @see TGM_Plugin_Activation::init() * @see TGM_Plugin_Activation::install_plugins_page() * * @return null Return early if user lacks capability to install a plugin. */ public function admin_menu() { // Make sure privileges are correct to see the page. if ( ! current_user_can( 'install_plugins' ) ) { return; } $args = apply_filters( 'tgmpa_admin_menu_args', array( 'parent_slug' => $this->parent_slug, // Parent Menu slug. 'page_title' => $this->strings['page_title'], // Page title. 'menu_title' => $this->strings['menu_title'], // Menu title. 'capability' => $this->capability, // Capability. 'menu_slug' => $this->menu, // Menu slug. 'function' => array( $this, 'install_plugins_page' ), // Callback. ) ); $this->add_admin_menu( $args ); } /** * Add the menu item. * * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA * generator on the website.}} * * @since 2.5.0 * * @param array $args Menu item configuration. */ protected function add_admin_menu( array $args ) { if ( has_filter( 'tgmpa_admin_menu_use_add_theme_page' ) ) { _deprecated_function( 'The "tgmpa_admin_menu_use_add_theme_page" filter', '2.5.0', esc_html__( 'Set the parent_slug config variable instead.', 'tgmpa' ) ); } if ( 'themes.php' === $this->parent_slug ) { $this->page_hook = call_user_func( 'add_theme_page', $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] ); } else { $this->page_hook = call_user_func( 'add_submenu_page', $args['parent_slug'], $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] ); } } /** * Echoes plugin installation form. * * This method is the callback for the admin_menu method function. * This displays the admin page and form area where the user can select to install and activate the plugin. * Aborts early if we're processing a plugin installation action. * * @since 1.0.0 * * @return null Aborts early if we're processing a plugin installation action. */ public function install_plugins_page() { // Store new instance of plugin table in object. $plugin_table = new TGMPA_List_Table; // Return early if processing a plugin installation action. if ( ( ( 'tgmpa-bulk-install' === $plugin_table->current_action() || 'tgmpa-bulk-update' === $plugin_table->current_action() ) && $plugin_table->process_bulk_actions() ) || $this->do_plugin_install() ) { return; } // Force refresh of available plugin information so we'll know about manual updates/deletes. wp_clean_plugins_cache( false ); ?> <div class="tgmpa wrap"> <h1><?php echo esc_html( get_admin_page_title() ); ?></h1> <?php $plugin_table->prepare_items(); ?> <?php if ( ! empty( $this->message ) && is_string( $this->message ) ) { echo wp_kses_post( $this->message ); } ?> <?php $plugin_table->views(); ?> <form id="tgmpa-plugins" action="" method="post"> <input type="hidden" name="tgmpa-page" value="<?php echo esc_attr( $this->menu ); ?>" /> <input type="hidden" name="plugin_status" value="<?php echo esc_attr( $plugin_table->view_context ); ?>" /> <?php $plugin_table->display(); ?> </form> </div> <?php } /** * Installs, updates or activates a plugin depending on the action link clicked by the user. * * Checks the $_GET variable to see which actions have been * passed and responds with the appropriate method. * * Uses WP_Filesystem to process and handle the plugin installation * method. * * @since 1.0.0 * * @uses WP_Filesystem * @uses WP_Error * @uses WP_Upgrader * @uses Plugin_Upgrader * @uses Plugin_Installer_Skin * @uses Plugin_Upgrader_Skin * * @return boolean True on success, false on failure. */ protected function do_plugin_install() { if ( empty( $_GET['plugin'] ) ) { return false; } // All plugin information will be stored in an array for processing. $slug = $this->sanitize_key( urldecode( $_GET['plugin'] ) ); if ( ! isset( $this->plugins[ $slug ] ) ) { return false; } // Was an install or upgrade action link clicked? if ( ( isset( $_GET['tgmpa-install'] ) && 'install-plugin' === $_GET['tgmpa-install'] ) || ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) ) { $install_type = 'install'; if ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) { $install_type = 'update'; } check_admin_referer( 'tgmpa-' . $install_type, 'tgmpa-nonce' ); // Pass necessary information via URL if WP_Filesystem is needed. $url = wp_nonce_url( add_query_arg( array( 'plugin' => urlencode( $slug ), 'tgmpa-' . $install_type => $install_type . '-plugin', ), $this->get_tgmpa_url() ), 'tgmpa-' . $install_type, 'tgmpa-nonce' ); $method = ''; // Leave blank so WP_Filesystem can populate it as necessary. if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, array() ) ) ) { return true; } if ( ! WP_Filesystem( $creds ) ) { request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, array() ); // Setup WP_Filesystem. return true; } /* If we arrive here, we have the filesystem. */ // Prep variables for Plugin_Installer_Skin class. $extra = array(); $extra['slug'] = $slug; // Needed for potentially renaming of directory name. $source = $this->get_download_url( $slug ); $api = ( 'repo' === $this->plugins[ $slug ]['source_type'] ) ? $this->get_plugins_api( $slug ) : null; $api = ( false !== $api ) ? $api : null; $url = add_query_arg( array( 'action' => $install_type . '-plugin', 'plugin' => urlencode( $slug ), ), 'update.php' ); if ( ! class_exists( 'Plugin_Upgrader', false ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; } $title = ( 'update' === $install_type ) ? $this->strings['updating'] : $this->strings['installing']; $skin_args = array( 'type' => ( 'bundled' !== $this->plugins[ $slug ]['source_type'] ) ? 'web' : 'upload', 'title' => sprintf( $title, $this->plugins[ $slug ]['name'] ), 'url' => esc_url_raw( $url ), 'nonce' => $install_type . '-plugin_' . $slug, 'plugin' => '', 'api' => $api, 'extra' => $extra, ); unset( $title ); if ( 'update' === $install_type ) { $skin_args['plugin'] = $this->plugins[ $slug ]['file_path']; $skin = new Plugin_Upgrader_Skin( $skin_args ); } else { $skin = new Plugin_Installer_Skin( $skin_args ); } // Create a new instance of Plugin_Upgrader. $upgrader = new Plugin_Upgrader( $skin ); // Perform the action and install the plugin from the $source urldecode(). add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 ); if ( 'update' === $install_type ) { // Inject our info into the update transient. $to_inject = array( $slug => $this->plugins[ $slug ] ); $to_inject[ $slug ]['source'] = $source; $this->inject_update_info( $to_inject ); $upgrader->upgrade( $this->plugins[ $slug ]['file_path'] ); } else { $upgrader->install( $source ); } remove_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1 ); // Make sure we have the correct file path now the plugin is installed/updated. $this->populate_file_path( $slug ); // Only activate plugins if the config option is set to true and the plugin isn't // already active (upgrade). if ( $this->is_automatic && ! $this->is_plugin_active( $slug ) ) { $plugin_activate = $upgrader->plugin_info(); // Grab the plugin info from the Plugin_Upgrader method. if ( false === $this->activate_single_plugin( $plugin_activate, $slug, true ) ) { return true; // Finish execution of the function early as we encountered an error. } } $this->show_tgmpa_version(); // Display message based on if all plugins are now active or not. if ( $this->is_tgmpa_complete() ) { echo '<p>', sprintf( esc_html( $this->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>' ), '</p>'; echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>'; } else { echo '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>'; } return true; } elseif ( isset( $this->plugins[ $slug ]['file_path'], $_GET['tgmpa-activate'] ) && 'activate-plugin' === $_GET['tgmpa-activate'] ) { // Activate action link was clicked. check_admin_referer( 'tgmpa-activate', 'tgmpa-nonce' ); if ( false === $this->activate_single_plugin( $this->plugins[ $slug ]['file_path'], $slug ) ) { return true; // Finish execution of the function early as we encountered an error. } } return false; } /** * Inject information into the 'update_plugins' site transient as WP checks that before running an update. * * @since 2.5.0 * * @param array $plugins The plugin information for the plugins which are to be updated. */ public function inject_update_info( $plugins ) { $repo_updates = get_site_transient( 'update_plugins' ); if ( ! is_object( $repo_updates ) ) { $repo_updates = new stdClass; } foreach ( $plugins as $slug => $plugin ) { $file_path = $plugin['file_path']; if ( empty( $repo_updates->response[ $file_path ] ) ) { $repo_updates->response[ $file_path ] = new stdClass; } // We only really need to set package, but let's do all we can in case WP changes something. $repo_updates->response[ $file_path ]->slug = $slug; $repo_updates->response[ $file_path ]->plugin = $file_path; $repo_updates->response[ $file_path ]->new_version = $plugin['version']; $repo_updates->response[ $file_path ]->package = $plugin['source']; if ( empty( $repo_updates->response[ $file_path ]->url ) && ! empty( $plugin['external_url'] ) ) { $repo_updates->response[ $file_path ]->url = $plugin['external_url']; } } set_site_transient( 'update_plugins', $repo_updates ); } /** * Adjust the plugin directory name if necessary. * * The final destination directory of a plugin is based on the subdirectory name found in the * (un)zipped source. In some cases - most notably GitHub repository plugin downloads -, this
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
true
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/functions/meta-boxes.php
functions/meta-boxes.php
<?php /* * Add custom metaboxes to the new/edit dashboard page */ function custom_add_metaboxes($post_type, $post){ add_meta_box('custom_media_meta', 'Media Meta', 'custom_media_meta', 'page', 'normal', 'low'); //add_meta_box('custom_second_featured_image', 'Second Featured Image', 'custom_second_featured_image', 'page', 'side', 'low'); } add_action('add_meta_boxes', 'custom_add_metaboxes', 10, 2); /* * Build media meta box */ function custom_media_meta($post) { // From functions/custom-vuehaus-templates.php $custom_vuehaus_templates = get_custom_vuehaus_templates(); ?> <div class="custom-meta"> <?php if( !empty($custom_vuehaus_templates) and count($custom_vuehaus_templates) > 1 ) : ?> <label for="custom-vuehaus-template">Select the custom template for this page:</label> <select id="custom-vuehaus-template" name="custom_vuehaus_template"> <?php foreach( $custom_vuehaus_templates as $template ) : ?> <option value="<?php echo $template; ?>" <?php selected($post->custom_vuehaus_template, $template); ?>><?php echo $template; ?></option> <?php endforeach; ?> </select> <br/> <?php endif; ?> <label for="video-url">Enter the video URL for this page:</label> <input id="video-url" class="short" title="This is needed for all video pages" name="custom_video_url" type="text" value="<?php echo $post->custom_video_url; ?>"> <br/> </div> <?php } /* * Second featured image uploader. * Requires changes to static/admin.js and to turn on admin enqueue script in wp-functions.php * @see: https://codex.wordpress.org/Javascript_Reference/wp.media */ function custom_second_featured_image($post){ // Meta key (need to update the save_metabox function below to reflect this too!) $meta_key = 'second_post_thumbnail'; // Get WordPress' media upload URL $upload_link = esc_url( get_upload_iframe_src( 'image', $post->ID ) ); // See if there's a media id already saved as post meta $image_id = get_post_meta( $post->ID, $meta_key, true ); // Get the image src $image_src = wp_get_attachment_image_src( $image_id, 'post-thumbnail' ); // For convenience, see if the array is valid $has_image = is_array( $image_src ); ?> <div class="custom-meta custom-image-uploader"> <!-- A hidden input to set and post the chosen image id --> <input class="custom-image-id" name="<?php echo $meta_key; ?>" type="hidden" value="<?php echo $image_id; ?>" /> <!-- Image container, which is manipulated with js --> <div class="custom-image-container"> <?php if ( $has_image ) : ?> <img src="<?php echo $image_src[0] ?>"/> <?php endif; ?> </div> <!-- Add & remove image links --> <p class="hide-if-no-js"> <a class="upload-custom-image <?php if ( $has_image ) { echo 'hidden'; } ?>" href="<?php echo $upload_link ?>"> <?php _e('Set second featured image') ?> </a> <a class="delete-custom-image <?php if ( ! $has_image ) { echo 'hidden'; } ?>" href="#"> <?php _e('Remove image') ?> </a> </p> </div> <?php } /* * Save metabox values */ function custom_save_metabox($post_id){ // check autosave if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) { return $post_id; } if( isset($_POST['custom_vuehaus_template']) ) { update_post_meta($post_id, 'custom_vuehaus_template', $_POST['custom_vuehaus_template']); } if( isset($_POST['custom_video_url']) ) { update_post_meta($post_id, 'custom_video_url', $_POST['custom_video_url']); } // if( isset($_POST['second_post_thumbnail']) ) { // update_post_meta($post_id, 'second_post_thumbnail', $_POST['second_post_thumbnail']); // } } add_action('save_post', 'custom_save_metabox'); /* * Add video URL metafield on attachments */ function custom_add_attachment_video_url( $fields, $post ) { $meta = get_post_meta( $post->ID, 'custom_video_url', true ); $fields['custom_video_url'] = array( 'label' => __( 'Video URL', 'text-domain' ), 'input' => 'text', 'value' => $meta, 'show_in_edit' => true, ); return $fields; } add_filter( 'attachment_fields_to_edit', 'custom_add_attachment_video_url', 10, 2 ); /* * Update media custom field when updating attachment */ function custom_update_attachment_video_url( $post_id = null ) { if( empty($post_id) and isset($_POST['id']) ) { $post_id = $_POST['id']; } if( isset( $_POST['attachments'][ $post_id ]['custom_video_url'] ) ) { update_post_meta( $post_id , 'custom_video_url', $_POST['attachments'][ $post_id ]['custom_video_url'] ); } clean_post_cache($post_id); return; } add_action( 'edit_attachment', 'custom_update_attachment_video_url', 1 ); add_action( 'wp_ajax_save-attachment-compat', 'custom_update_attachment_video_url', 0, 1 );
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/functions/shortcodes.php
functions/shortcodes.php
<?php /* * Translate shortcode to Vue components. * Use a new copy of this function for each shortcode supported in wp-content. * See the Readme.md file in this directory for more examples. * * @see https://codex.wordpress.org/Function_Reference/add_shortcode */ function custom_shortcode_function( $atts, $content = '', $name ) { // Include default props here extract(shortcode_atts(array( 'title' => '' ), $atts)); // Props to pass to Vue component $props = 'title="' . $title . '"'; $content = custom_filter_shortcode_text($content); return '<vue-component-name ' . $props . '>'. $content .'</vue-component-name>'; } //add_shortcode( 'shortcode-name', 'custom_shortcode_function' ); /* * Creates a an [svg-image] shortcode so a user can add SVGs into the editor correctly */ function add_svg_image_shortcode( $atts ) { extract(shortcode_atts(array( 'src' => '' ), $atts)); $props = 'src="' . $src . '"'; return '<svg-image ' . $props . '></svg-image>'; } //add_shortcode( 'svg-image', 'add_svg_image_shortcode' ); /** * Utility function to clean up the way WordPress auto formats text in a shortcode. * * @param string $text A stirng of HTML text */ function custom_filter_shortcode_text($text = '') { // Replace all the poorly formatted P tags that WP adds by default. $tags = array("<p>", "</p>"); $text = str_replace($tags, "\n", $text); // Remove any BR tags $tags = array("<br>", "<br/>", "<br />"); $text = str_replace($tags, "", $text); // Add back in the P and BR tags again, this will remove empty ones return apply_filters('the_content', $text); }
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/functions/rest-easy-filters.php
functions/rest-easy-filters.php
<?php /* * Custom Rest-Easy filters go in this file * You can see the documentation here: https://github.com/funkhaus/Rest-Easy * Common examples of filters to add in this file can be found here: https://github.com/funkhaus/vuehaus/tree/master/functions */ /** * Add dev_id to nav items as they are serialized * * @param array $input The nav item currently being processed by Rest-Easy */ function add_dev_id_to_nav_items($nav_item_data){ if ( isset($nav_item_data['id']) ) { // get full nav item $object_type = get_post_meta($nav_item_data['id'], '_menu_item_object', true); $object_id = get_post_meta($nav_item_data['id'], '_menu_item_object_id', true); // if nav item is a page, add Dev ID if ( $object_type == 'page' ) { $nav_item_data['devId'] = get_post_meta($object_id, 'custom_developer_id', true); } } return $nav_item_data; } add_filter('rez_serialize_nav_item', 'add_dev_id_to_nav_items'); /* * Serialize ACF content with get_field to respect ACF custom formatting */ function serialize_custom_acf_content($post_data){ // check to make sure we have ACF installed if (!function_exists('get_fields')){ return $post_data; } // get ACF fields attached to target post $acf_fields = get_fields($post_data['id']); // prep to save serialized fields $post_data['acf'] = array(); if( !empty($acf_fields) ){ // serialize ACF fields foreach( $acf_fields as $name => $value ){ $post_data['acf'][$name] = $value; } } return $post_data; } add_filter('rez_serialize_post', 'serialize_custom_acf_content'); /* * Add Focushaus focal point and Funky-Colors colors to ACF images */ function add_focal_point_to_acf_images($target){ if( function_exists('get_offset_x') ){ $target['focus'] = array( 'x' => get_offset_x( $target['ID'] ), 'y' => get_offset_y( $target['ID'] ) ); } if( function_exists('get_primary_image_color') ){ $target['primary_color'] = get_primary_image_color($target['ID']); $target['secondary_color'] = get_second_image_color($target['ID']); } $image['videoSrc'] = $target->custom_video_url; return $target; } add_filter('acf/format_value/type=image', 'add_focal_point_to_acf_images', 20, 4); /* * Add Focushaus focal point and Funky-Colors colors to ACF gallery images */ function add_image_data_to_acf_galleries($value){ foreach ($value as $index => &$image) { $target_post = get_post($image['id']); if( function_exists('get_offset_x') ){ $image['focus'] = array( 'x' => get_offset_x( $image['id'] ), 'y' => get_offset_y( $image['id'] ) ); } if( function_exists('get_primary_image_color') ){ $image['primary_color'] = get_primary_image_color($image['id']); $image['secondary_color'] = get_second_image_color($image['id']); } // add video to gallery image $image['meta']['custom_video_url'] = $target_post->custom_video_url; } return $value; } add_filter('acf/format_value/type=gallery', 'add_image_data_to_acf_galleries', 20, 4); /** * Add pages with dev ID to site data * * @param array $input The nav item currently being processed by Rest-Easy */ function add_dev_page_links_to_site_data($site_data){ $args = array( 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'ASC', // get all non-empty custom_developer_id pages 'meta_query' => array( array( 'key' => 'custom_developer_id', 'value' => array(''), 'compare' => 'NOT IN' ) ), 'post_type' => 'page', ); $posts_array = get_posts( $args ); $site_data['devIds'] = array(); foreach($posts_array as $dev_id_page){ $key = $dev_id_page->custom_developer_id; $site_data['devIds'][$key] = wp_make_link_relative(get_permalink($dev_id_page)); } return $site_data; } add_filter('rez_build_site_data', 'add_dev_page_links_to_site_data'); /** * Serialize page siblings * * @param array $input The post currently being processed by Rest-Easy */ // NOTE: This is a common Rest-Easy filter, but including it by default can slow // down load times on large sites. Uncomment to use, but it's best to // include some extra checks so this doesn't run on every page. // function add_page_siblings($related, $target = null){ // $target = get_post($target); // $args = array( // 'posts_per_page' => -1, // 'orderby' => 'menu_order', // 'order' => 'ASC', // 'exclude' => array( $target->ID ), // 'post_type' => 'page', // 'post_parent' => $target->post_parent // ); // $siblings = get_posts($args); // // // apply the serialize_object filter to all siblings // $related['siblings'] = array_map( // function ($sibling) { return apply_filters('rez_serialize_object', $sibling); }, // $siblings // ); // // // return modified data // return $related; // } // add_filter('rez_gather_related', 'add_page_siblings', 10, 2); // Add theme options to site data // function add_theme_options_to_site($site_data){ // if ( function_exists('the_field') ){ // $site_data['themeOptions'] = array( // 'singleText' => get_field('single_text', 'option'), // 'multilineText' => explode("\n", get_field('multiline_text', 'option')), // ); // } // return $site_data; // } // add_filter('rez_build_site_data', 'add_theme_options_to_site'); // Adds adjacent posts when they are unset due to recent bug in wordpress. //function add_adjacent_posts($related, $post = null) { // if (is_null($related['next']) && is_null($related['prev'])) { // $prev = get_posts(array( // 'post_type' => 'post', // 'posts_per_page' => 1, // 'date_query' => array( // 'after' => $post->post_date // ) // )); // $next = get_posts(array( // 'post_type' => 'post', // 'posts_per_page' => 1, // 'date_query' => array( // 'before' => $post->post_date // ) // )); // if (count($next) > 0){ // $related['next'] = apply_filters('rez_serialize_object', $next[0]); // } // if (count($prev) > 0){ // $related['prev'] = apply_filters('rez_serialize_object', $prev[0]); // } // } // return $related; // } // add_filter('rez_gather_related', 'add_adjacent_posts', 10, 2); /** * Add WP-Shopify options to site data * * @param array $site_data The site data currently being processed by Rest-Easy */ function add_wps_options_to_site_data($site_data){ if ( function_exists('get_wshop_domain') ){ $site_data['storefrontToken'] = get_wshop_api_key(); $site_data['shopifyDomain'] = get_wshop_domain(); } return $site_data; } add_filter('rez_build_site_data', 'add_wps_options_to_site_data'); /** * Add next posts link to site data for infinite scroll * * @param array $site_data The site data currently being processed by Rest-Easy */ function add_next_post_page_link($input) { $input['meta']['next_post_link'] = next_posts(0, false); return $input; } add_filter('rez_build_site_data', 'add_next_post_page_link');
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/functions/wp-functions.php
functions/wp-functions.php
<?php /* * Setup WordPress */ function custom_wordpress_setup() { // Enable tags for Pages (@see: https://wordpress.org/support/topic/enable-tags-screen-for-pages#post-29500520 //register_taxonomy_for_object_type('post_tag', 'page'); // Enable excerpts for pages add_post_type_support('page', 'excerpt'); } add_action('init', 'custom_wordpress_setup'); /* * Set custom page title */ function alter_wordpress_title( $title, $sep ) { return get_bloginfo('name') . $title; } add_filter('wp_title', 'alter_wordpress_title', 10, 2); /* * Setup theme */ function custom_theme_setup() { // Turn on menus add_theme_support('menus'); // Enable HTML5 support add_theme_support('html5'); } add_action( 'after_setup_theme', 'custom_theme_setup' ); /* * Enqueue any Custom Admin Scripts */ function custom_admin_scripts() { //wp_register_script('site-admin', get_template_directory_uri() . '/static/js/admin.js', 'jquery', custom_latest_timestamp()); //wp_enqueue_script('site-admin'); } //add_action( 'admin_enqueue_scripts', 'custom_admin_scripts' ); /* * Enqueue Custom Scripts */ function custom_scripts() { $has_bundle = file_exists(get_template_directory() . '/static/bundle.js'); $has_dev_bundle = file_exists(get_template_directory() . '/static/bundle.dev.js'); // if WP_DEBUG is on, prefer dev bundle but fallback to prod // do the opposite when WP_DEBUG is off. $bundle_path = $has_bundle ? '/static/bundle.js' : '/static/bundle.dev.js'; if ( WP_DEBUG ){ $bundle_path = $has_dev_bundle ? '/static/bundle.dev.js' : '/static/bundle.js'; } // Enqueue proper bundle wp_enqueue_script('bundle', get_template_directory_uri() . $bundle_path, null, custom_latest_timestamp(), true); } add_action('wp_enqueue_scripts', 'custom_scripts', 10); /* * Convenience function to generate timestamp based on latest edits. Used to automate cache updating */ function custom_latest_timestamp() { // set base, find top level assets of static dir $base = get_template_directory(); $assets = array_merge(glob($base . '/static/*.js'), glob($base . '/static/*.css')); // get m time of each asset $stamps = array_map(function($path){ return filemtime($path); }, $assets); // if valid return time of latest change, otherwise current time return rsort($stamps) ? reset($stamps) : time(); } /* * Style login page and dashboard */ // Style the login page function custom_loginpage_logo_link($url) { // Return a url; in this case the homepage url of wordpress return get_bloginfo('url'); } function custom_loginpage_logo_title($message) { // Return title text for the logo to replace 'wordpress'; in this case, the blog name. return get_bloginfo('name'); } function custom_loginpage_styles() { wp_enqueue_style( 'login_css', get_template_directory_uri() . '/static/css/login.css' ); } function custom_admin_styles() { wp_enqueue_style('admin-stylesheet', get_template_directory_uri() . '/static/css/admin.css'); } add_filter('login_headerurl','custom_loginpage_logo_link'); add_filter('login_headertitle','custom_loginpage_logo_title'); add_action('login_head','custom_loginpage_styles'); add_action('admin_print_styles', 'custom_admin_styles'); /* * Add post thumbnail into RSS feed */ function rss_post_thumbnail($content) { global $post; if( has_post_thumbnail($post->ID) ) { $content = '<p><a href='.get_permalink($post->ID).'>'.get_the_post_thumbnail($post->ID).'</a></p>'.$content; } return $content; } add_filter('the_excerpt_rss', 'rss_post_thumbnail'); /* * Custom conditional function. Used to get the parent and all it's child. */ function is_tree($tree_id, $target_post = null) { // get full post object $target_post = get_post($target_post); // get all post ancestors $ancestors = get_ancestors($target_post->ID, $target_post->post_type); // if ID is target post OR in target post tree, return true return ( ($target_post->ID == $tree_id) or in_array($tree_id, $ancestors) ); } /* * Allow SVG uploads */ function add_mime_types($mimes) { $mimes['svg'] = 'image/svg+xml'; return $mimes; } //add_filter('upload_mimes', 'add_mime_types'); /* * Allow subscriber to see Private posts/pages */ function add_theme_caps() { // Gets the author role $role = get_role('subscriber'); // Add capabilities $role->add_cap('read_private_posts'); $role->add_cap('read_private_pages'); } //add_action( 'switch_theme', 'add_theme_caps'); /* * Change the [...] that comes after excerpts */ function custom_excerpt_ellipsis( $more ) { return '...'; } add_filter('excerpt_more', 'custom_excerpt_ellipsis'); /* * Add Google Analytics tracking settings to admin dashboard */ function my_general_section() { add_settings_section( 'vh_google_analytics_section', // Section ID 'Google Analytics Tracking IDs', // Section Title 'vh_google_analytics_section', // Callback 'general' // This makes the section show up on the General Settings Page ); add_settings_field( 'ga_tracking_code_1', // Option ID 'Tracking ID #1', // Label 'vh_google_analytics_settings', // !important - This is where the args go! 'general', // Page it will be displayed (General Settings) 'vh_google_analytics_section', // Name of our section array( 'ga_tracking_code_1' // Should match Option ID ) ); add_settings_field( 'ga_tracking_code_2', // Option ID 'Tracking ID #2', // Label 'vh_google_analytics_settings', // !important - This is where the args go! 'general', // Page it will be displayed (General Settings) 'vh_google_analytics_section', // Name of our section array( 'ga_tracking_code_2' // Should match Option ID ) ); register_setting('general','ga_tracking_code_1', 'esc_attr'); register_setting('general','ga_tracking_code_2', 'esc_attr'); } add_action('admin_init', 'my_general_section'); /* * Settings callbacks that build the Analytics markup */ function vh_google_analytics_section() { echo '<p>Enter Google Analytics tracking codes. Uses the <code>gtag.js</code> tracking method.</p>'; } function vh_google_analytics_settings($args) { $option = get_option($args[0]); echo '<input type="text" id="'. $args[0] .'" name="'. $args[0] .'" value="' . $option . '" placeholder="UA-12345678-1"/>'; } /* * Add theme options page */ // if( function_exists('acf_add_options_page') ) { // acf_add_options_page(array( // 'page_title' => 'Theme Settings', // 'menu_title' => 'Theme Settings', // 'menu_slug' => 'theme-settings' // )); // }
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/functions/blocks.php
functions/blocks.php
<?php /* * This file handles the custom Gutenberg blocks for this theme */ function register_vuehaus_blocks(){ // Ignore if Gutenberg isn't installed if( !function_exists('register_block_type') ) return; // Prep custom blocks wp_register_script( 'vuehaus-block-registration', get_template_directory_uri() . '/blocks/dist/blocks.js', array( 'wp-blocks', 'wp-element' ) ); // Prep block styling wp_register_style( 'vuehaus-block-style', get_template_directory_uri() . '/blocks/dist/blocks.css', array( ) ); // Register all blocks register_block_type( 'vuehaus-blocks/vuehaus-blocks', array( 'style' => 'vuehaus-block-style', 'editor_script' => 'vuehaus-block-registration', ) ); // Add this theme to the custom block categories add_filter( 'block_categories', function( $categories ) { return array_merge( $categories, array( array( 'slug' => 'custom-fh', 'title' => __( get_bloginfo('name') ), ), ) ); }, 10, 2 ); } add_action('admin_init', 'register_vuehaus_blocks');
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
funkhaus/vuehaus
https://github.com/funkhaus/vuehaus/blob/79638013d2a1395b07512a545cd7a22f7d62112c/functions/router.php
functions/router.php
<?php /* * Add vue.js router to rest-easy data */ function add_routes_to_json($jsonData){ // Get the name of the category base. Default to "categories" $category_base = get_option('category_base'); if( empty($category_base) ){ $category_base = 'category'; } // build out router table to be used with Vue $programmed_routes = array( // Per-site // '/path' => 'VueComponent', // '/path/:var' => 'ComponentWithVar' // '/path/*/:var' => 'WildcardAndVar' // path_from_dev_id('dev-id') => 'DefinedByDevId', // path_from_dev_id('dev-id', '/append-me') => 'DevIdPathPlusAppendedString', /* // Common Funkhaus setups // Directors - redirect to first child path_from_dev_id('directors') => array( 'redirect' => get_child_of_dev_id_path('directors') ), // Director detail path_from_dev_id('directors', '/:director') => 'DirectorDetail', // Reel grid path_from_dev_id('directors', '/:director/:reel') => 'ReelGrid', // Video detail path_from_dev_id('directors', '/:director/:reel/:video') => 'VideoDetail', // About path_from_dev_id('about') => 'About', // Contact path_from_dev_id('contact') => 'Contact', // Contact region - redirect to parent path_from_dev_id('contact', '/:region') => array( 'redirect' => path_from_dev_id('contact') ), */ // Probably unchanging '' => 'FrontPage', '/' . $category_base => 'Archive', '/(\\d+)/:slug' => array( 'name' => 'SinglePost', 'component' => 'Default' ), // If Permalinks set to "/%post_id%/%postname%/" then this will be a single Blog post '*' => array( 'name' => 'Fallback', 'component' => 'Default' ) ); $jsonData['routes'] = array_merge( get_custom_template_routes(), $programmed_routes ); return $jsonData; } add_filter('rez_build_all_data', 'add_routes_to_json');
php
MIT
79638013d2a1395b07512a545cd7a22f7d62112c
2026-01-05T04:56:39.601097Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/server.php
server.php
<?php $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $uri = urldecode($uri); $paths = require __DIR__.'/bootstrap/paths.php'; $requested = $paths['public'].$uri; // This file allows us to emulate Apache's "mod_rewrite" functionality from the // built-in PHP web server. This provides a convenient way to test a Laravel // application without having installed a "real" web server software here. if ($uri !== '/' and file_exists($requested)) { return false; } require_once $paths['public'].'/index.php';
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/routes.php
app/routes.php
<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ Route::get('/', function() { $data = array(); if (Auth::check()) { $data = Auth::user(); } return View::make('user', array('data'=>$data)); }); Route::get('login/fb', function() { $facebook = new Facebook(Config::get('facebook')); $params = array( 'redirect_uri' => url('/login/fb/callback'), 'scope' => 'email', ); return Redirect::to($facebook->getLoginUrl($params)); }); Route::get('login/fb/callback', function() { $code = Input::get('code'); if (strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with Facebook'); $facebook = new Facebook(Config::get('facebook')); $uid = $facebook->getUser(); if ($uid == 0) return Redirect::to('/')->with('message', 'There was an error'); $me = $facebook->api('/me'); $profile = Profile::whereUid($uid)->first(); if (empty($profile)) { $user = new User; $user->name = $me['first_name'].' '.$me['last_name']; $user->email = $me['email']; $user->photo = 'https://graph.facebook.com/'.$me['id'].'/picture?type=large'; $user->save(); $profile = new Profile(); $profile->uid = $uid; $profile->username = $me['id']; $profile = $user->profiles()->save($profile); } $profile->access_token = $facebook->getAccessToken(); $profile->save(); $user = $profile->user; Auth::login($user); return Redirect::to('/')->with('message', 'Logged in with Facebook'); }); Route::get('logout', function() { Auth::logout(); return Redirect::to('/'); });
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/filters.php
app/filters.php
<?php /* |-------------------------------------------------------------------------- | Application & Route Filters |-------------------------------------------------------------------------- | | Below you will find the "before" and "after" events for the application | which may be used to do any work before or after a request into your | application. Here you may also register your custom route filters. | */ App::before(function($request) { // }); App::after(function($request, $response) { // }); /* |-------------------------------------------------------------------------- | Authentication Filters |-------------------------------------------------------------------------- | | The following filters are used to verify that the user of the current | session is logged into this application. The "basic" filter easily | integrates HTTP Basic authentication for quick, simple checking. | */ Route::filter('auth', function() { if (Auth::guest()) return Redirect::guest('login'); }); Route::filter('auth.basic', function() { return Auth::basic(); }); /* |-------------------------------------------------------------------------- | Guest Filter |-------------------------------------------------------------------------- | | The "guest" filter is the counterpart of the authentication filters as | it simply checks that the current user is not logged in. A redirect | response will be issued if they are, which you may freely change. | */ Route::filter('guest', function() { if (Auth::check()) return Redirect::to('/'); }); /* |-------------------------------------------------------------------------- | CSRF Protection Filter |-------------------------------------------------------------------------- | | The CSRF filter is responsible for protecting your application against | cross-site request forgery attacks. If this special token in a user | session does not match the one given in this request, we'll bail. | */ Route::filter('csrf', function() { if (Session::token() != Input::get('_token')) { throw new Illuminate\Session\TokenMismatchException; } });
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/lang/en/reminders.php
app/lang/en/reminders.php
<?php return array( /* |-------------------------------------------------------------------------- | Password Reminder Language Lines |-------------------------------------------------------------------------- | | The following language lines are the default lines which match reasons | that are given by the password broker for a password update attempt | has failed, such as for an invalid token or invalid new password. | */ "password" => "Passwords must be six characters and match the confirmation.", "user" => "We can't find a user with that e-mail address.", "token" => "This password reset token is invalid.", );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/lang/en/pagination.php
app/lang/en/pagination.php
<?php return array( /* |-------------------------------------------------------------------------- | Pagination Language Lines |-------------------------------------------------------------------------- | | The following language lines are used by the paginator library to build | the simple pagination links. You are free to change them to anything | you want to customize your views to better match your application. | */ 'previous' => '&laquo; Previous', 'next' => 'Next &raquo;', );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/lang/en/validation.php
app/lang/en/validation.php
<?php return array( /* |-------------------------------------------------------------------------- | Validation Language Lines |-------------------------------------------------------------------------- | | The following language lines contain the default error messages used by | the validator class. Some of these rules have multiple versions such | such as the size rules. Feel free to tweak each of these messages. | */ "accepted" => "The :attribute must be accepted.", "active_url" => "The :attribute is not a valid URL.", "after" => "The :attribute must be a date after :date.", "alpha" => "The :attribute may only contain letters.", "alpha_dash" => "The :attribute may only contain letters, numbers, and dashes.", "alpha_num" => "The :attribute may only contain letters and numbers.", "array" => "The :attribute must be an array.", "before" => "The :attribute must be a date before :date.", "between" => array( "numeric" => "The :attribute must be between :min - :max.", "file" => "The :attribute must be between :min - :max kilobytes.", "string" => "The :attribute must be between :min - :max characters.", "array" => "The :attribute must have between :min - :max items.", ), "confirmed" => "The :attribute confirmation does not match.", "date" => "The :attribute is not a valid date.", "date_format" => "The :attribute does not match the format :format.", "different" => "The :attribute and :other must be different.", "digits" => "The :attribute must be :digits digits.", "digits_between" => "The :attribute must be between :min and :max digits.", "email" => "The :attribute format is invalid.", "exists" => "The selected :attribute is invalid.", "image" => "The :attribute must be an image.", "in" => "The selected :attribute is invalid.", "integer" => "The :attribute must be an integer.", "ip" => "The :attribute must be a valid IP address.", "max" => array( "numeric" => "The :attribute may not be greater than :max.", "file" => "The :attribute may not be greater than :max kilobytes.", "string" => "The :attribute may not be greater than :max characters.", "array" => "The :attribute may not have more than :max items.", ), "mimes" => "The :attribute must be a file of type: :values.", "min" => array( "numeric" => "The :attribute must be at least :min.", "file" => "The :attribute must be at least :min kilobytes.", "string" => "The :attribute must be at least :min characters.", "array" => "The :attribute must have at least :min items.", ), "not_in" => "The selected :attribute is invalid.", "numeric" => "The :attribute must be a number.", "regex" => "The :attribute format is invalid.", "required" => "The :attribute field is required.", "required_if" => "The :attribute field is required when :other is :value.", "required_with" => "The :attribute field is required when :values is present.", "required_without" => "The :attribute field is required when :values is not present.", "same" => "The :attribute and :other must match.", "size" => array( "numeric" => "The :attribute must be :size.", "file" => "The :attribute must be :size kilobytes.", "string" => "The :attribute must be :size characters.", "array" => "The :attribute must contain :size items.", ), "unique" => "The :attribute has already been taken.", "url" => "The :attribute format is invalid.", /* |-------------------------------------------------------------------------- | Custom Validation Language Lines |-------------------------------------------------------------------------- | | Here you may specify custom validation messages for attributes using the | convention "attribute.rule" to name the lines. This makes it quick to | specify a specific custom language line for a given attribute rule. | */ 'custom' => array(), /* |-------------------------------------------------------------------------- | Custom Validation Attributes |-------------------------------------------------------------------------- | | The following language lines are used to swap attribute place-holders | with something more reader friendly such as E-Mail Address instead | of "email". This simply helps us make messages a little cleaner. | */ 'attributes' => array(), );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/tests/TestCase.php
app/tests/TestCase.php
<?php class TestCase extends Illuminate\Foundation\Testing\TestCase { /** * Creates the application. * * @return Symfony\Component\HttpKernel\HttpKernelInterface */ public function createApplication() { $unitTesting = true; $testEnvironment = 'testing'; return require __DIR__.'/../../bootstrap/start.php'; } }
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/tests/ExampleTest.php
app/tests/ExampleTest.php
<?php class ExampleTest extends TestCase { /** * A basic functional test example. * * @return void */ public function testBasicExample() { $crawler = $this->client->request('GET', '/'); $this->assertTrue($this->client->getResponse()->isOk()); } }
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/controllers/HomeController.php
app/controllers/HomeController.php
<?php class HomeController extends BaseController { /* |-------------------------------------------------------------------------- | Default Home Controller |-------------------------------------------------------------------------- | | You may wish to use controllers instead of, or in addition to, Closure | based routes. That's great! Here is an example controller method to | get you started. To route to this controller, just add the route: | | Route::get('/', 'HomeController@showWelcome'); | */ public function showWelcome() { return View::make('hello'); } }
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/controllers/BaseController.php
app/controllers/BaseController.php
<?php class BaseController extends Controller { /** * Setup the layout used by the controller. * * @return void */ protected function setupLayout() { if ( ! is_null($this->layout)) { $this->layout = View::make($this->layout); } } }
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/models/Profile.php
app/models/Profile.php
<?php class Profile extends Eloquent { public function user() { return $this->belongsTo('User'); } }
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/models/User.php
app/models/User.php
<?php use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableInterface; class User extends Eloquent implements UserInterface, RemindableInterface { /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = array('password'); /** * Get the unique identifier for the user. * * @return mixed */ public function getAuthIdentifier() { return $this->getKey(); } /** * Get the password for the user. * * @return string */ public function getAuthPassword() { return $this->password; } /** * Get the e-mail address where password reminders are sent. * * @return string */ public function getReminderEmail() { return $this->email; } public function getRememberToken() { return $this->remember_token; } public function setRememberToken($value) { $this->remember_token = $value; } public function getRememberTokenName() { return 'remember_token'; } public function profiles() { return $this->hasMany('Profile'); } }
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/views/user.blade.php
app/views/user.blade.php
@extends('layouts/layout') @section('content') @if(Session::has('message')) <div class="alert alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> {{ Session::get('message')}} </div> @endif @if (!empty($data)) <div class="media"> <a class="pull-left" href="#"> <img class="media-object" src="{{ $data['photo']}}" alt="Profile image"> </a> <div class="media-body"> <h4 class="media-heading">{{{ $data['name'] }}} </h4> Your email is {{ $data['email']}} </div> </div> <hr> <a href="{{url('logout')}}">Logout</a> @else <div class="jumbotron"> <h1>Facebook login example</h1> <p>Created by <a href="http://twitter.com/msurguy" target="_blank">Maks</a></p> <p class="text-center"> <a class="btn btn-lg btn-primary" href="{{url('login/fb')}}"><i class="icon-facebook"></i> Login with Facebook</a> </p> </div> @endif @stop
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/views/emails/auth/reminder.blade.php
app/views/emails/auth/reminder.blade.php
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> </head> <body> <h2>Password Reset</h2> <div> To reset your password, complete this form: {{ URL::to('password/reset', array($token)) }}. </div> </body> </html>
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/views/layouts/layout.blade.php
app/views/layouts/layout.blade.php
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Facebook integration for Laravel"> <meta name="author" content="Maks Surguy @msurguy"> <title>Laravel and Facebook integration</title> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/css/bootstrap.min.css"> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css"> <style type="text/css"> body { padding: 30px; } .navbar { margin-bottom: 30px; } </style> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.6.2/html5shiv.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.2.0/respond.js"></script> <![endif]--> </head> <body> <a href="https://github.com/msurguy/laravel-facebook-login" target="_blank"><img style="position: absolute; top: 0; left: 0; border: 0; z-index: 100000;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_darkblue_121621.png" alt="Fork me on GitHub"></a> <div class="container"> <!-- Static navbar --> <div class="navbar navbar-default"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="http://maxoffsky.com">Laravel App</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="{{url('/')}}">Home</a></li> <li><a href="http://maxoffsky.com/code-blog/integrating-facebook-login-into-laravel-application/" target="_blank">Tutorial</a></li> </ul> @if(Auth::check()) <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Your Profile <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="{{url('logout')}}">Logout</a></li> </ul> </li> </ul> @endif </div><!--/.nav-collapse --> </div> <!-- Main component for a primary marketing message or call to action --> @yield('content') </div> <!-- /container --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/js/bootstrap.min.js"></script> </body> </html>
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/start/local.php
app/start/local.php
<?php //
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/start/artisan.php
app/start/artisan.php
<?php /* |-------------------------------------------------------------------------- | Register The Artisan Commands |-------------------------------------------------------------------------- | | Each available Artisan command must be registered with the console so | that it is available to be called. We'll register every command so | the console gets access to each of the command object instances. | */
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/start/global.php
app/start/global.php
<?php /* |-------------------------------------------------------------------------- | Register The Laravel Class Loader |-------------------------------------------------------------------------- | | In addition to using Composer, you may use the Laravel class loader to | load your controllers and models. This is useful for keeping all of | your classes in the "global" namespace without Composer updating. | */ ClassLoader::addDirectories(array( app_path().'/commands', app_path().'/controllers', app_path().'/models', app_path().'/database/seeds', )); /* |-------------------------------------------------------------------------- | Application Error Logger |-------------------------------------------------------------------------- | | Here we will configure the error logger setup for the application which | is built on top of the wonderful Monolog library. By default we will | build a rotating log file setup which creates a new file each day. | */ $logFile = 'log-'.php_sapi_name().'.txt'; Log::useDailyFiles(storage_path().'/logs/'.$logFile); /* |-------------------------------------------------------------------------- | Application Error Handler |-------------------------------------------------------------------------- | | Here you may handle any errors that occur in your application, including | logging them or displaying custom views for specific errors. You may | even register several error handlers to handle different types of | exceptions. If nothing is returned, the default error view is | shown, which includes a detailed stack trace during debug. | */ App::error(function(Exception $exception, $code) { Log::error($exception); }); /* |-------------------------------------------------------------------------- | Maintenance Mode Handler |-------------------------------------------------------------------------- | | The "down" Artisan command gives you the ability to put an application | into maintenance mode. Here, you will define what is displayed back | to the user if maintenace mode is in effect for this application. | */ App::down(function() { return Response::make("Be right back!", 503); }); /* |-------------------------------------------------------------------------- | Require The Filters File |-------------------------------------------------------------------------- | | Next we will load the filters file for the application. This gives us | a nice separate location to store our route and application filter | definitions instead of putting them all in the main routes file. | */ require app_path().'/filters.php';
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/workbench.php
app/config/workbench.php
<?php return array( /* |-------------------------------------------------------------------------- | Workbench Author Name |-------------------------------------------------------------------------- | | When you create new packages via the Artisan "workbench" command your | name is needed to generate the composer.json file for your package. | You may specify it now so it is used for all of your workbenches. | */ 'name' => '', /* |-------------------------------------------------------------------------- | Workbench Author E-Mail Address |-------------------------------------------------------------------------- | | Like the option above, your e-mail address is used when generating new | workbench packages. The e-mail is placed in your composer.json file | automatically after the package is created by the workbench tool. | */ 'email' => '', );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/app.php
app/config/app.php
<?php return array( /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => false, /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => 'http://localhost', /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => 'ZmWZbFcYTpupnFpm0PuiV1VRJlQrlRDX', 'cipher' => MCRYPT_RIJNDAEL_256, /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => array( 'Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', 'Illuminate\Cache\CacheServiceProvider', 'Illuminate\Foundation\Providers\CommandCreatorServiceProvider', 'Illuminate\Session\CommandsServiceProvider', 'Illuminate\Foundation\Providers\ComposerServiceProvider', 'Illuminate\Routing\ControllerServiceProvider', 'Illuminate\Cookie\CookieServiceProvider', 'Illuminate\Database\DatabaseServiceProvider', 'Illuminate\Encryption\EncryptionServiceProvider', 'Illuminate\Filesystem\FilesystemServiceProvider', 'Illuminate\Hashing\HashServiceProvider', 'Illuminate\Html\HtmlServiceProvider', 'Illuminate\Foundation\Providers\KeyGeneratorServiceProvider', 'Illuminate\Log\LogServiceProvider', 'Illuminate\Mail\MailServiceProvider', 'Illuminate\Foundation\Providers\MaintenanceServiceProvider', 'Illuminate\Database\MigrationServiceProvider', 'Illuminate\Foundation\Providers\OptimizeServiceProvider', 'Illuminate\Pagination\PaginationServiceProvider', 'Illuminate\Foundation\Providers\PublisherServiceProvider', 'Illuminate\Queue\QueueServiceProvider', 'Illuminate\Redis\RedisServiceProvider', 'Illuminate\Auth\Reminders\ReminderServiceProvider', 'Illuminate\Foundation\Providers\RouteListServiceProvider', 'Illuminate\Database\SeedServiceProvider', 'Illuminate\Foundation\Providers\ServerServiceProvider', 'Illuminate\Session\SessionServiceProvider', 'Illuminate\Foundation\Providers\TinkerServiceProvider', 'Illuminate\Translation\TranslationServiceProvider', 'Illuminate\Validation\ValidationServiceProvider', 'Illuminate\View\ViewServiceProvider', 'Illuminate\Workbench\WorkbenchServiceProvider', ), /* |-------------------------------------------------------------------------- | Service Provider Manifest |-------------------------------------------------------------------------- | | The service provider manifest is used by Laravel to lazy load service | providers which are not needed for each request, as well to keep a | list of all of the services. Here, you may set its storage spot. | */ 'manifest' => storage_path().'/meta', /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => array( 'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan', 'Auth' => 'Illuminate\Support\Facades\Auth', 'Blade' => 'Illuminate\Support\Facades\Blade', 'Cache' => 'Illuminate\Support\Facades\Cache', 'ClassLoader' => 'Illuminate\Support\ClassLoader', 'Config' => 'Illuminate\Support\Facades\Config', 'Controller' => 'Illuminate\Routing\Controllers\Controller', 'Cookie' => 'Illuminate\Support\Facades\Cookie', 'Crypt' => 'Illuminate\Support\Facades\Crypt', 'DB' => 'Illuminate\Support\Facades\DB', 'Eloquent' => 'Illuminate\Database\Eloquent\Model', 'Event' => 'Illuminate\Support\Facades\Event', 'File' => 'Illuminate\Support\Facades\File', 'Form' => 'Illuminate\Support\Facades\Form', 'Hash' => 'Illuminate\Support\Facades\Hash', 'HTML' => 'Illuminate\Support\Facades\HTML', 'Input' => 'Illuminate\Support\Facades\Input', 'Lang' => 'Illuminate\Support\Facades\Lang', 'Log' => 'Illuminate\Support\Facades\Log', 'Mail' => 'Illuminate\Support\Facades\Mail', 'Paginator' => 'Illuminate\Support\Facades\Paginator', 'Password' => 'Illuminate\Support\Facades\Password', 'Queue' => 'Illuminate\Support\Facades\Queue', 'Redirect' => 'Illuminate\Support\Facades\Redirect', 'Redis' => 'Illuminate\Support\Facades\Redis', 'Request' => 'Illuminate\Support\Facades\Request', 'Response' => 'Illuminate\Support\Facades\Response', 'Route' => 'Illuminate\Support\Facades\Route', 'Schema' => 'Illuminate\Support\Facades\Schema', 'Seeder' => 'Illuminate\Database\Seeder', 'Session' => 'Illuminate\Support\Facades\Session', 'Str' => 'Illuminate\Support\Str', 'URL' => 'Illuminate\Support\Facades\URL', 'Validator' => 'Illuminate\Support\Facades\Validator', 'View' => 'Illuminate\Support\Facades\View', ), );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/session.php
app/config/session.php
<?php return array( /* |-------------------------------------------------------------------------- | Default Session Driver |-------------------------------------------------------------------------- | | This option controls the default session "driver" that will be used on | requests. By default, we will use the lightweight native driver but | you may specify any of the other wonderful drivers provided here. | | Supported: "native", "cookie", "database", "apc", | "memcached", "redis", "array" | */ 'driver' => 'redis', /* |-------------------------------------------------------------------------- | Session Lifetime |-------------------------------------------------------------------------- | | Here you may specify the number of minutes that you wish the session | to be allowed to remain idle before it expires. If you want them | to immediately expire when the browser closes, set it to zero. | */ 'lifetime' => 120, /* |-------------------------------------------------------------------------- | Session File Location |-------------------------------------------------------------------------- | | When using the native session driver, we need a location where session | files may be stored. A default has been set for you but a different | location may be specified. This is only needed for file sessions. | */ 'files' => storage_path().'/sessions', /* |-------------------------------------------------------------------------- | Session Database Connection |-------------------------------------------------------------------------- | | When using the "database" session driver, you may specify the database | connection that should be used to manage your sessions. This should | correspond to a connection in your "database" configuration file. | */ 'connection' => null, /* |-------------------------------------------------------------------------- | Session Database Table |-------------------------------------------------------------------------- | | When using the "database" session driver, you may specify the table we | should use to manage the sessions. Of course, a sensible default is | provided for you; however, you are free to change this as needed. | */ 'table' => 'sessions', /* |-------------------------------------------------------------------------- | Session Sweeping Lottery |-------------------------------------------------------------------------- | | Some session drivers must manually sweep their storage location to get | rid of old sessions from storage. Here are the chances that it will | happen on a given request. By default, the odds are 2 out of 100. | */ 'lottery' => array(2, 100), /* |-------------------------------------------------------------------------- | Session Cookie Name |-------------------------------------------------------------------------- | | Here you may change the name of the cookie used to identify a session | instance by ID. The name specified here will get used every time a | new session cookie is created by the framework for every driver. | */ 'cookie' => 'laravel_session', /* |-------------------------------------------------------------------------- | Session Cookie Path |-------------------------------------------------------------------------- | | The session cookie path determines the path for which the cookie will | be regarded as available. Typically, this will be the root path of | your application but you are free to change this when necessary. | */ 'path' => '/', 'expire_on_close' => false, /* |-------------------------------------------------------------------------- | Session Cookie Domain |-------------------------------------------------------------------------- | | Here you may change the domain of the cookie used to identify a session | in your application. This will determine which domains the cookie is | available to in your application. A sensible default has been set. | */ 'domain' => null, );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/queue.php
app/config/queue.php
<?php return array( /* |-------------------------------------------------------------------------- | Default Queue Driver |-------------------------------------------------------------------------- | | The Laravel queue API supports a variety of back-ends via an unified | API, giving you convenient access to each back-end using the same | syntax for each one. Here you may set the default queue driver. | | Supported: "sync", "beanstalkd", "sqs", "iron" | */ 'default' => 'sync', /* |-------------------------------------------------------------------------- | Queue Connections |-------------------------------------------------------------------------- | | Here you may configure the connection information for each server that | is used by your application. A default configuration has been added | for each back-end shipped with Laravel. You are free to add more. | */ 'connections' => array( 'sync' => array( 'driver' => 'sync', ), 'beanstalkd' => array( 'driver' => 'beanstalkd', 'host' => 'localhost', 'queue' => 'default', ), 'sqs' => array( 'driver' => 'sqs', 'key' => 'your-public-key', 'secret' => 'your-secret-key', 'queue' => 'your-queue-url', 'region' => 'us-east-1', ), 'iron' => array( 'driver' => 'iron', 'project' => 'your-project-id', 'token' => 'your-token', 'queue' => 'your-queue-name', ), ), );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/cache.php
app/config/cache.php
<?php return array( /* |-------------------------------------------------------------------------- | Default Cache Driver |-------------------------------------------------------------------------- | | This option controls the default cache "driver" that will be used when | using the Caching library. Of course, you may use other drivers any | time you wish. This is the default when another is not specified. | | Supported: "file", "database", "apc", "memcached", "redis", "array" | */ 'driver' => 'redis', /* |-------------------------------------------------------------------------- | File Cache Location |-------------------------------------------------------------------------- | | When using the "file" cache driver, we need a location where the cache | files may be stored. A sensible default has been specified, but you | are free to change it to any other place on disk that you desire. | */ 'path' => storage_path().'/cache', /* |-------------------------------------------------------------------------- | Database Cache Connection |-------------------------------------------------------------------------- | | When using the "database" cache driver you may specify the connection | that should be used to store the cached items. When this option is | null the default database connection will be utilized for cache. | */ 'connection' => null, /* |-------------------------------------------------------------------------- | Database Cache Table |-------------------------------------------------------------------------- | | When using the "database" cache driver we need to know the table that | should be used to store the cached items. A default table name has | been provided but you're free to change it however you deem fit. | */ 'table' => 'cache', /* |-------------------------------------------------------------------------- | Memcached Servers |-------------------------------------------------------------------------- | | Now you may specify an array of your Memcached servers that should be | used when utilizing the Memcached cache driver. All of the servers | should contain a value for "host", "port", and "weight" options. | */ 'memcached' => array( array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 100), ), /* |-------------------------------------------------------------------------- | Cache Key Prefix |-------------------------------------------------------------------------- | | When utilizing a RAM based store such as APC or Memcached, there might | be other applications utilizing the same cache. So, we'll specify a | value to get prefixed to all our keys so we can avoid collisions. | */ 'prefix' => 'laravel', );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false