4
0
mirror of https://github.com/AzuraCast/AzuraCast.git synced 2024-06-17 22:47:04 +00:00

Playin with Phalcon some more. Initial structure.

This commit is contained in:
Buster Silver 2015-01-02 02:16:54 -06:00
parent 0c384f3326
commit 7220df0e85
320 changed files with 23452 additions and 23020 deletions

View File

@ -1,3 +0,0 @@
<?php
namespace DF;
class Exception extends \Exception {}

View File

@ -1,3 +0,0 @@
<?php
namespace DF\Exception;
class NotLoggedIn extends \Exception {}

View File

@ -1,3 +0,0 @@
<?php
namespace DF\Exception;
class Severe extends \Exception {}

View File

@ -1,3 +0,0 @@
<?php
namespace DF\Exception;
class Warning extends \Exception {}

View File

@ -1,5 +0,0 @@
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]
</IfModule>

117
phalcon/app/bootstrap.php Normal file
View File

@ -0,0 +1,117 @@
<?php
/**
* Global bootstrap file.
*/
// Security settings
define('DF_IS_COMMAND_LINE', (PHP_SAPI == "cli"));
define("DF_IS_SECURE", (!DF_IS_COMMAND_LINE && (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on")) ? TRUE : FALSE);
// General includes
define("DF_INCLUDE_BASE", dirname(__FILE__));
define("DF_INCLUDE_ROOT", realpath(DF_INCLUDE_BASE.'/..'));
define("DF_INCLUDE_WEB", DF_INCLUDE_ROOT.'/web');
define("DF_INCLUDE_APP", DF_INCLUDE_BASE);
define("DF_INCLUDE_MODULES", DF_INCLUDE_ROOT.'/modules');
define("DF_INCLUDE_MODELS", DF_INCLUDE_BASE.'/models');
define("DF_INCLUDE_STATIC", DF_INCLUDE_WEB.'/static');
define("DF_INCLUDE_TEMP", DF_INCLUDE_ROOT.'/../www_tmp');
define("DF_INCLUDE_CACHE", DF_INCLUDE_TEMP.'/cache');
define("DF_INCLUDE_LIB", DF_INCLUDE_ROOT.'/library');
define("DF_INCLUDE_VENDOR", DF_INCLUDE_ROOT.'/../vendor');
define("DF_UPLOAD_FOLDER", DF_INCLUDE_STATIC);
// Self-reference to current script.
if (isset($_SERVER['REQUEST_URI']))
define("DF_THIS_PAGE", reset(explode("?", $_SERVER['REQUEST_URI'])));
else
define("DF_THIS_PAGE", '');
// Application environment.
define('DF_APPLICATION_ENV_PATH', DF_INCLUDE_BASE.DIRECTORY_SEPARATOR.'.env');
if (!defined('DF_APPLICATION_ENV'))
define('DF_APPLICATION_ENV', ($env = @file_get_contents(DF_APPLICATION_ENV_PATH)) ? trim($env) : 'development');
// Set error reporting for the bootstrapping process.
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
// Set include paths.
set_include_path(implode(PATH_SEPARATOR, $include_path));
// Composer autoload.
$autoloader = require(DF_INCLUDE_VENDOR.DIRECTORY_SEPARATOR.'autoload.php');
// Save configuration object.
require(DF_INCLUDE_LIB.'/DF/Config.php');
$config = new \DF\Config(DF_INCLUDE_ROOT.'/config');
$config->preload(array('application','general'));
// Loop through modules to find configuration files or libraries.
$module_config_dirs = array();
$modules = scandir(DF_INCLUDE_MODULES);
foreach($modules as $module)
{
if ($module == '.' || $module == '..')
continue;
$config_directory = DF_INCLUDE_MODULES.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.'config';
if (file_exists($config_directory))
$module_config[$module] = new \DF\Config($config_directory);
}
$autoload_classes = $config->application->autoload->toArray();
foreach($autoload_classes['psr0'] as $class_key => $class_dir)
$autoloader->add($class_key, $class_dir);
foreach($autoload_classes['psr4'] as $class_key => $class_dir)
$autoloader->addPsr4($class_key, $class_dir);
// Initialize the ZendFramework Application Bootstrapper.
// $application = new \Zend_Application('application', $config->application);
// $application->getBootstrap();
// Bootstrap the DB for the following options.
// TODO
//$application->bootstrap('doctrine');
// $em = \Zend_Registry::get('em');
// \DF\Doctrine\Session\SaveHandler::register($em);
// PVL-specific customization.
$system_tz = \PVL\Customization::get('timezone');
@date_default_timezone_set($system_tz);
$di = new \Phalcon\DI\FactoryDefault();
$di['router'] = function() {
$router = require DF_INCLUDE_BASE.'/routes.php';
return $router;
};
// Configs
$di['config'] = $config;
$di['module_config'] = $module_config;
// Auth and ACL
$di->setShared('auth', '\DF\Auth\Model');
$di->setShared('acl', '\DF\Acl\Instance');
$di->setShared('cache', '\DF\Cache');
// Register URL handler.
$di->set('url', function() {
$url = new \Phalcon\Mvc\Url();
return $url;
});
// Register session.
$di->set('session', function() {
$session = new \Phalcon\Session\Adapter\Files();
$session->start();
return $session;
});
return $di;

20
phalcon/app/routes.php Normal file
View File

@ -0,0 +1,20 @@
<?php
$router = new \Phalcon\Mvc\Router(true);
$router->add('/admin', array(
'module' => 'backend',
'controller' => 'index',
'action' => 'index'
));
$router->add('/index', array(
'module' => 'frontend',
'controller' => 'index',
'action' => 'index'
));
$router->add('/', array(
'module' => 'frontend',
'controller' => 'index',
'action' => 'index'
));
return $router;

View File

@ -0,0 +1,122 @@
<?php
/**
* Configuration for PVL Third-Party APIs.
*/
return array(
// PVL deployment API sent by this application.
'pvl_api_key' => '52e067cbb156ea70b15a95b9501d0b61',
// PVL deployment API keys accepted by this application.
'pvl_api_keys' => array(
'PVLAPIAccess_20140605', // 52e067cbb156ea70b15a95b9501d0b61
),
// PVLNode Live update service locations.
'pvlnode_local_url' => 'http://localhost:4001/data',
'pvlnode_remote_url' => 'dev.pvlive.me',
'pvlnode_remote_path' => '/dev/live',
// Mandrill SMTP service.
'smtp' => array(
'server' => 'smtp.mandrillapp.com',
'port' => '587',
'auth' => 'login',
'username' => 'loobalightdark@gmail.com',
'password' => 'd05MxdhMxGxq7i8HRh8_mg',
),
// Google Common APIs server key (get from https://console.developers.google.com/)
'google_apis_key' => 'AIzaSyCQkwi2pVjtmV4ZXgobsbyQcZYEkOZY9c4',
// Twitter API settings.
'twitter' => array(
'consumer_key' => 'dekLAskiLF8nrTZI3zmmg',
'consumer_secret' => 'J6OaNpKHlDmrQLEmvxfdlRWO4E7WbyNnBTdpz1njLcw',
'user_token' => '974916638-1jK4vgMYvv9pAc2gQfAYGcnDY58xTij5M42P93VU',
'user_secret' => 'TTDLFrhcULlU3a9uYxIbdW5DZxx4TsCfOlf9sWuVlY4',
'curl_ssl_verifyhost' => 0,
'curl_ssl_verifypeer' => false,
),
// Notifico settings.
'notifico_push_url' => 'http://n.tkte.ch/h/3254/6XP7inz2mdedPggNN8oeWpaU',
// Hybrid/oAuth API settings.
'hybrid_auth' => array(
'base_url' => \DF\Url::baseUrl(TRUE),
// Enable debug mode (specify "debug_file" below).
'debug_mode' => false,
'debug_file' => '',
'providers' => array (
"OpenID" => array (
"enabled" => true
),
"Google" => array (
"enabled" => true,
"keys" => array(
"id" => "722497886984.apps.googleusercontent.com",
"secret" => "d8SDY90qkWddYFSRamKe40zq",
),
),
"Facebook" => array (
"enabled" => true,
"keys" => array(
"id" => "507310642670190",
"secret" => "c4481c738c8e3a86eb9fa9838f4bc8b8"
),
"scope" => "email, user_about_me", // optional
),
"Twitter" => array (
"enabled" => true,
"keys" => array(
"key" => "dekLAskiLF8nrTZI3zmmg",
"secret" => "J6OaNpKHlDmrQLEmvxfdlRWO4E7WbyNnBTdpz1njLcw",
),
),
"Tumblr" => array (
"enabled" => true,
"keys" => array(
"key" => "Hp1W4lpJ0dhHA7pOGih0yow02ZXAFHdiIR5bzFS67C0xlERPAZ",
"secret" => "Nr3gbtyd5N0maCC1rx3GJ6K7I7wAOxYM7nfYbLnhS2bYIqbtOg"
),
),
"Poniverse" => array(
"enabled" => true,
"keys" => array(
"id" => 'B0H3Z647MoD4qg047i2Io87Jq77ydcdC',
"secret" => '8R1aX5G88QMUU848gDluzxcC14Hec1S7',
),
),
),
),
// CentovaCast API settings.
'centovacast' => array(
// IP or hostname of the CentovaCast server.
'host' => '162.243.167.103',
'db_user' => 'centova',
'db_pass' => 'MZpXJhfv',
'db_name' => 'centova',
// Time zone to use when submitting requests.
'timezone' => 'US/Eastern',
),
// ReCAPTCHA Service keys.
'recaptcha' => array(
'public_key' => '6LfE7eASAAAAADg6R11mHJaFdiGKj_KNB55kB-A4',
'private_key' => '6LfE7eASAAAAAIH3Wn8LUhEUihib4uO2qDxg64n7',
),
);

View File

@ -1,120 +1,120 @@
<?php
/**
* Configuration for PVL Third-Party APIs.
*/
return array(
// PVL deployment API sent by this application. Contact PVL lead developer for info.
'pvl_api_key' => '',
// PVL deployment API keys accepted by this application.
'pvl_api_keys' => array(),
// PVLNode Live update service locations.
'pvlnode_local_url' => 'http://localhost:4001/data',
'pvlnode_remote_url' => 'http://dev.pvlive.me/',
'pvlnode_remote_path' => '/api/live',
// Mandrill SMTP service.
'smtp' => array(
'server' => 'smtp.mandrillapp.com',
'port' => '587',
'auth' => 'login',
'username' => '',
'password' => '',
),
// Google Common APIs server key (get from https://console.developers.google.com/)
'google_apis_key' => '',
// Twitter API settings.
'twitter' => array(
'consumer_key' => '',
'consumer_secret' => '',
'user_token' => '',
'user_secret' => '',
'curl_ssl_verifyhost' => 0,
'curl_ssl_verifypeer' => false,
),
// Notifico settings.
'notifico_push_url' => '',
// Hybrid/oAuth API settings.
'hybrid_auth' => array(
'base_url' => \DF\Url::baseUrl(),
// Enable debug mode (specify "debug_file" below).
'debug_mode' => false,
'debug_file' => '',
'providers' => array (
"OpenID" => array (
"enabled" => true
),
"Google" => array (
"enabled" => true,
"keys" => array(
"id" => "",
"secret" => "",
),
),
"Facebook" => array (
"enabled" => true,
"keys" => array(
"id" => "",
"secret" => ""
),
"scope" => "email, user_about_me", // optional
),
"Twitter" => array (
"enabled" => true,
"keys" => array(
"key" => "",
"secret" => "",
),
),
"Tumblr" => array (
"enabled" => true,
"keys" => array(
"key" => "",
"secret" => ""
),
),
"Poniverse" => array(
"enabled" => true,
"keys" => array(
"id" => '',
"secret" => '',
),
),
),
),
// CentovaCast API settings.
'centovacast' => array(
// IP or hostname of the CentovaCast server.
'host' => '198.27.112.218',
'db_user' => 'centova',
'db_pass' => '',
'db_name' => 'centova',
// Time zone to use when submitting requests.
'timezone' => 'US/Eastern',
),
// ReCAPTCHA Service keys.
'recaptcha' => array(
'public_key' => '',
'private_key' => '',
),
<?php
/**
* Configuration for PVL Third-Party APIs.
*/
return array(
// PVL deployment API sent by this application. Contact PVL lead developer for info.
'pvl_api_key' => '',
// PVL deployment API keys accepted by this application.
'pvl_api_keys' => array(),
// PVLNode Live update service locations.
'pvlnode_local_url' => 'http://localhost:4001/data',
'pvlnode_remote_url' => 'http://dev.pvlive.me/',
'pvlnode_remote_path' => '/api/live',
// Mandrill SMTP service.
'smtp' => array(
'server' => 'smtp.mandrillapp.com',
'port' => '587',
'auth' => 'login',
'username' => '',
'password' => '',
),
// Google Common APIs server key (get from https://console.developers.google.com/)
'google_apis_key' => '',
// Twitter API settings.
'twitter' => array(
'consumer_key' => '',
'consumer_secret' => '',
'user_token' => '',
'user_secret' => '',
'curl_ssl_verifyhost' => 0,
'curl_ssl_verifypeer' => false,
),
// Notifico settings.
'notifico_push_url' => '',
// Hybrid/oAuth API settings.
'hybrid_auth' => array(
'base_url' => \DF\Url::baseUrl(),
// Enable debug mode (specify "debug_file" below).
'debug_mode' => false,
'debug_file' => '',
'providers' => array (
"OpenID" => array (
"enabled" => true
),
"Google" => array (
"enabled" => true,
"keys" => array(
"id" => "",
"secret" => "",
),
),
"Facebook" => array (
"enabled" => true,
"keys" => array(
"id" => "",
"secret" => ""
),
"scope" => "email, user_about_me", // optional
),
"Twitter" => array (
"enabled" => true,
"keys" => array(
"key" => "",
"secret" => "",
),
),
"Tumblr" => array (
"enabled" => true,
"keys" => array(
"key" => "",
"secret" => ""
),
),
"Poniverse" => array(
"enabled" => true,
"keys" => array(
"id" => '',
"secret" => '',
),
),
),
),
// CentovaCast API settings.
'centovacast' => array(
// IP or hostname of the CentovaCast server.
'host' => '198.27.112.218',
'db_user' => 'centova',
'db_pass' => '',
'db_name' => 'centova',
// Time zone to use when submitting requests.
'timezone' => 'US/Eastern',
),
// ReCAPTCHA Service keys.
'recaptcha' => array(
'public_key' => '',
'private_key' => '',
),
);

View File

@ -1,120 +1,120 @@
<?php
/**
* Application Settings
*/
$session_lifetime = 86400*4;
$config = array(
// Application name
'name' => 'Ponyville Live!',
'analytics_code' => 'UA-37359273-1',
// Primary application web address
'base_url' => '//'.($_SERVER["HTTP_HOST"] ? $_SERVER["HTTP_HOST"] : 'ponyvillelive.com'),
// DF Messenger mail settings
'mail' => array(
'templates' => DF_INCLUDE_BASE.'/messages',
'from_addr' => 'info@ponyvillelive.com',
'from_name' => 'Ponyville Live!',
'use_smtp' => true,
),
'phpSettings' => array(
'display_startup_errors' => 0,
'display_errors' => 0,
'log_errors' => 1,
'error_log' => DF_INCLUDE_TEMP.'/php_errors.log',
'error_reporting' => E_ALL & ~E_NOTICE & ~E_WARNING & ~E_STRICT,
'session' => array(
'use_only_cookies' => 1,
'save_path' => DF_INCLUDE_TEMP.DIRECTORY_SEPARATOR.'sessions',
'gc_maxlifetime' => $session_lifetime,
'gc_probability' => 1,
'gc_divisor' => 100,
'cookie_lifetime' => $session_lifetime,
'hash_function' => 'sha512',
'hash_bits_per_character' => 4,
),
),
'bootstrap' => array(
'path' => 'DF/Application/Bootstrap.php',
'class' => '\DF\Application\Bootstrap',
),
'includePaths' => array(
DF_INCLUDE_LIB.'/ThirdParty',
),
'pluginpaths' => array(
'DF\Application\Resource\\' => 'DF/Application/Resource',
),
'autoload' => array(
'psr0' => array(
'DF' => DF_INCLUDE_LIB,
'PVL' => DF_INCLUDE_LIB,
'Entity' => DF_INCLUDE_MODELS,
'Hybrid' => DF_INCLUDE_LIB.'/ThirdParty',
'Hybrid_' => DF_INCLUDE_LIB.'/ThirdParty/Hybrid',
'tmhOAuth' => DF_INCLUDE_LIB.'/ThirdParty',
),
'psr4' => array(
'\\Proxy\\' => DF_INCLUDE_TEMP.'/proxies',
),
),
'resources' => array(
/* RESOURCES: Locale */
'locale' => array(
'default' => 'en_US',
),
/* RESOURCES: Front Controller */
'frontController' => array(
'throwerrors' => true,
'moduleDirectory' => DF_INCLUDE_MODULES,
'moduleControllerDirectoryName' => "controllers",
'defaultModule' => "default",
'defaultAction' => "index",
'defaultControllerName' => "index",
),
/* RESOURCES: Doctrine ORM Layer */
'doctrine' => array(
'autoGenerateProxies' => (DF_APPLICATION_ENV == "development"),
'proxyNamespace' => 'Proxy',
'proxyPath' => DF_INCLUDE_TEMP.'/proxies',
'modelPath' => DF_INCLUDE_MODELS,
),
/* RESOURCES: Menu */
'menu' => array(
'enabled' => true,
),
/* RESOURCES: Layout */
'layout' => array(
'layout' => 'default',
'layoutPath' => DF_INCLUDE_APP.'/layouts',
'commonTemplates' => DF_INCLUDE_BASE.'/common',
),
),
);
/**
* Development mode changes.
*/
if (DF_APPLICATION_ENV != 'production')
{
$config['phpSettings']['display_startup_errors'] = 1;
$config['phpSettings']['display_errors'] = 1;
// Update if your local configuration differs.
$config['base_url'] = '//dev.pvlive.me';
}
return $config;
<?php
/**
* Application Settings
*/
$session_lifetime = 86400*4;
$config = array(
// Application name
'name' => 'Ponyville Live!',
'analytics_code' => 'UA-37359273-1',
// Primary application web address
'base_url' => '//'.($_SERVER["HTTP_HOST"] ? $_SERVER["HTTP_HOST"] : 'ponyvillelive.com'),
// DF Messenger mail settings
'mail' => array(
'templates' => DF_INCLUDE_BASE.'/messages',
'from_addr' => 'info@ponyvillelive.com',
'from_name' => 'Ponyville Live!',
'use_smtp' => true,
),
'phpSettings' => array(
'display_startup_errors' => 0,
'display_errors' => 0,
'log_errors' => 1,
'error_log' => DF_INCLUDE_TEMP.'/php_errors.log',
'error_reporting' => E_ALL & ~E_NOTICE & ~E_WARNING & ~E_STRICT,
'session' => array(
'use_only_cookies' => 1,
'save_path' => DF_INCLUDE_TEMP.DIRECTORY_SEPARATOR.'sessions',
'gc_maxlifetime' => $session_lifetime,
'gc_probability' => 1,
'gc_divisor' => 100,
'cookie_lifetime' => $session_lifetime,
'hash_function' => 'sha512',
'hash_bits_per_character' => 4,
),
),
'bootstrap' => array(
'path' => 'DF/Application/Bootstrap.php',
'class' => '\DF\Application\Bootstrap',
),
'includePaths' => array(
DF_INCLUDE_LIB.'/ThirdParty',
),
'pluginpaths' => array(
'DF\Application\Resource\\' => 'DF/Application/Resource',
),
'autoload' => array(
'psr0' => array(
'DF' => DF_INCLUDE_LIB,
'PVL' => DF_INCLUDE_LIB,
'Entity' => DF_INCLUDE_MODELS,
'Hybrid' => DF_INCLUDE_LIB.'/ThirdParty',
'Hybrid_' => DF_INCLUDE_LIB.'/ThirdParty/Hybrid',
'tmhOAuth' => DF_INCLUDE_LIB.'/ThirdParty',
),
'psr4' => array(
'\\Proxy\\' => DF_INCLUDE_TEMP.'/proxies',
),
),
'resources' => array(
/* RESOURCES: Locale */
'locale' => array(
'default' => 'en_US',
),
/* RESOURCES: Front Controller */
'frontController' => array(
'throwerrors' => true,
'moduleDirectory' => DF_INCLUDE_MODULES,
'moduleControllerDirectoryName' => "controllers",
'defaultModule' => "default",
'defaultAction' => "index",
'defaultControllerName' => "index",
),
/* RESOURCES: Doctrine ORM Layer */
'doctrine' => array(
'autoGenerateProxies' => (DF_APPLICATION_ENV == "development"),
'proxyNamespace' => 'Proxy',
'proxyPath' => DF_INCLUDE_TEMP.'/proxies',
'modelPath' => DF_INCLUDE_MODELS,
),
/* RESOURCES: Menu */
'menu' => array(
'enabled' => true,
),
/* RESOURCES: Layout */
'layout' => array(
'layout' => 'default',
'layoutPath' => DF_INCLUDE_APP.'/layouts',
'commonTemplates' => DF_INCLUDE_BASE.'/common',
),
),
);
/**
* Development mode changes.
*/
if (DF_APPLICATION_ENV != 'production')
{
$config['phpSettings']['display_startup_errors'] = 1;
$config['phpSettings']['display_errors'] = 1;
// Update if your local configuration differs.
$config['base_url'] = '//dev.pvlive.me';
}
return $config;

View File

@ -0,0 +1,29 @@
<?php
/**
* Database configuration and credentials.
*/
return array(
// Backend driver to use with the database.
'driver' => 'pdo_mysql',
// Host or IP to connect to (default: localhost).
'host' => 'localhost',
// Name of the primary application database.
'dbname' => 'pvl',
// Username for the database user with read/write access to the above database.
'user' => 'root',
// Password for the user account specified above.
'password' => 'password',
// Character set.
'charset' => 'utf8',
// Other options to send to the PDO adapter for the database.
'driverOptions' => array(
1002 => 'SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci',
),
);

View File

@ -1,29 +1,29 @@
<?php
/**
* Database configuration and credentials.
*/
return array(
// Backend driver to use with the database.
'driver' => 'pdo_mysql',
// Host or IP to connect to (default: localhost).
'host' => 'localhost',
// Name of the primary application database.
'dbname' => 'pvl',
// Username for the database user with read/write access to the above database.
'user' => 'root',
// Password for the user account specified above.
'password' => 'password',
// Character set.
'charset' => 'utf8',
// Other options to send to the PDO adapter for the database.
'driverOptions' => array(
1002 => 'SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci',
),
<?php
/**
* Database configuration and credentials.
*/
return array(
// Backend driver to use with the database.
'driver' => 'pdo_mysql',
// Host or IP to connect to (default: localhost).
'host' => 'localhost',
// Name of the primary application database.
'dbname' => 'pvl',
// Username for the database user with read/write access to the above database.
'user' => 'root',
// Password for the user account specified above.
'password' => 'password',
// Character set.
'charset' => 'utf8',
// Other options to send to the PDO adapter for the database.
'driverOptions' => array(
1002 => 'SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci',
),
);

View File

@ -1,100 +1,100 @@
<?php
/**
* General configuration file.
*/
define('DF_OPT_NO', 0);
define('DF_OPT_YES', 1);
return array(
// Yes/no options.
'opts_yesno' => array(
DF_OPT_NO => 'No',
DF_OPT_YES => 'Yes',
),
// Gender options.
'opts_gender' => array(
'M' => 'Male',
'F' => 'Female',
),
// Month options.
'months' => array(
1 => 'January',
2 => 'February',
3 => 'March',
4 => 'April',
5 => 'May',
6 => 'June',
7 => 'July',
8 => 'August',
9 => 'September',
10 => 'October',
11 => 'November',
12 => 'December',
),
// US State options.
'states' => array(
'AK' => 'Alaska',
'AL' => 'Alabama',
'AR' => 'Arkansas',
'AS' => 'American Samoa',
'AZ' => 'Arizona',
'CA' => 'California',
'CO' => 'Colorado',
'CT' => 'Connecticut',
'DC' => 'D.C.',
'DE' => 'Delaware',
'FL' => 'Florida',
'FM' => 'Micronesia',
'GA' => 'Georgia',
'GU' => 'Guam',
'HI' => 'Hawaii',
'IA' => 'Iowa',
'ID' => 'Idaho',
'IL' => 'Illinois',
'IN' => 'Indiana',
'KS' => 'Kansas',
'KY' => 'Kentucky',
'LA' => 'Louisiana',
'MA' => 'Massachusetts',
'MD' => 'Maryland',
'ME' => 'Maine',
'MH' => 'Marshall Islands',
'MI' => 'Michigan',
'MN' => 'Minnesota',
'MO' => 'Missouri',
'MP' => 'Marianas',
'MS' => 'Mississippi',
'MT' => 'Montana',
'NC' => 'North Carolina',
'ND' => 'North Dakota',
'NE' => 'Nebraska',
'NH' => 'New Hampshire',
'NJ' => 'New Jersey',
'NM' => 'New Mexico',
'NV' => 'Nevada',
'NY' => 'New York',
'OH' => 'Ohio',
'OK' => 'Oklahoma',
'OR' => 'Oregon',
'PA' => 'Pennsylvania',
'PR' => 'Puerto Rico',
'PW' => 'Palau',
'RI' => 'Rhode Island',
'SC' => 'South Carolina',
'SD' => 'South Dakota',
'TN' => 'Tennessee',
'TX' => 'Texas',
'UT' => 'Utah',
'VA' => 'Virginia',
'VI' => 'Virgin Islands',
'VT' => 'Vermont',
'WA' => 'Washington',
'WI' => 'Wisconsin',
'WV' => 'West Virginia',
'WY' => 'Wyoming',
),
<?php
/**
* General configuration file.
*/
define('DF_OPT_NO', 0);
define('DF_OPT_YES', 1);
return array(
// Yes/no options.
'opts_yesno' => array(
DF_OPT_NO => 'No',
DF_OPT_YES => 'Yes',
),
// Gender options.
'opts_gender' => array(
'M' => 'Male',
'F' => 'Female',
),
// Month options.
'months' => array(
1 => 'January',
2 => 'February',
3 => 'March',
4 => 'April',
5 => 'May',
6 => 'June',
7 => 'July',
8 => 'August',
9 => 'September',
10 => 'October',
11 => 'November',
12 => 'December',
),
// US State options.
'states' => array(
'AK' => 'Alaska',
'AL' => 'Alabama',
'AR' => 'Arkansas',
'AS' => 'American Samoa',
'AZ' => 'Arizona',
'CA' => 'California',
'CO' => 'Colorado',
'CT' => 'Connecticut',
'DC' => 'D.C.',
'DE' => 'Delaware',
'FL' => 'Florida',
'FM' => 'Micronesia',
'GA' => 'Georgia',
'GU' => 'Guam',
'HI' => 'Hawaii',
'IA' => 'Iowa',
'ID' => 'Idaho',
'IL' => 'Illinois',
'IN' => 'Indiana',
'KS' => 'Kansas',
'KY' => 'Kentucky',
'LA' => 'Louisiana',
'MA' => 'Massachusetts',
'MD' => 'Maryland',
'ME' => 'Maine',
'MH' => 'Marshall Islands',
'MI' => 'Michigan',
'MN' => 'Minnesota',
'MO' => 'Missouri',
'MP' => 'Marianas',
'MS' => 'Mississippi',
'MT' => 'Montana',
'NC' => 'North Carolina',
'ND' => 'North Dakota',
'NE' => 'Nebraska',
'NH' => 'New Hampshire',
'NJ' => 'New Jersey',
'NM' => 'New Mexico',
'NV' => 'Nevada',
'NY' => 'New York',
'OH' => 'Ohio',
'OK' => 'Oklahoma',
'OR' => 'Oregon',
'PA' => 'Pennsylvania',
'PR' => 'Puerto Rico',
'PW' => 'Palau',
'RI' => 'Rhode Island',
'SC' => 'South Carolina',
'SD' => 'South Dakota',
'TN' => 'Tennessee',
'TX' => 'Texas',
'UT' => 'Utah',
'VA' => 'Virginia',
'VI' => 'Virgin Islands',
'VT' => 'Vermont',
'WA' => 'Washington',
'WI' => 'Wisconsin',
'WV' => 'West Virginia',
'WY' => 'Wyoming',
),
);

View File

@ -1,11 +0,0 @@
<?php
/**
* Register application modules
*/
$application->registerModules(array(
'frontend' => array(
'className' => 'Phalcon\Frontend\Module',
'path' => __DIR__ . '/../apps/frontend/Module.php'
)
));

View File

@ -1,10 +1,10 @@
<?php
return array(
// Default theme used to render PVL site.
'default_theme' => 'light',
'customization_defaults' => array(
'theme' => 'light',
'timezone' => 'US/Eastern',
),
<?php
return array(
// Default theme used to render PVL site.
'default_theme' => 'light',
'customization_defaults' => array(
'theme' => 'light',
'timezone' => 'US/Eastern',
),
);

View File

@ -1 +0,0 @@
<html><body><h1>Mod-Rewrite is not enabled</h1><p>Please enable rewrite module on your web server to continue</body></html>

42
app/library/DF/Acl.php → phalcon/library/DF/Acl.php Executable file → Normal file
View File

@ -1,22 +1,22 @@
<?php
/**
* Access Control List (ACL) manager
*/
namespace DF;
use \Entity\User;
class Acl
{
public static function getInstance()
{
return \Zend_Registry::get('acl');
}
public static function __callStatic($name, $arguments)
{
$instance = self::getInstance();
return call_user_func_array(array($instance, $name), $arguments);
}
<?php
/**
* Access Control List (ACL) manager
*/
namespace DF;
use \Entity\User;
class Acl
{
public static function getInstance()
{
return \Zend_Registry::get('acl');
}
public static function __callStatic($name, $arguments)
{
$instance = self::getInstance();
return call_user_func_array(array($instance, $name), $arguments);
}
}

View File

@ -1,149 +1,159 @@
<?php
/**
* Access Control List (ACL) manager
*/
namespace DF\Acl;
use \Entity\User;
use \Entity\Role;
class Instance
{
protected $_actions = NULL;
public function __construct()
{}
public function init()
{
if (null === $this->_actions)
{
$this->_actions = array();
$em = \Zend_Registry::get('em');
$query = $em->createQuery('SELECT r, a FROM \Entity\Role r JOIN r.actions a');
$roles_with_actions = $query->getArrayResult();
foreach($roles_with_actions as $role)
{
foreach((array)$role['actions'] as $action)
{
$this->_actions[$role['id']][] = $action['name'];
}
}
}
}
public function userAllowed($action, User $user = null)
{
static $roles;
static $cache;
$action = array_map('strtolower', (array)$action);
asort($action);
$memoize = md5(serialize($action));
$user_id = ($user instanceof User) ? $user->id : 'anonymous';
if( !isset($cache[$user_id][$memoize]) )
{
if($user instanceof User)
{
if(!isset($roles[$user_id]))
{
$roles[$user_id] = array();
if (count($user->roles) > 0)
{
foreach($user->roles as $role)
{
$roles[$user_id][] = $role->id;
}
}
}
$cache[$user_id][$memoize] = $this->roleAllowed($roles[$user_id], $action);
}
else
{
$cache[$user_id][$memoize] = $this->roleAllowed(array('Unauthenticated'), $action);
}
}
return $cache[$user_id][$memoize];
}
public function isAllowed($action)
{
$auth = \Zend_Registry::get('auth');
$user = $auth->getLoggedInUser();
$is_logged_in = ($user instanceof User);
if ($action == "is logged in")
return ($is_logged_in);
elseif ($action == "is not logged in")
return (!$is_logged_in);
elseif ($is_logged_in)
return $this->userAllowed($action, $user);
else
return false;
}
public function roleAllowed($role_id, $action, $exact_only = FALSE)
{
$this->init();
if(is_array($role_id))
{
foreach($role_id as $r)
{
if($this->roleAllowed($r, $action)) //Once we've gotten a true, move forward
return true;
}
return false;
}
else if(is_array($action))
{
foreach($action as $a)
{
if($this->roleAllowed($role_id, $a))
return true;
}
return false;
}
else
{
// Without "exact_only" flag, matches based on root-level access are permitted.
if (!$exact_only)
{
if($role_id == 1) //ROOT
return true;
if (in_array('administer all', (array)$this->_actions[$role_id]))
return true;
}
if (isset($this->_actions[$role_id]) && in_array($action, $this->_actions[$role_id]))
return true;
return false;
}
}
/**
* Pretty wrapper around the 'isAllowed' function that throws a UI-friendly exception upon failure.
*/
public function checkPermission($action)
{
$auth = \Zend_Registry::get('auth');
if (!$this->isAllowed($action))
{
if (!$auth->isLoggedIn())
throw new \DF\Exception\NotLoggedIn();
else
throw new \DF\Exception\PermissionDenied();
}
}
<?php
/**
* Access Control List (ACL) manager
*/
namespace DF\Acl;
use \Entity\User;
use \Entity\Role;
class Instance implements \Phalcon\DI\InjectionAwareInterface
{
protected $_actions = NULL;
protected $_di;
public function setDi($di)
{
$this->_di = $di;
}
public function getDi()
{
return $this->_di;
}
public function __construct()
{}
public function init()
{
if (null === $this->_actions)
{
$this->_actions = array();
$em = $this->_di->get('em');
$query = $em->createQuery('SELECT r, a FROM \Entity\Role r JOIN r.actions a');
$roles_with_actions = $query->getArrayResult();
foreach($roles_with_actions as $role)
{
foreach((array)$role['actions'] as $action)
{
$this->_actions[$role['id']][] = $action['name'];
}
}
}
}
public function userAllowed($action, User $user = null)
{
static $roles;
static $cache;
$action = array_map('strtolower', (array)$action);
asort($action);
$memoize = md5(serialize($action));
$user_id = ($user instanceof User) ? $user->id : 'anonymous';
if( !isset($cache[$user_id][$memoize]) )
{
if($user instanceof User)
{
if(!isset($roles[$user_id]))
{
$roles[$user_id] = array();
if (count($user->roles) > 0)
{
foreach($user->roles as $role)
{
$roles[$user_id][] = $role->id;
}
}
}
$cache[$user_id][$memoize] = $this->roleAllowed($roles[$user_id], $action);
}
else
{
$cache[$user_id][$memoize] = $this->roleAllowed(array('Unauthenticated'), $action);
}
}
return $cache[$user_id][$memoize];
}
public function isAllowed($action)
{
$auth = $this->_di->get('auth');
$user = $auth->getLoggedInUser();
$is_logged_in = ($user instanceof User);
if ($action == "is logged in")
return ($is_logged_in);
elseif ($action == "is not logged in")
return (!$is_logged_in);
elseif ($is_logged_in)
return $this->userAllowed($action, $user);
else
return false;
}
public function roleAllowed($role_id, $action, $exact_only = FALSE)
{
$this->init();
if(is_array($role_id))
{
foreach($role_id as $r)
{
if($this->roleAllowed($r, $action)) //Once we've gotten a true, move forward
return true;
}
return false;
}
else if(is_array($action))
{
foreach($action as $a)
{
if($this->roleAllowed($role_id, $a))
return true;
}
return false;
}
else
{
// Without "exact_only" flag, matches based on root-level access are permitted.
if (!$exact_only)
{
if($role_id == 1) //ROOT
return true;
if (in_array('administer all', (array)$this->_actions[$role_id]))
return true;
}
if (isset($this->_actions[$role_id]) && in_array($action, $this->_actions[$role_id]))
return true;
return false;
}
}
/**
* Pretty wrapper around the 'isAllowed' function that throws a UI-friendly exception upon failure.
*/
public function checkPermission($action)
{
$auth = \Zend_Registry::get('auth');
if (!$this->isAllowed($action))
{
if (!$auth->isLoggedIn())
throw new \DF\Exception\NotLoggedIn();
else
throw new \DF\Exception\PermissionDenied();
}
}
}

View File

@ -1,34 +1,34 @@
<?php
namespace DF\Application;
class Bootstrap extends \Zend_Application_Bootstrap_Bootstrap
{
public function _initView()
{
return self::getNewView(TRUE);
}
public static function getNewView($use_static = TRUE)
{
$view = new \Zend_View();
$view->setEncoding('UTF-8');
$view->headMeta()->appendHttpEquiv('Content-Type', 'text/html;charset=utf-8');
$view->doctype(\Zend_View_Helper_Doctype::HTML5);
$view->config = \Zend_Registry::get('config');
$view->addHelperPath('DF/View/Helper', 'DF\View\Helper\\');
if ($use_static)
{
$viewRenderer = \Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$viewRenderer->setView($view);
}
else
{
$viewRenderer = new \Zend_Controller_Action_Helper_ViewRenderer($view);
}
return $viewRenderer;
}
<?php
namespace DF\Application;
class Bootstrap extends \Zend_Application_Bootstrap_Bootstrap
{
public function _initView()
{
return self::getNewView(TRUE);
}
public static function getNewView($use_static = TRUE)
{
$view = new \Zend_View();
$view->setEncoding('UTF-8');
$view->headMeta()->appendHttpEquiv('Content-Type', 'text/html;charset=utf-8');
$view->doctype(\Zend_View_Helper_Doctype::HTML5);
$view->config = \Zend_Registry::get('config');
$view->addHelperPath('DF/View/Helper', 'DF\View\Helper\\');
if ($use_static)
{
$viewRenderer = \Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$viewRenderer->setView($view);
}
else
{
$viewRenderer = new \Zend_Controller_Action_Helper_ViewRenderer($view);
}
return $viewRenderer;
}
}

View File

@ -1,52 +1,52 @@
<?php
namespace DF\Application;
class Maintenance
{
public static function render($message, $title = NULL)
{
$layout = self::getLayout();
if ($title !== NULL)
$layout->getView()->headTitle($title);
$layout->content = $message;
return $layout->render();
}
public static function display($message, $title = NULL)
{
echo self::render($message, $title);
}
public static function getLayout()
{
static $layout;
if ($layout === NULL)
{
$registry = \Zend_Registry::getInstance();
if (isset($registry['config']))
$config = $registry['config'];
else
$config = $_GLOBALS['config'];
// Initialize Zend routing.
$front = \Zend_Controller_Front::getInstance();
$front->setRequest(new \Zend_Controller_Request_Http);
// Special handling for .php scripts being accessed directly.
if (stristr($_SERVER['REQUEST_URI'], '.php') !== FALSE)
$front->setBaseUrl(substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], '/')));
// Set up maintenance layout.
$layout = new \Zend_Layout();
$layout->setLayoutPath($config->application->resources->layout->layoutPath);
$layout->getView()->assign(array(
'config' => $config,
));
$layout->setLayout('maintenance');
}
return $layout;
}
<?php
namespace DF\Application;
class Maintenance
{
public static function render($message, $title = NULL)
{
$layout = self::getLayout();
if ($title !== NULL)
$layout->getView()->headTitle($title);
$layout->content = $message;
return $layout->render();
}
public static function display($message, $title = NULL)
{
echo self::render($message, $title);
}
public static function getLayout()
{
static $layout;
if ($layout === NULL)
{
$registry = \Zend_Registry::getInstance();
if (isset($registry['config']))
$config = $registry['config'];
else
$config = $_GLOBALS['config'];
// Initialize Zend routing.
$front = \Zend_Controller_Front::getInstance();
$front->setRequest(new \Zend_Controller_Request_Http);
// Special handling for .php scripts being accessed directly.
if (stristr($_SERVER['REQUEST_URI'], '.php') !== FALSE)
$front->setBaseUrl(substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], '/')));
// Set up maintenance layout.
$layout = new \Zend_Layout();
$layout->setLayoutPath($config->application->resources->layout->layoutPath);
$layout->getView()->assign(array(
'config' => $config,
));
$layout->setLayout('maintenance');
}
return $layout;
}
}

View File

@ -1,153 +1,153 @@
<?php
namespace DF\Application\Resource;
use \Doctrine\Common\ClassLoader;
use \Doctrine\DBAL\Types\Type;
class Doctrine extends \Zend_Application_Resource_ResourceAbstract
{
protected $_em;
public function init()
{
$options = $this->getOptions();
if(empty($options))
return false;
// Register custom data types.
Type::addType('json', 'DF\Doctrine\Type\Json');
Type::addType('unixdatetime', 'DF\Doctrine\Type\UnixDateTime');
Type::overrideType('array', 'DF\Doctrine\Type\SoftArray');
Type::overrideType('datetime', 'DF\Doctrine\Type\UTCDateTime');
// Fetch and store entity manager.
$this->_em = $this->_getEntityManager();
$conn = $this->_em->getConnection();
$platform = $conn->getDatabasePlatform();
$platform->markDoctrineTypeCommented(Type::getType('json'));
$platform->markDoctrineTypeCommented(Type::getType('unixdatetime'));
\Zend_Registry::set('em', $this->_em);
return $this->_em;
}
protected function _getEntityManager()
{
$options = $this->getOptions();
$config = new \Doctrine\ORM\Configuration;
$app_config = \Zend_Registry::get('config');
$options['conn'] = $app_config->db->toArray();
// Handling for class names specified as platform types.
if ($options['conn']['platform'])
{
$class_obj = new \ReflectionClass($options['conn']['platform']);
$options['conn']['platform'] = $class_obj->newInstance();
}
// Special handling for the utf8mb4 type.
if ($options['conn']['driver'] == 'pdo_mysql' && $options['conn']['charset'] == 'utf8mb4')
{
$options['conn']['platform'] = new \DF\Doctrine\Platform\MysqlUnicode;
}
$metadata_driver = $config->newDefaultAnnotationDriver($options['modelPath']);
$config->setMetadataDriverImpl($metadata_driver);
$regen_proxies = FALSE;
if (DF_APPLICATION_ENV == "production" && !DF_IS_COMMAND_LINE)
{
$cache = new \DF\Doctrine\Cache;
$cache->setNamespace('doctrine_');
// Clear cache in case of updated production code.
$upload_reference_path = DF_INCLUDE_BASE.DIRECTORY_SEPARATOR . '.env';
$update_reference_path = DF_INCLUDE_BASE.DIRECTORY_SEPARATOR . '.updated';
if (!file_exists($update_reference_path))
{
@file_put_contents($update_reference_path, 'This file is automatically modified to track proxy regeneration.');
@touch($upload_reference_path);
}
clearstatcache();
$last_upload_time = (int)@filemtime($upload_reference_path);
$last_update_time = (int)@filemtime($update_reference_path);
if ($last_upload_time >= $last_update_time)
{
@touch($update_reference_path);
// Flush the cache.
$cache->flushAll();
// Clear the proxy directory.
$proxy_dir = $options['proxyPath'];
@mkdir($proxy_dir);
$files = glob($proxy_dir.DIRECTORY_SEPARATOR.'*.php');
foreach((array)$files as $file)
@unlink($file);
// Trigger proxy regeneration below.
$regen_proxies = TRUE;
$config->setAutoGenerateProxyClasses(TRUE);
}
}
else
{
$cache = new \Doctrine\Common\Cache\ArrayCache;
}
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
$config->setResultCacheImpl($cache);
$config->setProxyDir($options['proxyPath']);
$config->setProxyNamespace($options['proxyNamespace']);
if (!$regen_proxies)
$config->setAutoGenerateProxyClasses($options['autoGenerateProxies']);
if (isset($options['conn']['debug']) && $options['conn']['debug'])
$config->setSQLLogger(new \DF\Doctrine\Logger\EchoSQL);
$config->addFilter('softdelete', '\DF\Doctrine\Filter\SoftDelete');
$config->addCustomNumericFunction('RAND', '\DF\Doctrine\Functions\Rand');
$evm = new \Doctrine\Common\EventManager();
$em = \Doctrine\ORM\EntityManager::create($options['conn'], $config, $evm);
$em->getFilters()->enable("softdelete");
// Trigger proxy regeneration.
if ($regen_proxies)
{
$metadatas = $em->getMetadataFactory()->getAllMetadata();
$em->getProxyFactory()->generateProxyClasses($metadatas);
}
// Try the connection before rendering the page.
try
{
$em->getConnection()->connect();
}
catch(\Exception $e)
{
$db_config_location = str_replace(DF_INCLUDE_ROOT, '', DF_INCLUDE_APP).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'application.conf.php';
\DF\Application\Maintenance::display('
<h2>Database Error</h2>
<p>The system could not connect to the database. Verify that the information listed in "<i>'.$db_config_location.'</i>" is correct.</p>
<blockquote>'.$e->getMessage().'</blockquote>
');
exit;
}
return $em;
}
<?php
namespace DF\Application\Resource;
use \Doctrine\Common\ClassLoader;
use \Doctrine\DBAL\Types\Type;
class Doctrine extends \Zend_Application_Resource_ResourceAbstract
{
protected $_em;
public function init()
{
$options = $this->getOptions();
if(empty($options))
return false;
// Register custom data types.
Type::addType('json', 'DF\Doctrine\Type\Json');
Type::addType('unixdatetime', 'DF\Doctrine\Type\UnixDateTime');
Type::overrideType('array', 'DF\Doctrine\Type\SoftArray');
Type::overrideType('datetime', 'DF\Doctrine\Type\UTCDateTime');
// Fetch and store entity manager.
$this->_em = $this->_getEntityManager();
$conn = $this->_em->getConnection();
$platform = $conn->getDatabasePlatform();
$platform->markDoctrineTypeCommented(Type::getType('json'));
$platform->markDoctrineTypeCommented(Type::getType('unixdatetime'));
\Zend_Registry::set('em', $this->_em);
return $this->_em;
}
protected function _getEntityManager()
{
$options = $this->getOptions();
$config = new \Doctrine\ORM\Configuration;
$app_config = \Zend_Registry::get('config');
$options['conn'] = $app_config->db->toArray();
// Handling for class names specified as platform types.
if ($options['conn']['platform'])
{
$class_obj = new \ReflectionClass($options['conn']['platform']);
$options['conn']['platform'] = $class_obj->newInstance();
}
// Special handling for the utf8mb4 type.
if ($options['conn']['driver'] == 'pdo_mysql' && $options['conn']['charset'] == 'utf8mb4')
{
$options['conn']['platform'] = new \DF\Doctrine\Platform\MysqlUnicode;
}
$metadata_driver = $config->newDefaultAnnotationDriver($options['modelPath']);
$config->setMetadataDriverImpl($metadata_driver);
$regen_proxies = FALSE;
if (DF_APPLICATION_ENV == "production" && !DF_IS_COMMAND_LINE)
{
$cache = new \DF\Doctrine\Cache;
$cache->setNamespace('doctrine_');
// Clear cache in case of updated production code.
$upload_reference_path = DF_INCLUDE_BASE.DIRECTORY_SEPARATOR . '.env';
$update_reference_path = DF_INCLUDE_BASE.DIRECTORY_SEPARATOR . '.updated';
if (!file_exists($update_reference_path))
{
@file_put_contents($update_reference_path, 'This file is automatically modified to track proxy regeneration.');
@touch($upload_reference_path);
}
clearstatcache();
$last_upload_time = (int)@filemtime($upload_reference_path);
$last_update_time = (int)@filemtime($update_reference_path);
if ($last_upload_time >= $last_update_time)
{
@touch($update_reference_path);
// Flush the cache.
$cache->flushAll();
// Clear the proxy directory.
$proxy_dir = $options['proxyPath'];
@mkdir($proxy_dir);
$files = glob($proxy_dir.DIRECTORY_SEPARATOR.'*.php');
foreach((array)$files as $file)
@unlink($file);
// Trigger proxy regeneration below.
$regen_proxies = TRUE;
$config->setAutoGenerateProxyClasses(TRUE);
}
}
else
{
$cache = new \Doctrine\Common\Cache\ArrayCache;
}
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
$config->setResultCacheImpl($cache);
$config->setProxyDir($options['proxyPath']);
$config->setProxyNamespace($options['proxyNamespace']);
if (!$regen_proxies)
$config->setAutoGenerateProxyClasses($options['autoGenerateProxies']);
if (isset($options['conn']['debug']) && $options['conn']['debug'])
$config->setSQLLogger(new \DF\Doctrine\Logger\EchoSQL);
$config->addFilter('softdelete', '\DF\Doctrine\Filter\SoftDelete');
$config->addCustomNumericFunction('RAND', '\DF\Doctrine\Functions\Rand');
$evm = new \Doctrine\Common\EventManager();
$em = \Doctrine\ORM\EntityManager::create($options['conn'], $config, $evm);
$em->getFilters()->enable("softdelete");
// Trigger proxy regeneration.
if ($regen_proxies)
{
$metadatas = $em->getMetadataFactory()->getAllMetadata();
$em->getProxyFactory()->generateProxyClasses($metadatas);
}
// Try the connection before rendering the page.
try
{
$em->getConnection()->connect();
}
catch(\Exception $e)
{
$db_config_location = str_replace(DF_INCLUDE_ROOT, '', DF_INCLUDE_APP).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'application.conf.php';
\DF\Application\Maintenance::display('
<h2>Database Error</h2>
<p>The system could not connect to the database. Verify that the information listed in "<i>'.$db_config_location.'</i>" is correct.</p>
<blockquote>'.$e->getMessage().'</blockquote>
');
exit;
}
return $em;
}
}

View File

@ -1,79 +1,79 @@
<?php
namespace DF\Application\Resource;
class Menu extends \Zend_Application_Resource_ResourceAbstract
{
public function init()
{
$menu = $this->_getMenuCache();
if (!$menu)
{
$menu = $this->_loadMenu();
$this->_setMenuCache($menu);
}
return new \DF\Menu($menu);
}
protected function _getMenuCache()
{
// Never cache menus on dev environments.
if (DF_APPLICATION_ENV == "dev")
return NULL;
// Compare to environment file timestamp, updated upon phing.
$upload_reference_path = DF_INCLUDE_BASE.DIRECTORY_SEPARATOR . '.env';
$last_upload_time = (int)@filemtime($upload_reference_path);
$cache_contents = \DF\Cache::get('df_menu');
$cache_timestamp = \DF\Cache::get('df_menu_timestamp');
if ($cache_contents && $cache_timestamp >= $last_upload_time)
return $cache_contents;
else
return NULL;
}
protected function _setMenuCache($menu)
{
\DF\Cache::save($menu, 'df_menu');
\DF\Cache::save(time(), 'df_menu_timestamp');
}
protected function _loadMenu()
{
$menu = array();
foreach(new \DirectoryIterator(DF_INCLUDE_MODULES) as $item)
{
if( $item->isDir() && !$item->isDot() )
{
$menu_file = $item->getPathname().DIRECTORY_SEPARATOR.'menu.php';
if(file_exists($menu_file))
{
$new_menu = (array)include_once($menu_file);
$menu = $this->_mergeFlat($menu, $new_menu);
}
}
}
return $menu;
}
protected function _mergeFlat()
{
$arrays = func_get_args();
$base = array_shift($arrays);
foreach ($arrays as $array)
{
reset($base); //important
foreach($array as $key => $value)
{
if (is_array($value) && @is_array($base[$key]))
$base[$key] = $this->_mergeFlat($base[$key], $value);
else
$base[$key] = $value;
}
}
return $base;
}
<?php
namespace DF\Application\Resource;
class Menu extends \Zend_Application_Resource_ResourceAbstract
{
public function init()
{
$menu = $this->_getMenuCache();
if (!$menu)
{
$menu = $this->_loadMenu();
$this->_setMenuCache($menu);
}
return new \DF\Menu($menu);
}
protected function _getMenuCache()
{
// Never cache menus on dev environments.
if (DF_APPLICATION_ENV == "dev")
return NULL;
// Compare to environment file timestamp, updated upon phing.
$upload_reference_path = DF_INCLUDE_BASE.DIRECTORY_SEPARATOR . '.env';
$last_upload_time = (int)@filemtime($upload_reference_path);
$cache_contents = \DF\Cache::get('df_menu');
$cache_timestamp = \DF\Cache::get('df_menu_timestamp');
if ($cache_contents && $cache_timestamp >= $last_upload_time)
return $cache_contents;
else
return NULL;
}
protected function _setMenuCache($menu)
{
\DF\Cache::save($menu, 'df_menu');
\DF\Cache::save(time(), 'df_menu_timestamp');
}
protected function _loadMenu()
{
$menu = array();
foreach(new \DirectoryIterator(DF_INCLUDE_MODULES) as $item)
{
if( $item->isDir() && !$item->isDot() )
{
$menu_file = $item->getPathname().DIRECTORY_SEPARATOR.'menu.php';
if(file_exists($menu_file))
{
$new_menu = (array)include_once($menu_file);
$menu = $this->_mergeFlat($menu, $new_menu);
}
}
}
return $menu;
}
protected function _mergeFlat()
{
$arrays = func_get_args();
$base = array_shift($arrays);
foreach ($arrays as $array)
{
reset($base); //important
foreach($array as $key => $value)
{
if (is_array($value) && @is_array($base[$key]))
$base[$key] = $this->_mergeFlat($base[$key], $value);
else
$base[$key] = $value;
}
}
return $base;
}
}

36
app/library/DF/Auth.php → phalcon/library/DF/Auth.php Executable file → Normal file
View File

@ -1,19 +1,19 @@
<?php
/**
* DF\Auth - Static Wrapper for the global auth instance.
*/
namespace DF;
class Auth
{
public static function getInstance()
{
return \Zend_Registry::get('auth');
}
public static function __callStatic($name, $arguments)
{
$instance = self::getInstance();
return call_user_func_array(array($instance, $name), $arguments);
}
<?php
/**
* DF\Auth - Static Wrapper for the global auth instance.
*/
namespace DF;
class Auth
{
public static function getInstance()
{
return \Zend_Registry::get('auth');
}
public static function __callStatic($name, $arguments)
{
$instance = self::getInstance();
return call_user_func_array(array($instance, $name), $arguments);
}
}

View File

@ -1,138 +1,138 @@
<?php
namespace DF\Auth\Adapter;
class Cas implements \Zend_Auth_Adapter_Interface
{
protected $_options;
public function __construct($options)
{
$this->setOptions($options);
}
public function setOptions($options)
{
$this->_options = $options;
}
public function authenticate()
{
try
{
$auth_result = $this->login();
if ($auth_result['success'])
{
$result = new \Zend_Auth_Result(
\Zend_Auth_Result::SUCCESS,
$auth_result,
array()
);
}
else
{
$result = new \Zend_Auth_Result(
\Zend_Auth_Result::FAILURE_UNCATEGORIZED,
null,
array($auth_result['message'])
);
}
}
catch( \Exception $e )
{
$result = new \Zend_Auth_Result(
\Zend_Auth_Result::FAILURE,
null,
(array)sprintf('%s',
$e->getMessage()
)
);
}
return $result;
}
public function login($destination_url = NULL)
{
// Get the CAS ticket if it has been set.
$ticket = (isset($_REQUEST['ticket'])) ? $_REQUEST['ticket'] : '';
if (is_null($destination_url) || empty($destination_url))
{
$destination_url = $this->getServiceUrl();
}
if (!empty($ticket))
{
$validate = (substr($ticket, 0, 2) == 'ST') ? 'serviceValidate' : 'proxyValidate';
$query_string = array(
'service' => $destination_url,
'ticket' => $ticket,
);
$file_url = $this->_options['cas_base'].'/'.$validate.'?'.http_build_query($query_string);
$file = file_get_contents($file_url);
if (!$file)
{
throw new \Exception('Could Not Authenticate: The CAS service did not return a complete response.');
}
}
else
{
$query_string = array('service' => $destination_url);
if ($this->_options['renew'])
{
$query_string['renew'] = 'true';
}
// Redirect to login page.
header("Location: ".$this->_options['cas_base'].'/login?'.http_build_query($query_string));
exit;
}
$xml_array = \DF\Export::XmlToArray($file);
$return_value = array();
if (isset($xml_array['cas:serviceResponse']['cas:authenticationSuccess']))
{
$attributes = $xml_array['cas:serviceResponse']['cas:authenticationSuccess'][0]['cas:attributes'][0];
$return_value['success'] = TRUE;
$return_value['uin'] = $attributes['cas:tamuEduPersonUIN'];
$return_value['netid'] = $attributes['cas:tamuEduPersonNetID'];
}
else
{
$return_value['success'] = FALSE;
$return_value['message'] = $xml_array['cas:serviceResponse']['cas:authenticationFailure']['code'];
}
return $return_value;
}
public function logout($destination_url = NULL)
{
if ($this->_options['full_logout'])
{
if (is_null($destination_url))
{
$destination_url = $this->getServiceUrl();
}
$url_params = array(
'service' => $destination_url,
);
// Redirect to login page.
header("Location: ".$this->_options['cas_base'].'/logout?'.http_build_query($url_params));
exit;
}
}
private function getServiceUrl()
{
return \DF\Url::current(TRUE, FALSE);
}
<?php
namespace DF\Auth\Adapter;
class Cas implements \Zend_Auth_Adapter_Interface
{
protected $_options;
public function __construct($options)
{
$this->setOptions($options);
}
public function setOptions($options)
{
$this->_options = $options;
}
public function authenticate()
{
try
{
$auth_result = $this->login();
if ($auth_result['success'])
{
$result = new \Zend_Auth_Result(
\Zend_Auth_Result::SUCCESS,
$auth_result,
array()
);
}
else
{
$result = new \Zend_Auth_Result(
\Zend_Auth_Result::FAILURE_UNCATEGORIZED,
null,
array($auth_result['message'])
);
}
}
catch( \Exception $e )
{
$result = new \Zend_Auth_Result(
\Zend_Auth_Result::FAILURE,
null,
(array)sprintf('%s',
$e->getMessage()
)
);
}
return $result;
}
public function login($destination_url = NULL)
{
// Get the CAS ticket if it has been set.
$ticket = (isset($_REQUEST['ticket'])) ? $_REQUEST['ticket'] : '';
if (is_null($destination_url) || empty($destination_url))
{
$destination_url = $this->getServiceUrl();
}
if (!empty($ticket))
{
$validate = (substr($ticket, 0, 2) == 'ST') ? 'serviceValidate' : 'proxyValidate';
$query_string = array(
'service' => $destination_url,
'ticket' => $ticket,
);
$file_url = $this->_options['cas_base'].'/'.$validate.'?'.http_build_query($query_string);
$file = file_get_contents($file_url);
if (!$file)
{
throw new \Exception('Could Not Authenticate: The CAS service did not return a complete response.');
}
}
else
{
$query_string = array('service' => $destination_url);
if ($this->_options['renew'])
{
$query_string['renew'] = 'true';
}
// Redirect to login page.
header("Location: ".$this->_options['cas_base'].'/login?'.http_build_query($query_string));
exit;
}
$xml_array = \DF\Export::XmlToArray($file);
$return_value = array();
if (isset($xml_array['cas:serviceResponse']['cas:authenticationSuccess']))
{
$attributes = $xml_array['cas:serviceResponse']['cas:authenticationSuccess'][0]['cas:attributes'][0];
$return_value['success'] = TRUE;
$return_value['uin'] = $attributes['cas:tamuEduPersonUIN'];
$return_value['netid'] = $attributes['cas:tamuEduPersonNetID'];
}
else
{
$return_value['success'] = FALSE;
$return_value['message'] = $xml_array['cas:serviceResponse']['cas:authenticationFailure']['code'];
}
return $return_value;
}
public function logout($destination_url = NULL)
{
if ($this->_options['full_logout'])
{
if (is_null($destination_url))
{
$destination_url = $this->getServiceUrl();
}
$url_params = array(
'service' => $destination_url,
);
// Redirect to login page.
header("Location: ".$this->_options['cas_base'].'/logout?'.http_build_query($url_params));
exit;
}
}
private function getServiceUrl()
{
return \DF\Url::current(TRUE, FALSE);
}
}

View File

@ -1,34 +1,34 @@
<?php
/**
* LDAP Authentication Adapter
*/
namespace DF\Auth\Adapter;
define(LDAP_OPT_DIAGNOSTIC_MESSAGE, 0x0032);
class Ldap implements \Zend_Auth_Adapter_Interface
{
protected $_options = array();
public function __construct($options = array())
{
$this->setOptions($options);
}
public function setOptions($options)
{
$this->_options = array_merge($this->_options, (array)$options);
}
/**
* (non-PHPdoc)
* @see Zend/Auth/Adapter/Zend_Auth_Adapter_Interface#authenticate()
*
* @return Zend_Auth_Result
*/
public function authenticate()
{
return \DF\Service\Ldap::authenticate($this->_options['username'], $this->_options['password']);
}
<?php
/**
* LDAP Authentication Adapter
*/
namespace DF\Auth\Adapter;
define(LDAP_OPT_DIAGNOSTIC_MESSAGE, 0x0032);
class Ldap implements \Zend_Auth_Adapter_Interface
{
protected $_options = array();
public function __construct($options = array())
{
$this->setOptions($options);
}
public function setOptions($options)
{
$this->_options = array_merge($this->_options, (array)$options);
}
/**
* (non-PHPdoc)
* @see Zend/Auth/Adapter/Zend_Auth_Adapter_Interface#authenticate()
*
* @return Zend_Auth_Result
*/
public function authenticate()
{
return \DF\Service\Ldap::authenticate($this->_options['username'], $this->_options['password']);
}
}

View File

@ -1,50 +1,50 @@
<?php
/**
* Doctrine DB Model Custom Authentication Adapter
*/
namespace DF\Auth\Adapter;
use \Entity\User;
class Model implements \Zend_Auth_Adapter_Interface
{
protected $_options = array();
public function __construct($options = array())
{
$this->setOptions($options);
}
public function setOptions($options)
{
$this->_options = array_merge($this->_options, (array)$options);
}
public function authenticate()
{
$user = $this->modelAuth($this->_options['username'], $this->_options['password']);
if ($user !== FALSE)
{
return new \Zend_Auth_Result(
\Zend_Auth_Result::SUCCESS,
array('id' => $user['id']),
array()
);
}
else
{
return new \Zend_Auth_Result(
\Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,
null,
array('Invalid username or password supplied. Please try again.')
);
}
}
public function modelAuth($username, $password)
{
return \Entity\User::authenticate($username, $password);
}
<?php
/**
* Doctrine DB Model Custom Authentication Adapter
*/
namespace DF\Auth\Adapter;
use \Entity\User;
class Model implements \Zend_Auth_Adapter_Interface
{
protected $_options = array();
public function __construct($options = array())
{
$this->setOptions($options);
}
public function setOptions($options)
{
$this->_options = array_merge($this->_options, (array)$options);
}
public function authenticate()
{
$user = $this->modelAuth($this->_options['username'], $this->_options['password']);
if ($user !== FALSE)
{
return new \Zend_Auth_Result(
\Zend_Auth_Result::SUCCESS,
array('id' => $user['id']),
array()
);
}
else
{
return new \Zend_Auth_Result(
\Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,
null,
array('Invalid username or password supplied. Please try again.')
);
}
}
public function modelAuth($username, $password)
{
return \Entity\User::authenticate($username, $password);
}
}

View File

@ -1,40 +1,40 @@
<?php
namespace DF\Auth;
use \Entity\User;
class Cas extends Instance
{
public function __construct()
{
parent::__construct();
$config = \Zend_Registry::get('config');
$this->_adapter = new Adapter\Cas($config->services->cas->toArray());
}
public function authenticate()
{
$response = parent::authenticate();
if($response->isValid())
{
$identity = $response->getIdentity();
$user = User::getOrCreate($identity['uin']);
$this->_session->identity = $identity;
$this->_session->user_id = $user['id'];
$this->_user = $user;
return true;
}
else
{
if($response->getCode() != \Zend_Auth_Result::FAILURE_UNCATEGORIZED)
{
foreach($response->getMessages() as $message)
\DF\Flash::addMessage($message);
}
return false;
}
}
<?php
namespace DF\Auth;
use \Entity\User;
class Cas extends Instance
{
public function __construct()
{
parent::__construct();
$config = \Zend_Registry::get('config');
$this->_adapter = new Adapter\Cas($config->services->cas->toArray());
}
public function authenticate()
{
$response = parent::authenticate();
if($response->isValid())
{
$identity = $response->getIdentity();
$user = User::getOrCreate($identity['uin']);
$this->_session->identity = $identity;
$this->_session->user_id = $user['id'];
$this->_user = $user;
return true;
}
else
{
if($response->getCode() != \Zend_Auth_Result::FAILURE_UNCATEGORIZED)
{
foreach($response->getMessages() as $message)
\DF\Flash::addMessage($message);
}
return false;
}
}
}

View File

@ -1,14 +1,14 @@
<?php
/**
* Invalid User exception
*/
namespace DF\Auth\Exception;
class InvalidUser extends \DF\Exception\DisplayOnly {
public function __construct($message = NULL, $code = 0, Exception $previous = null) {
if (!$message)
$message = 'Your account has experienced an error and has been logged out for security purposes. Please log in again to continue.';
parent::__construct($message, $code, $previous);
}
<?php
/**
* Invalid User exception
*/
namespace DF\Auth\Exception;
class InvalidUser extends \DF\Exception\DisplayOnly {
public function __construct($message = NULL, $code = 0, Exception $previous = null) {
if (!$message)
$message = 'Your account has experienced an error and has been logged out for security purposes. Please log in again to continue.';
parent::__construct($message, $code, $previous);
}
}

View File

@ -1,209 +1,209 @@
<?php
namespace DF\Auth;
use \Entity\User;
class Instance
{
protected $_adapter;
protected $_session;
protected $_user = NULL;
protected $_masqueraded_user = NULL;
public function __construct()
{
$this->_session = $this->getSession();
}
public function getSession()
{
$class_name = strtolower(str_replace(array('\\', '_'), array('', ''), get_called_class()));
return \DF\Session::get('auth_'.$class_name.'_user');
}
public function login()
{
if ($this->isLoggedIn() || php_sapi_name() == 'cli')
return true;
else
return $this->authenticate();
}
public function authenticate()
{
$result = $this->_adapter->authenticate();
unset($this->_session->user_id);
unset($this->_session->masquerade_user_id);
return $result;
}
public function logout($destination = NULL, $unset_session = true)
{
unset($this->_session->identity);
unset($this->_session->user_id);
unset($this->_session->masquerade_user_id);
if ($unset_session)
@session_unset();
if (method_exists($this->_adapter, 'logout'))
$this->_adapter->logout($destination);
}
public function isLoggedIn()
{
if( php_sapi_name() == 'cli' )
return false;
$user = $this->getUser();
return ($user instanceof User);
}
public function getLoggedInUser($real_user_only = FALSE)
{
if ($this->isMasqueraded() && !$real_user_only)
return $this->getMasquerade();
else
return $this->getUser();
}
public function getUser()
{
if ($this->_user === NULL)
{
$user_id = (int)$this->_session->user_id;
if ($user_id == 0)
{
$this->_user = FALSE;
return false;
}
$user = User::find($user_id);
if ($user instanceof User)
{
$this->_user = $user;
}
else
{
unset($this->_session->user_id);
$this->_user = FALSE;
$this->logout();
throw new Exception\InvalidUser;
}
}
return $this->_user;
}
public function setUser(User $user)
{
// Prevent any previous identity from being used.
unset($this->_session->identity);
session_regenerate_id(TRUE);
$this->_session->user_id = $user->id;
$this->_user = $user;
return true;
}
public function getAdapter()
{
return $this->_adapter;
}
public function setAdapter($adapter)
{
$this->_adapter = $adapter;
}
public function setAdapterOptions($options)
{
if (method_exists($this->_adapter, 'setOptions'))
$this->_adapter->setOptions($options);
}
public function exists($response = null)
{
$user_id = (int)$this->_session->user_id;
$user = User::find($user_id);
return ($user instanceof User);
}
public function getIdentity()
{
return $this->_session->identity;
}
public function setIdentity($identity)
{
$this->_session->identity = $identity;
}
public function clearIdentity()
{
unset($this->_session->identity);
}
/**
* Masquerading
*/
public function masqueradeAsUser($user_info)
{
if (!($user_info instanceof User))
$user_info = User::getRepository()->findOneByUsername($user_info);
$this->_session->masquerade_user_id = $user_info->id;
$this->_masqueraded_user = $user_info;
}
public function endMasquerade()
{
unset($this->_session->masquerade_user_id);
$this->_masqueraded_user = null;
}
public function getMasquerade()
{
return $this->_masqueraded_user;
}
public function isMasqueraded()
{
if (!$this->isLoggedIn())
{
$this->_masqueraded_user = FALSE;
return NULL;
}
if ($this->_masqueraded_user === NULL)
{
if (!$this->_session->masquerade_user_id)
{
$this->_masqueraded_user = FALSE;
}
else
{
$mask_user_id = (int)$this->_session->masquerade_user_id;
if ($mask_user_id != 0)
$user = User::find($mask_user_id);
if ($user instanceof User)
{
$this->_masqueraded_user = $user;
}
else
{
unset($this->_session->user_id);
unset($this->_session->masquerade_user_id);
$this->_masqueraded_user = FALSE;
}
}
}
return $this->_masqueraded_user;
}
<?php
namespace DF\Auth;
use \Entity\User;
class Instance
{
protected $_adapter;
protected $_session;
protected $_user = NULL;
protected $_masqueraded_user = NULL;
public function __construct()
{
$this->_session = $this->getSession();
}
public function getSession()
{
$class_name = strtolower(str_replace(array('\\', '_'), array('', ''), get_called_class()));
return \DF\Session::get('auth_'.$class_name.'_user');
}
public function login()
{
if ($this->isLoggedIn() || php_sapi_name() == 'cli')
return true;
else
return $this->authenticate();
}
public function authenticate()
{
$result = $this->_adapter->authenticate();
unset($this->_session->user_id);
unset($this->_session->masquerade_user_id);
return $result;
}
public function logout($destination = NULL, $unset_session = true)
{
unset($this->_session->identity);
unset($this->_session->user_id);
unset($this->_session->masquerade_user_id);
if ($unset_session)
@session_unset();
if (method_exists($this->_adapter, 'logout'))
$this->_adapter->logout($destination);
}
public function isLoggedIn()
{
if( php_sapi_name() == 'cli' )
return false;
$user = $this->getUser();
return ($user instanceof User);
}
public function getLoggedInUser($real_user_only = FALSE)
{
if ($this->isMasqueraded() && !$real_user_only)
return $this->getMasquerade();
else
return $this->getUser();
}
public function getUser()
{
if ($this->_user === NULL)
{
$user_id = (int)$this->_session->user_id;
if ($user_id == 0)
{
$this->_user = FALSE;
return false;
}
$user = User::find($user_id);
if ($user instanceof User)
{
$this->_user = $user;
}
else
{
unset($this->_session->user_id);
$this->_user = FALSE;
$this->logout();
throw new Exception\InvalidUser;
}
}
return $this->_user;
}
public function setUser(User $user)
{
// Prevent any previous identity from being used.
unset($this->_session->identity);
session_regenerate_id(TRUE);
$this->_session->user_id = $user->id;
$this->_user = $user;
return true;
}
public function getAdapter()
{
return $this->_adapter;
}
public function setAdapter($adapter)
{
$this->_adapter = $adapter;
}
public function setAdapterOptions($options)
{
if (method_exists($this->_adapter, 'setOptions'))
$this->_adapter->setOptions($options);
}
public function exists($response = null)
{
$user_id = (int)$this->_session->user_id;
$user = User::find($user_id);
return ($user instanceof User);
}
public function getIdentity()
{
return $this->_session->identity;
}
public function setIdentity($identity)
{
$this->_session->identity = $identity;
}
public function clearIdentity()
{
unset($this->_session->identity);
}
/**
* Masquerading
*/
public function masqueradeAsUser($user_info)
{
if (!($user_info instanceof User))
$user_info = User::getRepository()->findOneByUsername($user_info);
$this->_session->masquerade_user_id = $user_info->id;
$this->_masqueraded_user = $user_info;
}
public function endMasquerade()
{
unset($this->_session->masquerade_user_id);
$this->_masqueraded_user = null;
}
public function getMasquerade()
{
return $this->_masqueraded_user;
}
public function isMasqueraded()
{
if (!$this->isLoggedIn())
{
$this->_masqueraded_user = FALSE;
return NULL;
}
if ($this->_masqueraded_user === NULL)
{
if (!$this->_session->masquerade_user_id)
{
$this->_masqueraded_user = FALSE;
}
else
{
$mask_user_id = (int)$this->_session->masquerade_user_id;
if ($mask_user_id != 0)
$user = User::find($mask_user_id);
if ($user instanceof User)
{
$this->_masqueraded_user = $user;
}
else
{
unset($this->_session->user_id);
unset($this->_session->masquerade_user_id);
$this->_masqueraded_user = FALSE;
}
}
}
return $this->_masqueraded_user;
}
}

View File

@ -1,65 +1,65 @@
<?php
namespace DF\Auth;
use \Entity\User;
use \Entity\Role;
class Ldap extends Instance
{
public function __construct()
{
parent::__construct();
$this->_adapter = new Adapter\Ldap;
}
public function authenticate($credentials = NULL)
{
$this->_adapter->setOptions($credentials);
$response = parent::authenticate();
if($response->isValid())
{
$identity = $response->getIdentity();
$this->_session->identity = $identity;
}
else
{
if($response->getCode() != \Zend_Auth_Result::FAILURE_UNCATEGORIZED)
{
foreach($response->getMessages() as $message)
\DF\Flash::addMessage($message);
}
return false;
}
$user = User::getOrCreate($identity, 'ldap');
$this->_session->user_id = $user['id'];
$this->_user = $user;
return true;
}
public function getUser()
{
$user = parent::getUser();
$identity = $this->getIdentity();
if ($user instanceof User)
{
return $user;
}
elseif ($identity)
{
$user = User::getOrCreate($identity, 'ldap');
if ($user instanceof User)
{
$this->_session->user_id = $user['id'];
$this->_user = $user;
return $user;
}
return false;
}
}
<?php
namespace DF\Auth;
use \Entity\User;
use \Entity\Role;
class Ldap extends Instance
{
public function __construct()
{
parent::__construct();
$this->_adapter = new Adapter\Ldap;
}
public function authenticate($credentials = NULL)
{
$this->_adapter->setOptions($credentials);
$response = parent::authenticate();
if($response->isValid())
{
$identity = $response->getIdentity();
$this->_session->identity = $identity;
}
else
{
if($response->getCode() != \Zend_Auth_Result::FAILURE_UNCATEGORIZED)
{
foreach($response->getMessages() as $message)
\DF\Flash::addMessage($message);
}
return false;
}
$user = User::getOrCreate($identity, 'ldap');
$this->_session->user_id = $user['id'];
$this->_user = $user;
return true;
}
public function getUser()
{
$user = parent::getUser();
$identity = $this->getIdentity();
if ($user instanceof User)
{
return $user;
}
elseif ($identity)
{
$user = User::getOrCreate($identity, 'ldap');
if ($user instanceof User)
{
$this->_session->user_id = $user['id'];
$this->_user = $user;
return $user;
}
return false;
}
}
}

View File

@ -1,37 +1,37 @@
<?php
namespace DF\Auth;
use \Entity\User;
class Model extends Instance
{
public function __construct()
{
parent::__construct();
$this->_adapter = new Adapter\Model;
}
public function authenticate($credentials = NULL)
{
$this->_adapter->setOptions($credentials);
$response = parent::authenticate();
if($response->isValid())
{
$identity = $response->getIdentity();
$user = User::find($identity['id']);
$this->setUser($user);
return true;
}
else
{
if($response->getCode() != \Zend_Auth_Result::FAILURE_UNCATEGORIZED)
{
foreach($response->getMessages() as $message)
\DF\Flash::addMessage($message);
}
return false;
}
}
<?php
namespace DF\Auth;
use \Entity\User;
class Model extends Instance
{
public function __construct()
{
parent::__construct();
$this->_adapter = new Adapter\Model;
}
public function authenticate($credentials = NULL)
{
$this->_adapter->setOptions($credentials);
$response = parent::authenticate();
if($response->isValid())
{
$identity = $response->getIdentity();
$user = User::find($identity['id']);
$this->setUser($user);
return true;
}
else
{
if($response->getCode() != \Zend_Auth_Result::FAILURE_UNCATEGORIZED)
{
foreach($response->getMessages() as $message)
\DF\Flash::addMessage($message);
}
return false;
}
}
}

View File

@ -1,12 +1,12 @@
<?php
namespace DF\Auth\Storage;
class Session extends \Zend_Auth_Storage_Session
{
public function __construct($namespace = 'default', $member = self::MEMBER_DEFAULT)
{
$this->_namespace = $namespace;
$this->_member = $member;
$this->_session = \DF\Session::get('zend_auth_'.$this->_namespace);
}
<?php
namespace DF\Auth\Storage;
class Session extends \Zend_Auth_Storage_Session
{
public function __construct($namespace = 'default', $member = self::MEMBER_DEFAULT)
{
$this->_namespace = $namespace;
$this->_member = $member;
$this->_session = \DF\Session::get('zend_auth_'.$this->_namespace);
}
}

View File

@ -1,199 +1,199 @@
<?php
/**
* A static interface to the Zend_Cache class.
*/
namespace DF;
class Cache
{
/**
* User Cache
*/
// Load data from the cache.
public static function load($id)
{
$cache = self::getCache();
return $cache->load($id);
}
// Alias of the "load" function.
public static function get($id, $default = NULL)
{
return self::load($id);
}
// Test whether an ID is present in the cache.
public static function test($id)
{
$cache = self::getCache();
return $cache->test($id);
}
// Save an item to the cache.
public static function save($data, $id, $tags = array(), $specificLifetime = false)
{
$cache = self::getCache();
return $cache->save($data, $id, $tags, $specificLifetime);
}
// Alias for the "set" function.
public static function set($data, $id, $tags = array(), $specificLifetime = false)
{
self::save($data, $id, $tags, $specificLifetime);
}
// Special callback function to get or save a new cache entry.
public static function getOrSet($id, $default = NULL, $tags = array(), $specificLifetime = false)
{
$result = self::load($id);
if ($result === false)
{
$result = (is_callable($default)) ? $default() : $default;
if ($result !== null)
{
self::save($result, $id, $tags, $specificLifetime);
}
}
return $result;
}
// Delete an item from the cache.
public static function remove($id)
{
$cache = self::getCache();
return $cache->remove($id);
}
// Clean the cache.
public static function clean($mode = 'all', $tags = array())
{
if ($mode == 'all' && $tags)
$mode = \Zend_Cache::CLEANING_MODE_MATCHING_TAG;
$cache = self::getCache();
return $cache->clean($mode, $tags);
}
// Get all cache keys.
public static function getKeys()
{
$cache = self::getCache();
return $cache->getIds();
}
// Retrieve or initialize the cache.
protected static $_user_cache;
public static function getCache()
{
return self::getUserCache();
}
public static function getUserCache()
{
if (!is_object(self::$_user_cache))
{
$frontend_name = 'Core';
$frontend_options = array(
'cache_id_prefix' => self::getSitePrefix().'_user_',
'lifetime' => 3600,
'automatic_serialization' => true
);
// Choose the most optimal caching mechanism available.
list($backend_name, $backend_options) = self::getBackendCache();
self::$_user_cache = \Zend_Cache::factory($frontend_name, $backend_name, $frontend_options, $backend_options);
}
return self::$_user_cache;
}
/**
* Page Cache
*/
public static function page()
{
$auth = \Zend_Registry::get('auth');
if (!$auth->isLoggedIn() && !\DF\Flash::hasMessages())
{
$page_cache = self::getPageCache();
$page_cache->start();
}
}
protected static $_page_cache;
public static function getPageCache()
{
if (!is_object(self::$_page_cache))
{
$frontend_name = 'Page';
$frontend_options = array(
'cache_id_prefix' => self::getSitePrefix().'_page_',
'lifetime' => 3600,
'automatic_serialization' => true,
'default_options' => array(
'cache_with_session_variables' => TRUE,
'cache_with_cookie_variables' => TRUE,
'make_id_with_session_variables' => FALSE,
'make_id_with_cookie_variables' => FALSE,
),
);
// Choose the most optimal caching mechanism available.
list($backend_name, $backend_options) = self::getBackendCache();
self::$_page_cache = \Zend_Cache::factory($frontend_name, $backend_name, $frontend_options, $backend_options);
}
return self::$_page_cache;
}
/**
* Generic Cache Details
*/
public static function getSitePrefix()
{
$folders = explode(DIRECTORY_SEPARATOR, DF_INCLUDE_ROOT);
$base_folder = @array_pop($folders);
if (strpos($base_folder, '.') !== FALSE)
$base_folder = substr($base_folder, 0, strpos($base_folder, '.'));
return ($base_folder) ? preg_replace("/[^a-zA-Z0-9]/", "", $base_folder) : 'default';
}
public static function getBackendCache()
{
$cache_dir = DF_INCLUDE_CACHE;
$backend_options = array();
if (extension_loaded('wincache') && class_exists('Zend_Cache_Backend_WinCache'))
{
$backend_name = 'WinCache';
}
else if (extension_loaded('xcache'))
{
$backend_name = 'Xcache';
}
else if (extension_loaded('apc'))
{
$backend_name = 'Apc';
}
else
{
$backend_name = 'File';
$backend_options = array(
'cache_dir' => $cache_dir,
'file_name_prefix' => 'df_cache',
'hashed_directory_perm' => 0777,
'cache_file_perm' => 0777,
);
}
return array($backend_name, $backend_options);
}
<?php
/**
* A static interface to the Zend_Cache class.
*/
namespace DF;
class Cache
{
/**
* User Cache
*/
// Load data from the cache.
public static function load($id)
{
$cache = self::getCache();
return $cache->load($id);
}
// Alias of the "load" function.
public static function get($id, $default = NULL)
{
return self::load($id);
}
// Test whether an ID is present in the cache.
public static function test($id)
{
$cache = self::getCache();
return $cache->test($id);
}
// Save an item to the cache.
public static function save($data, $id, $tags = array(), $specificLifetime = false)
{
$cache = self::getCache();
return $cache->save($data, $id, $tags, $specificLifetime);
}
// Alias for the "set" function.
public static function set($data, $id, $tags = array(), $specificLifetime = false)
{
self::save($data, $id, $tags, $specificLifetime);
}
// Special callback function to get or save a new cache entry.
public static function getOrSet($id, $default = NULL, $tags = array(), $specificLifetime = false)
{
$result = self::load($id);
if ($result === false)
{
$result = (is_callable($default)) ? $default() : $default;
if ($result !== null)
{
self::save($result, $id, $tags, $specificLifetime);
}
}
return $result;
}
// Delete an item from the cache.
public static function remove($id)
{
$cache = self::getCache();
return $cache->remove($id);
}
// Clean the cache.
public static function clean($mode = 'all', $tags = array())
{
if ($mode == 'all' && $tags)
$mode = \Zend_Cache::CLEANING_MODE_MATCHING_TAG;
$cache = self::getCache();
return $cache->clean($mode, $tags);
}
// Get all cache keys.
public static function getKeys()
{
$cache = self::getCache();
return $cache->getIds();
}
// Retrieve or initialize the cache.
protected static $_user_cache;
public static function getCache()
{
return self::getUserCache();
}
public static function getUserCache()
{
if (!is_object(self::$_user_cache))
{
$frontend_name = 'Core';
$frontend_options = array(
'cache_id_prefix' => self::getSitePrefix().'_user_',
'lifetime' => 3600,
'automatic_serialization' => true
);
// Choose the most optimal caching mechanism available.
list($backend_name, $backend_options) = self::getBackendCache();
self::$_user_cache = \Zend_Cache::factory($frontend_name, $backend_name, $frontend_options, $backend_options);
}
return self::$_user_cache;
}
/**
* Page Cache
*/
public static function page()
{
$auth = \Zend_Registry::get('auth');
if (!$auth->isLoggedIn() && !\DF\Flash::hasMessages())
{
$page_cache = self::getPageCache();
$page_cache->start();
}
}
protected static $_page_cache;
public static function getPageCache()
{
if (!is_object(self::$_page_cache))
{
$frontend_name = 'Page';
$frontend_options = array(
'cache_id_prefix' => self::getSitePrefix().'_page_',
'lifetime' => 3600,
'automatic_serialization' => true,
'default_options' => array(
'cache_with_session_variables' => TRUE,
'cache_with_cookie_variables' => TRUE,
'make_id_with_session_variables' => FALSE,
'make_id_with_cookie_variables' => FALSE,
),
);
// Choose the most optimal caching mechanism available.
list($backend_name, $backend_options) = self::getBackendCache();
self::$_page_cache = \Zend_Cache::factory($frontend_name, $backend_name, $frontend_options, $backend_options);
}
return self::$_page_cache;
}
/**
* Generic Cache Details
*/
public static function getSitePrefix()
{
$folders = explode(DIRECTORY_SEPARATOR, DF_INCLUDE_ROOT);
$base_folder = @array_pop($folders);
if (strpos($base_folder, '.') !== FALSE)
$base_folder = substr($base_folder, 0, strpos($base_folder, '.'));
return ($base_folder) ? preg_replace("/[^a-zA-Z0-9]/", "", $base_folder) : 'default';
}
public static function getBackendCache()
{
$cache_dir = DF_INCLUDE_CACHE;
$backend_options = array();
if (extension_loaded('wincache') && class_exists('Zend_Cache_Backend_WinCache'))
{
$backend_name = 'WinCache';
}
else if (extension_loaded('xcache'))
{
$backend_name = 'Xcache';
}
else if (extension_loaded('apc'))
{
$backend_name = 'Apc';
}
else
{
$backend_name = 'File';
$backend_options = array(
'cache_dir' => $cache_dir,
'file_name_prefix' => 'df_cache',
'hashed_directory_perm' => 0777,
'cache_file_perm' => 0777,
);
}
return array($backend_name, $backend_options);
}
}

View File

@ -1,227 +1,227 @@
<?php
/**
* Calendar generation helper
*/
namespace DF;
class Calendar
{
protected $_datecode;
protected $_month;
protected $_year;
protected $_start_timestamp;
protected $_mid_timestamp;
protected $_end_timestamp;
protected $_records;
public function __construct($datecode = NULL)
{
$datecode = ($datecode) ? (int)$datecode : date('Ym');
$this->setDateCode($datecode);
$this->_records = array();
}
public function setDateCode($datecode)
{
$this->_datecode = $datecode;
$this->_month = (int)substr($datecode, 4, 2);
$this->_year = (int)substr($datecode, 0, 4);
$mid_timestamp = mktime(0, 0, 0, $this->_month, 15, $this->_year);
if (!$this->isValidDate($mid_timestamp))
{
throw new \DF\Exception\DisplayOnly('Invalid date/time specified.');
}
$this->_start_timestamp = mktime(0, 0, 0, $this->_month, 1, $this->_year);
$this->_mid_timestamp = $mid_timestamp;
$this->_end_timestamp = mktime(0, 0, 0, $this->_month+1, 1, $this->_year);
}
public function getDateCode()
{
return $this->_datecode;
}
public function getTimestamps()
{
return array(
'start' => $this->_start_timestamp,
'mid' => $this->_mid_timestamp,
'end' => $this->_end_timestamp,
);
}
public function setRecords($records)
{
$this->_records = $records;
}
public function fetch($records = NULL)
{
if ($records)
$this->setRecords($records);
$return_vars = array();
// Current page.
$current_page_timestamp = $this->_mid_timestamp;
$return_vars['current_page_datecode'] = date('Ym', $current_page_timestamp);
$return_vars['current_page_text'] = date('F Y', $current_page_timestamp);
// Surrounding pages.
$prev_page_timestamp = strtotime("-1 month", $this->_mid_timestamp);
if ($this->isValidDate($prev_page_timestamp))
{
$return_vars['prev_page_datecode'] = date('Ym', $prev_page_timestamp);
$return_vars['prev_page_text'] = date('F Y', $prev_page_timestamp);
}
$next_page_timestamp = strtotime("+1 month", $this->_mid_timestamp);
if ($this->isValidDate($next_page_timestamp))
{
$return_vars['next_page_datecode'] = date('Ym', $next_page_timestamp);
$return_vars['next_page_text'] = date('F Y', $next_page_timestamp);
}
// Retrieves the day (Sunday = 0, Monday = 1, etc.) of the first day of the month.
$first_calendar_day = date('w', $this->_start_timestamp);
$days_in_previous_month = date('t', $prev_page_timestamp);
// Creates the cells containing the previous month's days, starting the first row.
for($i = 0; $i < $first_calendar_day+1; $i++)
{
$calendar_days[$i+1] = array(
'day' => $days_in_previous_month - ($first_calendar_day - $i) + 1,
'disabled' => true,
'records' => array(),
);
}
// Creates the cells containing the current month's days.
$k = $first_calendar_day+1;
$starting_index = $k;
$days_in_current_month = date('t', $this->_mid_timestamp);
for($i = 0; $i < $days_in_current_month; $i++)
{
$calendar_days[$i+$k] = array(
'day' => $i+1,
'records' => array()
);
}
// Creates the cells containing the next month's days, finishing the last row.
$k = $days_in_current_month + $k - 1;
$last_calendar_day = date('w', $this->_end_timestamp);
$j = 1;
for($i = $last_calendar_day+1; $i <= 7; $i++)
{
$calendar_days[$k+$j] = array(
'day' => $j,
'disabled' => true,
'class' => 'disabled',
'records' => array()
);
$j++;
}
$today_info = array('year' => date('Y'), 'month' => date('m'), 'day' => date('d'));
$today = new \Zend_Date($today_info);
$today_timestamp = $today->getTimestamp();
// Create timestamp values for each day.
$day_timestamps = array();
for($i = 0; $i < $days_in_current_month; $i++)
{
$date_info = array(
'year' => $this->_year,
'month' => $this->_month,
'day' => $i+1,
);
$date = new \Zend_Date($date_info);
$date_timestamp = $date->getTimestamp();
$k = $starting_index+$i;
$day_timestamps[$k] = array(
'start' => $date_timestamp,
'end' => $date_timestamp + 86399,
);
if ($date_timestamp == $today_timestamp)
$calendar_days[$k]['class'] = 'blue';
}
// Populate records into days.
if ($this->_records)
{
foreach($this->_records as $record)
{
// Determine the "start" and "end" timestamps for the item.
if (isset($record['timestamp']))
{
$start_timestamp = (int)$record['timestamp'];
$end_timestamp = (int)$record['timestamp'];
}
else if (isset($record['start_timestamp']))
{
$start_timestamp = (int)$record['start_timestamp'];
$end_timestamp = (int)$record['end_timestamp'];
}
if ($start_timestamp && $end_timestamp)
{
foreach($day_timestamps as $i => $timestamps)
{
$day_start = $timestamps['start'];
$day_end = $timestamps['end'];
$day_record = $record;
$day_record['starts_today'] = ($start_timestamp > $day_start && $start_timestamp < $day_end);
$day_record['ends_today'] = ($end_timestamp > $day_start && $end_timestamp < $day_end);
$day_record['only_today'] = ($day_record['starts_today'] && $day_record['ends_today']);
if ($day_record['is_all_day'])
$day_record['time'] = 'All Day';
elseif ($day_record['only_today'])
$day_record['time'] = date('g:ia', $start_timestamp).' to '.date('g:ia', $end_timestamp);
elseif ($day_record['starts_today'])
$day_record['time'] = 'Starts '.date('g:ia', $start_timestamp);
elseif ($day_record['ends_today'])
$day_record['time'] = 'Ends '.date('g:ia', $end_timestamp);
else
$day_record['time'] = 'All Day';
if ($start_timestamp < $day_end && $end_timestamp > $day_start)
{
$calendar_days[$i]['records'][] = $day_record;
}
}
}
}
}
// Reassign calendar days into rows.
$new_calendar_days = array();
foreach($calendar_days as $calendar_day_num => $calendar_day_info)
{
$current_row = floor(($calendar_day_num-1) / 7);
$new_calendar_days[$current_row][] = $calendar_day_info;
}
$return_vars['days'] = $new_calendar_days;
return $return_vars;
}
protected function isValidDate($timestamp)
{
$threshold = 86400 * 365 * 5; // 5 Years
return ($timestamp >= (time() - $threshold) && $timestamp <= (time() + $threshold));
}
<?php
/**
* Calendar generation helper
*/
namespace DF;
class Calendar
{
protected $_datecode;
protected $_month;
protected $_year;
protected $_start_timestamp;
protected $_mid_timestamp;
protected $_end_timestamp;
protected $_records;
public function __construct($datecode = NULL)
{
$datecode = ($datecode) ? (int)$datecode : date('Ym');
$this->setDateCode($datecode);
$this->_records = array();
}
public function setDateCode($datecode)
{
$this->_datecode = $datecode;
$this->_month = (int)substr($datecode, 4, 2);
$this->_year = (int)substr($datecode, 0, 4);
$mid_timestamp = mktime(0, 0, 0, $this->_month, 15, $this->_year);
if (!$this->isValidDate($mid_timestamp))
{
throw new \DF\Exception\DisplayOnly('Invalid date/time specified.');
}
$this->_start_timestamp = mktime(0, 0, 0, $this->_month, 1, $this->_year);
$this->_mid_timestamp = $mid_timestamp;
$this->_end_timestamp = mktime(0, 0, 0, $this->_month+1, 1, $this->_year);
}
public function getDateCode()
{
return $this->_datecode;
}
public function getTimestamps()
{
return array(
'start' => $this->_start_timestamp,
'mid' => $this->_mid_timestamp,
'end' => $this->_end_timestamp,
);
}
public function setRecords($records)
{
$this->_records = $records;
}
public function fetch($records = NULL)
{
if ($records)
$this->setRecords($records);
$return_vars = array();
// Current page.
$current_page_timestamp = $this->_mid_timestamp;
$return_vars['current_page_datecode'] = date('Ym', $current_page_timestamp);
$return_vars['current_page_text'] = date('F Y', $current_page_timestamp);
// Surrounding pages.
$prev_page_timestamp = strtotime("-1 month", $this->_mid_timestamp);
if ($this->isValidDate($prev_page_timestamp))
{
$return_vars['prev_page_datecode'] = date('Ym', $prev_page_timestamp);
$return_vars['prev_page_text'] = date('F Y', $prev_page_timestamp);
}
$next_page_timestamp = strtotime("+1 month", $this->_mid_timestamp);
if ($this->isValidDate($next_page_timestamp))
{
$return_vars['next_page_datecode'] = date('Ym', $next_page_timestamp);
$return_vars['next_page_text'] = date('F Y', $next_page_timestamp);
}
// Retrieves the day (Sunday = 0, Monday = 1, etc.) of the first day of the month.
$first_calendar_day = date('w', $this->_start_timestamp);
$days_in_previous_month = date('t', $prev_page_timestamp);
// Creates the cells containing the previous month's days, starting the first row.
for($i = 0; $i < $first_calendar_day+1; $i++)
{
$calendar_days[$i+1] = array(
'day' => $days_in_previous_month - ($first_calendar_day - $i) + 1,
'disabled' => true,
'records' => array(),
);
}
// Creates the cells containing the current month's days.
$k = $first_calendar_day+1;
$starting_index = $k;
$days_in_current_month = date('t', $this->_mid_timestamp);
for($i = 0; $i < $days_in_current_month; $i++)
{
$calendar_days[$i+$k] = array(
'day' => $i+1,
'records' => array()
);
}
// Creates the cells containing the next month's days, finishing the last row.
$k = $days_in_current_month + $k - 1;
$last_calendar_day = date('w', $this->_end_timestamp);
$j = 1;
for($i = $last_calendar_day+1; $i <= 7; $i++)
{
$calendar_days[$k+$j] = array(
'day' => $j,
'disabled' => true,
'class' => 'disabled',
'records' => array()
);
$j++;
}
$today_info = array('year' => date('Y'), 'month' => date('m'), 'day' => date('d'));
$today = new \Zend_Date($today_info);
$today_timestamp = $today->getTimestamp();
// Create timestamp values for each day.
$day_timestamps = array();
for($i = 0; $i < $days_in_current_month; $i++)
{
$date_info = array(
'year' => $this->_year,
'month' => $this->_month,
'day' => $i+1,
);
$date = new \Zend_Date($date_info);
$date_timestamp = $date->getTimestamp();
$k = $starting_index+$i;
$day_timestamps[$k] = array(
'start' => $date_timestamp,
'end' => $date_timestamp + 86399,
);
if ($date_timestamp == $today_timestamp)
$calendar_days[$k]['class'] = 'blue';
}
// Populate records into days.
if ($this->_records)
{
foreach($this->_records as $record)
{
// Determine the "start" and "end" timestamps for the item.
if (isset($record['timestamp']))
{
$start_timestamp = (int)$record['timestamp'];
$end_timestamp = (int)$record['timestamp'];
}
else if (isset($record['start_timestamp']))
{
$start_timestamp = (int)$record['start_timestamp'];
$end_timestamp = (int)$record['end_timestamp'];
}
if ($start_timestamp && $end_timestamp)
{
foreach($day_timestamps as $i => $timestamps)
{
$day_start = $timestamps['start'];
$day_end = $timestamps['end'];
$day_record = $record;
$day_record['starts_today'] = ($start_timestamp > $day_start && $start_timestamp < $day_end);
$day_record['ends_today'] = ($end_timestamp > $day_start && $end_timestamp < $day_end);
$day_record['only_today'] = ($day_record['starts_today'] && $day_record['ends_today']);
if ($day_record['is_all_day'])
$day_record['time'] = 'All Day';
elseif ($day_record['only_today'])
$day_record['time'] = date('g:ia', $start_timestamp).' to '.date('g:ia', $end_timestamp);
elseif ($day_record['starts_today'])
$day_record['time'] = 'Starts '.date('g:ia', $start_timestamp);
elseif ($day_record['ends_today'])
$day_record['time'] = 'Ends '.date('g:ia', $end_timestamp);
else
$day_record['time'] = 'All Day';
if ($start_timestamp < $day_end && $end_timestamp > $day_start)
{
$calendar_days[$i]['records'][] = $day_record;
}
}
}
}
}
// Reassign calendar days into rows.
$new_calendar_days = array();
foreach($calendar_days as $calendar_day_num => $calendar_day_info)
{
$current_row = floor(($calendar_day_num-1) / 7);
$new_calendar_days[$current_row][] = $calendar_day_info;
}
$return_vars['days'] = $new_calendar_days;
return $return_vars;
}
protected function isValidDate($timestamp)
{
$threshold = 86400 * 365 * 5; // 5 Years
return ($timestamp >= (time() - $threshold) && $timestamp <= (time() + $threshold));
}
}

View File

@ -1,94 +1,88 @@
<?php
/**
* Zend_Config Wrapper Class
*/
namespace DF;
require_once('Zend/Config.php');
class Config
{
protected $_baseFolder;
protected $_loaded_configs;
public function __construct($baseFolder)
{
$this->_loaded_configs = array();
if(is_dir($baseFolder))
$this->_baseFolder = $baseFolder;
else
throw new \Zend_Exception("Invalid base folder for configurations.");
}
public function preload($configs)
{
$config_array = (is_array($configs)) ? $configs : array($configs);
foreach($config_array as $config_item)
{
$this->__get($config_item);
}
}
public function __set($name, $value)
{
throw new \Zend_Exception("Configuration is read-only.");
}
public function __get($name)
{
if (!isset($this->_loaded_configs[$name]))
{
$config_name = str_replace(array('.','..'), array('', ''), $name);
$config_base = $this->_baseFolder.DIRECTORY_SEPARATOR.$config_name;
if (is_dir($config_base))
return new self($config_base); // Return entire directories.
else
$this_config = $this->getFile($config_base); // Return single files.
$this->_loaded_configs[$name] = $this_config;
}
return $this->_loaded_configs[$name];
}
public function getFile($config_base)
{
if (file_exists($config_base))
return new \Zend_Config(require $config_base);
if (file_exists($config_base.'.conf.php'))
return new \Zend_Config(require $config_base.'.conf.php');
else if (file_exists($config_base.'.ini'))
return new \Zend_Config_Ini($config_base.'.ini');
else if (file_exists($config_base.'.xml'))
return new \Zend_Config_Xml($config_base.'.xml');
else
return new \Zend_Config(array());
}
/**
* Static Functions
*/
public static function loadConfig($directory)
{
return new self($directory);
}
public static function loadModuleConfig($directory)
{
$module_config = array();
foreach(new \DirectoryIterator($directory) as $item)
{
if($item->isDir() && !$item->isDot())
{
$config = $item->getPathname().DIRECTORY_SEPARATOR.'config';
if(file_exists($config))
$module_config[$item->getFilename()] = new self($config);
}
}
return $module_config;
}
<?php
namespace DF;
class Config
{
protected $_baseFolder;
protected $_loaded_configs;
public function __construct($baseFolder)
{
$this->_loaded_configs = array();
if(is_dir($baseFolder))
$this->_baseFolder = $baseFolder;
else
throw new \Exception("Invalid base folder for configurations.");
}
public function preload($configs)
{
$config_array = (is_array($configs)) ? $configs : array($configs);
foreach($config_array as $config_item)
{
$this->__get($config_item);
}
}
public function __set($name, $value)
{
throw new \Exception("Configuration is read-only.");
}
public function __get($name)
{
if (!isset($this->_loaded_configs[$name]))
{
$config_name = str_replace(array('.','..'), array('', ''), $name);
$config_base = $this->_baseFolder.DIRECTORY_SEPARATOR.$config_name;
if (is_dir($config_base))
return new self($config_base); // Return entire directories.
else
$this_config = $this->getFile($config_base); // Return single files.
$this->_loaded_configs[$name] = $this_config;
}
return $this->_loaded_configs[$name];
}
public function getFile($config_base)
{
if (file_exists($config_base))
return new \Phalcon\Config(require $config_base);
if (file_exists($config_base.'.conf.php'))
return new \Phalcon\Config\Adapter\Php($config_base.'.conf.php');
else if (file_exists($config_base.'.ini'))
return new \Phalcon\Config\Adapter\Ini($config_base.'.ini');
else if (file_exists($config_base.'.json'))
return new \Phalcon\Config\Adapter\Json($config_base.'.json');
else
return new \Phalcon\Config(array());
}
/**
* Static Functions
*/
public static function loadConfig($directory)
{
return new self($directory);
}
public static function loadModuleConfig($directory)
{
$module_config = array();
foreach(new \DirectoryIterator($directory) as $item)
{
if($item->isDir() && !$item->isDot())
{
$config = $item->getPathname().DIRECTORY_SEPARATOR.'config';
if(file_exists($config))
$module_config[$item->getFilename()] = new self($config);
}
}
return $module_config;
}
}

View File

@ -1,385 +1,385 @@
<?php
namespace DF\Controller;
use DF\Exception\NotLoggedIn;
use DF\Exception\PermissionDenied;
use DF\Url;
use DF\Flash;
class Action extends \Zend_Controller_Action
{
/**
* @var \DF\Config
*/
public $config;
/**
* @var array
*/
public $module_config;
/**
* @var \DF\Config
*/
public $current_module_config;
/**
* @var \DF\Auth\Instance
*/
public $auth;
/**
* @var \DF\Acl\Instance
*/
public $acl;
/**
* @var \Doctrine\ORM\EntityManager
*/
public $em;
/**
* @var string
*/
public $module_name;
/**
* @var boolean
*/
public $test_mode;
public function init()
{
$this->config = $this->view->config = \Zend_Registry::get('config');
$this->module_config = $this->view->module_config = \Zend_Registry::get('module_config');
$this->auth = $this->view->auth = \Zend_Registry::get('auth');
$this->acl = $this->view->acl = \Zend_Registry::get('acl');
$this->em = \Zend_Registry::get('em');
$this->module_name = $this->_getModuleName();
\Zend_Registry::set('module_name', $this->module_name);
if (isset($this->module_config[$this->module_name]))
$this->current_module_config = $this->module_config[$this->module_name];
else
$this->current_module_config = NULL;
$this->test_mode = $this->isTestMode();
if ($this->test_mode)
{
$front = $this->getFrontController();
$front->setParam('noErrorHandler', true);
}
$this->preInit();
$isAllowed = $this->permissions();
if (!$isAllowed)
{
if (!\DF\Auth::isLoggedIn())
throw new NotLoggedIn;
else
throw new PermissionDenied;
}
$this->postInit();
}
public function preInit() {}
public function postInit() {}
protected function _getModuleName()
{
$front = $this->getFrontController();
$request = $this->getRequest();
$module = $request->getModuleName();
if (!$module)
$module = $front->getDispatcher()->getDefaultModule();
return $module;
}
protected function _getControllerName()
{
return $this->getRequest()->getControllerName();
}
protected function _getActionName()
{
return $this->getRequest()->getActionName();
}
protected function _getMvcPath($appendPath = null)
{
if (!isset($this->_mvcPath)) {
$front = $this->getFrontController();
$module = $this->_getModuleName();
$dirs = $front->getControllerDirectory();
$this->_mvcPath = dirname($dirs[$module]);
}
if (null !== $appendPath) {
if (!is_string($appendPath)) {
throw new \Zend_Controller_Action_Exception();
}
return $this->_mvcPath . DIRECTORY_SEPARATOR . $appendPath;
}
return $this->_mvcPath;
}
public function permissions()
{
return true;
}
public function preDispatch()
{
$is_ajax = ($this->isAjax());
$this->view->is_ajax = $is_ajax;
if ($is_ajax)
\Zend_Layout::getMvcInstance()->disableLayout();
if ($this->hasParam('debug') && $this->_getParam('debug') === 'true')
{
error_reporting(E_ALL & ~E_STRICT);
ini_set('display_errors', 1);
}
}
public function postDispatch()
{
$db_log = $this->em->getConnection()->getConfiguration()->getSQLLogger();
if ($db_log instanceof \Doctrine\DBAL\Logging\SQLLogger)
{
if (DF_APPLICATION_ENV != "production" || $this->acl->isAllowed('administer all'))
{
$logger = new \Zend_Log(new \Zend_Log_Writer_Firebug);
foreach((array)$db_log->queries as $query)
$logger->info(round($query['executionMS'], 5).': '.$query['sql']);
}
}
}
public function isAjax()
{
return $this->_request->isXmlHttpRequest();
}
public function renderJson($json_data)
{
$this->doNotRender();
$this->getResponse()->appendBody(\Zend_Json::encode($json_data));
}
public function getResource($resource_name)
{
if( isset($this->getInvokeArg('bootstrap')->getContainer()->{$resource_name}) )
return $this->getInvokeArg('bootstrap')->getContainer()->{$resource_name};
else
return false;
}
public function flash($message, $level = Flash::INFO)
{
$this->alert($message, $level);
}
public function alert($message, $level = Flash::INFO)
{
$func_args = func_get_args();
call_user_func_array('\DF\Flash::addMessage', $func_args);
}
public function redirect($url, array $options = null)
{
if( $options === null )
{
$options = array(
'prependBase' => false,
'exit' => true,
);
}
$this->_helper->_redirector->gotoUrl($url, $options);
}
protected function redirectHome()
{
$this->redirect(Url::route(array(
'module' => 'default',
'controller' => 'index',
'action' => 'index',
)));
}
protected function redirectHere()
{
$this->redirect(Url::route(array(), NULL, FALSE));
}
protected function redirectToRoute()
{
$func_args = func_get_args();
$routed_url = call_user_func_array('\DF\Url::route', $func_args);
$this->redirect($routed_url);
}
protected function redirectFromHere()
{
$func_args = func_get_args();
$routed_url = Url::route($func_args[0], NULL, FALSE);
$this->redirect($routed_url);
}
protected function doNotRender()
{
$this->_helper->viewRenderer->setNoRender();
\Zend_Layout::getMvcInstance()->disableLayout();
}
protected function isTestMode()
{
return (defined('DF_TEST_MODE') && DF_TEST_MODE == true);
}
protected function renderForm($form, $mode = 'edit', $form_title = NULL)
{
$this->_helper->viewRenderer->setNoRender();
$body = '';
if ($form_title)
{
// Show visible title.
$body .= '<h2>'.$form_title.'</h2>';
}
if ($this->isAjax())
{
// Show title if otherwise not set.
if (!$form_title)
{
$title = current($this->view->headTitle()->getIterator());
$body .= '<h2 class="page_title">'.$title.'</h2>';
}
// Proper action routing.
if (!$form->getAction())
{
$form->setAction(\DF\Url::current());
}
}
// Form render mode.
if ($mode == 'edit')
$body .= $form->render();
else
$body .= $form->renderView();
$this->getResponse()->appendBody($body);
}
/**
* Referrer storage
*/
protected function storeReferrer($namespace = 'default', $loose = true)
{
$session = \DF\Session::get('referrer_'.$namespace);
if( !isset($session->url) || ($loose && isset($session->url) && Url::current() != Url::referrer()) )
$session->url = Url::referrer();
}
protected function getStoredReferrer($namespace = 'default')
{
$session = \DF\Session::get('referrer_'.$namespace);
return $session->url;
}
protected function clearStoredReferrer($namespace = 'default')
{
$session = \DF\Session::get('referrer_'.$namespace);
unset($session->url);
}
protected function redirectToStoredReferrer($namespace = 'default', $default_url = false)
{
$referrer = $this->getStoredReferrer($namespace);
$this->clearStoredReferrer($namespace);
if( trim($referrer) == '' )
if( $default_url )
$referrer = $default_url;
else
$referrer = Url::baseUrl();
$this->redirect($referrer);
}
protected function redirectToReferrer($default = false)
{
if( !$default )
$default = Url::baseUrl();
$this->redirect(Url::referrer($default));
}
/**
* CSRF security token validation
*/
protected function validateToken($token, $redirect = true)
{
if(!\DF\Csrf::validateToken($token) )
{
Flash::addMessage("Invalid Security Token");
if( $redirect )
$this->redirectToReferrer();
else
return false;
}
else
{
return true;
}
}
/**
* SSL Handling
*/
protected function forceSecure()
{
if (DF_APPLICATION_ENV == 'production' && !DF_IS_SECURE)
{
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit;
}
}
/**
* Parameter Handling
*/
protected function convertGetToParam($params)
{
if (!is_array($params))
$params = array($params);
$url_changes = array();
foreach($params as $param)
{
if (isset($_GET[$param]))
$url_changes[$param] = $_GET[$param];
}
if (count($url_changes) > 0)
$this->redirectFromHere($url_changes);
}
<?php
namespace DF\Controller;
use DF\Exception\NotLoggedIn;
use DF\Exception\PermissionDenied;
use DF\Url;
use DF\Flash;
class Action extends \Zend_Controller_Action
{
/**
* @var \DF\Config
*/
public $config;
/**
* @var array
*/
public $module_config;
/**
* @var \DF\Config
*/
public $current_module_config;
/**
* @var \DF\Auth\Instance
*/
public $auth;
/**
* @var \DF\Acl\Instance
*/
public $acl;
/**
* @var \Doctrine\ORM\EntityManager
*/
public $em;
/**
* @var string
*/
public $module_name;
/**
* @var boolean
*/
public $test_mode;
public function init()
{
$this->config = $this->view->config = \Zend_Registry::get('config');
$this->module_config = $this->view->module_config = \Zend_Registry::get('module_config');
$this->auth = $this->view->auth = \Zend_Registry::get('auth');
$this->acl = $this->view->acl = \Zend_Registry::get('acl');
$this->em = \Zend_Registry::get('em');
$this->module_name = $this->_getModuleName();
\Zend_Registry::set('module_name', $this->module_name);
if (isset($this->module_config[$this->module_name]))
$this->current_module_config = $this->module_config[$this->module_name];
else
$this->current_module_config = NULL;
$this->test_mode = $this->isTestMode();
if ($this->test_mode)
{
$front = $this->getFrontController();
$front->setParam('noErrorHandler', true);
}
$this->preInit();
$isAllowed = $this->permissions();
if (!$isAllowed)
{
if (!\DF\Auth::isLoggedIn())
throw new NotLoggedIn;
else
throw new PermissionDenied;
}
$this->postInit();
}
public function preInit() {}
public function postInit() {}
protected function _getModuleName()
{
$front = $this->getFrontController();
$request = $this->getRequest();
$module = $request->getModuleName();
if (!$module)
$module = $front->getDispatcher()->getDefaultModule();
return $module;
}
protected function _getControllerName()
{
return $this->getRequest()->getControllerName();
}
protected function _getActionName()
{
return $this->getRequest()->getActionName();
}
protected function _getMvcPath($appendPath = null)
{
if (!isset($this->_mvcPath)) {
$front = $this->getFrontController();
$module = $this->_getModuleName();
$dirs = $front->getControllerDirectory();
$this->_mvcPath = dirname($dirs[$module]);
}
if (null !== $appendPath) {
if (!is_string($appendPath)) {
throw new \Zend_Controller_Action_Exception();
}
return $this->_mvcPath . DIRECTORY_SEPARATOR . $appendPath;
}
return $this->_mvcPath;
}
public function permissions()
{
return true;
}
public function preDispatch()
{
$is_ajax = ($this->isAjax());
$this->view->is_ajax = $is_ajax;
if ($is_ajax)
\Zend_Layout::getMvcInstance()->disableLayout();
if ($this->hasParam('debug') && $this->_getParam('debug') === 'true')
{
error_reporting(E_ALL & ~E_STRICT);
ini_set('display_errors', 1);
}
}
public function postDispatch()
{
$db_log = $this->em->getConnection()->getConfiguration()->getSQLLogger();
if ($db_log instanceof \Doctrine\DBAL\Logging\SQLLogger)
{
if (DF_APPLICATION_ENV != "production" || $this->acl->isAllowed('administer all'))
{
$logger = new \Zend_Log(new \Zend_Log_Writer_Firebug);
foreach((array)$db_log->queries as $query)
$logger->info(round($query['executionMS'], 5).': '.$query['sql']);
}
}
}
public function isAjax()
{
return $this->_request->isXmlHttpRequest();
}
public function renderJson($json_data)
{
$this->doNotRender();
$this->getResponse()->appendBody(\Zend_Json::encode($json_data));
}
public function getResource($resource_name)
{
if( isset($this->getInvokeArg('bootstrap')->getContainer()->{$resource_name}) )
return $this->getInvokeArg('bootstrap')->getContainer()->{$resource_name};
else
return false;
}
public function flash($message, $level = Flash::INFO)
{
$this->alert($message, $level);
}
public function alert($message, $level = Flash::INFO)
{
$func_args = func_get_args();
call_user_func_array('\DF\Flash::addMessage', $func_args);
}
public function redirect($url, array $options = null)
{
if( $options === null )
{
$options = array(
'prependBase' => false,
'exit' => true,
);
}
$this->_helper->_redirector->gotoUrl($url, $options);
}
protected function redirectHome()
{
$this->redirect(Url::route(array(
'module' => 'default',
'controller' => 'index',
'action' => 'index',
)));
}
protected function redirectHere()
{
$this->redirect(Url::route(array(), NULL, FALSE));
}
protected function redirectToRoute()
{
$func_args = func_get_args();
$routed_url = call_user_func_array('\DF\Url::route', $func_args);
$this->redirect($routed_url);
}
protected function redirectFromHere()
{
$func_args = func_get_args();
$routed_url = Url::route($func_args[0], NULL, FALSE);
$this->redirect($routed_url);
}
protected function doNotRender()
{
$this->_helper->viewRenderer->setNoRender();
\Zend_Layout::getMvcInstance()->disableLayout();
}
protected function isTestMode()
{
return (defined('DF_TEST_MODE') && DF_TEST_MODE == true);
}
protected function renderForm($form, $mode = 'edit', $form_title = NULL)
{
$this->_helper->viewRenderer->setNoRender();
$body = '';
if ($form_title)
{
// Show visible title.
$body .= '<h2>'.$form_title.'</h2>';
}
if ($this->isAjax())
{
// Show title if otherwise not set.
if (!$form_title)
{
$title = current($this->view->headTitle()->getIterator());
$body .= '<h2 class="page_title">'.$title.'</h2>';
}
// Proper action routing.
if (!$form->getAction())
{
$form->setAction(\DF\Url::current());
}
}
// Form render mode.
if ($mode == 'edit')
$body .= $form->render();
else
$body .= $form->renderView();
$this->getResponse()->appendBody($body);
}
/**
* Referrer storage
*/
protected function storeReferrer($namespace = 'default', $loose = true)
{
$session = \DF\Session::get('referrer_'.$namespace);
if( !isset($session->url) || ($loose && isset($session->url) && Url::current() != Url::referrer()) )
$session->url = Url::referrer();
}
protected function getStoredReferrer($namespace = 'default')
{
$session = \DF\Session::get('referrer_'.$namespace);
return $session->url;
}
protected function clearStoredReferrer($namespace = 'default')
{
$session = \DF\Session::get('referrer_'.$namespace);
unset($session->url);
}
protected function redirectToStoredReferrer($namespace = 'default', $default_url = false)
{
$referrer = $this->getStoredReferrer($namespace);
$this->clearStoredReferrer($namespace);
if( trim($referrer) == '' )
if( $default_url )
$referrer = $default_url;
else
$referrer = Url::baseUrl();
$this->redirect($referrer);
}
protected function redirectToReferrer($default = false)
{
if( !$default )
$default = Url::baseUrl();
$this->redirect(Url::referrer($default));
}
/**
* CSRF security token validation
*/
protected function validateToken($token, $redirect = true)
{
if(!\DF\Csrf::validateToken($token) )
{
Flash::addMessage("Invalid Security Token");
if( $redirect )
$this->redirectToReferrer();
else
return false;
}
else
{
return true;
}
}
/**
* SSL Handling
*/
protected function forceSecure()
{
if (DF_APPLICATION_ENV == 'production' && !DF_IS_SECURE)
{
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit;
}
}
/**
* Parameter Handling
*/
protected function convertGetToParam($params)
{
if (!is_array($params))
$params = array($params);
$url_changes = array();
foreach($params as $param)
{
if (isset($_GET[$param]))
$url_changes[$param] = $_GET[$param];
}
if (count($url_changes) > 0)
$this->redirectFromHere($url_changes);
}
}

56
app/library/DF/Csrf.php → phalcon/library/DF/Csrf.php Executable file → Normal file
View File

@ -1,29 +1,29 @@
<?php
namespace DF;
class Csrf
{
public static function getToken()
{
$session = new \Zend_Session_Namespace('csrf');
if( !isset($session->token) )
self::resetToken();
return $session->token;
}
public static function validateToken($token)
{
$session = new \Zend_Session_Namespace('csrf');
$old_token = $session->token;
self::resetToken();
return ($token == $old_token);
}
public static function resetToken()
{
$session = new \Zend_Session_Namespace('csrf');
$session->token = sprintf("%s:%d", md5(uniqid(mt_rand(), true)), time());
}
<?php
namespace DF;
class Csrf
{
public static function getToken()
{
$session = new \Zend_Session_Namespace('csrf');
if( !isset($session->token) )
self::resetToken();
return $session->token;
}
public static function validateToken($token)
{
$session = new \Zend_Session_Namespace('csrf');
$old_token = $session->token;
self::resetToken();
return ($token == $old_token);
}
public static function resetToken()
{
$session = new \Zend_Session_Namespace('csrf');
$session->token = sprintf("%s:%d", md5(uniqid(mt_rand(), true)), time());
}
}

View File

@ -1,71 +1,71 @@
<?php
/**
* Doctrine/DF Cache Connector
*/
namespace DF\Doctrine;
class Cache extends \Doctrine\Common\Cache\CacheProvider
{
protected function doFetch($id, $testCacheValidity = true)
{
return \DF\Cache::get($this->_filterCacheId($id));
}
protected function doContains($id)
{
return \DF\Cache::test($this->_filterCacheId($id));
}
protected function doSave($id, $data, $lifeTime = NULL)
{
if ($lifeTime == 0)
$lifeTime = NULL;
\DF\Cache::save($data, $this->_filterCacheId($id), array(), $lifeTime);
return true;
}
protected function doDelete($id)
{
\DF\Cache::remove($this->_filterCacheId($id));
}
protected function doGetStats()
{
return null;
}
protected function doFlush()
{
\DF\Cache::clean('all');
}
public function getIds()
{
$all_keys = \DF\Cache::getKeys();
if (!$this->_prefix)
{
return $all_keys;
}
else
{
$relevant_keys = array();
foreach((array)$all_keys as $key_name => $key_value)
{
if (strpos($key_name, $this->_prefix) === 0)
{
$filtered_name = str_replace($this->_prefix.'_', '', $key_name);
$relevant_keys[$filtered_name] = $key_value;
}
}
return $relevant_keys;
}
}
protected function _filterCacheId($id)
{
return preg_replace("/[^a-zA-Z0-9_]/", "", $id);
}
<?php
/**
* Doctrine/DF Cache Connector
*/
namespace DF\Doctrine;
class Cache extends \Doctrine\Common\Cache\CacheProvider
{
protected function doFetch($id, $testCacheValidity = true)
{
return \DF\Cache::get($this->_filterCacheId($id));
}
protected function doContains($id)
{
return \DF\Cache::test($this->_filterCacheId($id));
}
protected function doSave($id, $data, $lifeTime = NULL)
{
if ($lifeTime == 0)
$lifeTime = NULL;
\DF\Cache::save($data, $this->_filterCacheId($id), array(), $lifeTime);
return true;
}
protected function doDelete($id)
{
\DF\Cache::remove($this->_filterCacheId($id));
}
protected function doGetStats()
{
return null;
}
protected function doFlush()
{
\DF\Cache::clean('all');
}
public function getIds()
{
$all_keys = \DF\Cache::getKeys();
if (!$this->_prefix)
{
return $all_keys;
}
else
{
$relevant_keys = array();
foreach((array)$all_keys as $key_name => $key_value)
{
if (strpos($key_name, $this->_prefix) === 0)
{
$filtered_name = str_replace($this->_prefix.'_', '', $key_name);
$relevant_keys[$filtered_name] = $key_value;
}
}
return $relevant_keys;
}
}
protected function _filterCacheId($id)
{
return preg_replace("/[^a-zA-Z0-9_]/", "", $id);
}
}

View File

@ -1,496 +1,496 @@
<?php
namespace DF\Doctrine;
class Entity implements \ArrayAccess
{
/**
* Magic methods.
*/
public function __get($key)
{
$method_name = $this->_getMethodName($key, 'get');
if (method_exists($this, $method_name))
return $this->$method_name();
else
return $this->_getVar($key);
}
public function __set($key, $value)
{
$method_name = $this->_getMethodName($key, 'set');
if (method_exists($this, $method_name))
return $this->$method_name($value);
else
return $this->_setVar($key, $value);
}
public function __call($method, $arguments)
{
if (substr($method, 0, 3) == "get") {
$var = $this->_getVarName(substr($method, 3));
return $this->_getVar($var);
}
else if (substr($method, 0, 3) == "set") {
$var = $this->_getVarName(substr($method, 3));
$this->_setVar($var, $arguments[0]);
return $this;
}
}
protected function _getVar($var)
{
if (property_exists($this, $var))
return $this->$var;
else
return NULL;
}
protected function _setVar($var, $value)
{
if (property_exists($this, $var))
$this->$var = $value;
}
// Converts "varNameBlah" to "var_name_blah".
protected function _getVarName($var)
{
return strtolower(preg_replace('~(?<=\\w)([A-Z])~', '_$1', $var));
}
// Converts "getvar_name_blah" to "getVarNameBlah".
protected function _getMethodName($var, $prefix = '')
{
return $prefix.str_replace(" ", "", ucwords(strtr($var, "_-", " ")));
}
/**
* ArrayAccess implementation
*/
public function offsetExists($offset)
{
return property_exists($this, $offset);
}
public function offsetSet($key, $value)
{
$method_name = $this->_getMethodName($key, 'set');
if (method_exists($this, $method_name))
return $this->$method_name($value);
else
return $this->_setVar($key, $value);
}
public function offsetGet($key)
{
$method_name = $this->_getMethodName($key, 'get');
if (method_exists($this, $method_name))
return $this->$method_name();
else
return $this->_getVar($key);
}
public function offsetUnset($offset)
{
if (property_exists($this, $offset))
unset($this->$offset);
}
/**
* FromArray (A Doctrine 1 Classic)
*/
public function fromArray($source)
{
$em = \Zend_Registry::get('em');
$metafactory = $em->getMetadataFactory();
$meta = $metafactory->getMetadataFor(get_called_class());
$mapped_fields = array();
if ($meta->associationMappings)
{
foreach($meta->associationMappings as $mapping_name => $mapping_info)
{
$entity = $mapping_info['targetEntity'];
if (isset($mapping_info['joinTable']))
{
$mapped_fields[$mapping_info['fieldName']] = array(
'type' => 'many',
'entity' => $entity,
'is_owning_side' => ($mapping_info['isOwningSide'] == 1),
'mappedBy' => $mapping_info['mappedBy'],
);
}
else if (isset($mapping_info['joinColumns']))
{
foreach($mapping_info['joinColumns'] as $col)
{
$col_name = $col['name'];
$col_name = (isset($meta->fieldNames[$col_name])) ? $meta->fieldNames[$col_name] : $col_name;
$mapped_fields[$col_name] = array(
'name' => $mapping_name,
'type' => 'one',
'entity' => $entity,
);
}
}
}
}
foreach((array)$source as $field => $value)
{
if (isset($mapped_fields[$field]))
{
$mapping = $mapped_fields[$field];
if ($mapping['type'] == "one")
{
$field_name = $mapping['name'];
if (empty($value))
{
$this->$field_name = NULL;
}
else if ($value != $this->$field)
{
$obj_class = $mapping['entity'];
$obj = $obj_class::find($value);
if ($obj instanceof $obj_class)
$this->$field_name = $obj;
}
}
else if ($mapping['type'] == "many")
{
$obj_class = $mapping['entity'];
if ($mapping['is_owning_side'])
{
$this->$field->clear();
if ($value)
{
foreach((array)$value as $field_id)
{
if(($field_item = $obj_class::find((int)$field_id)) instanceof $obj_class)
{
$this->$field->add($field_item);
}
}
}
}
else
{
$foreign_field = $mapping['mappedBy'];
if (count($this->$field) > 0)
{
foreach($this->$field as $record)
{
$record->$foreign_field->removeElement($this);
$em->persist($record);
}
}
foreach((array)$value as $field_id)
{
if(($record = $obj_class::find((int)$field_id)) instanceof $obj_class)
{
$record->$foreign_field->add($this);
$em->persist($record);
}
}
$em->flush();
}
}
}
else
{
if (!isset($meta->fieldMappings[$field]))
$field_info = array();
else
$field_info = $meta->fieldMappings[$field];
switch($field_info['type'])
{
case "datetime":
case "date":
if (!($value instanceof \DateTime))
{
if ($value)
{
if (!is_numeric($value))
$value = strtotime($value.' UTC');
$value = \DateTime::createFromFormat(\DateTime::ISO8601, gmdate(\DateTime::ISO8601, (int)$value));
}
else
{
$value = NULL;
}
}
break;
case "string":
if ($field_info['length'] && strlen($value) > $field_info['length'])
$value = substr($value, 0, $field_info['length']);
break;
case "decimal":
case "float":
if ($value !== NULL && !is_float($value))
$value = (float)$value;
break;
case "integer":
case "smallint":
case "bigint":
if ($value !== NULL)
$value = (int)$value;
break;
case "boolean":
if ($value !== NULL)
$value = (bool)$value;
break;
}
$this->__set($field, $value);
}
}
return $this;
}
/**
* ToArray (A Doctrine 1 Classic)
* @param $deep Iterate through collections associated with this item.
* @param $form_mode Return values in a format suitable for ZendForm setDefault function.
*/
public function toArray($deep = FALSE, $form_mode = FALSE)
{
$return_arr = array();
$em = \Zend_Registry::get('em');
$class_meta = $em->getClassMetadata(get_called_class());
$reflect = new \ReflectionClass($this);
$props = $reflect->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED);
if ($props)
{
foreach($props as $property)
{
$property->setAccessible(true);
$prop_name = $property->getName();
$prop_val = $property->getValue($this);
if (isset($class_meta->fieldMappings[$prop_name]))
$prop_info = $class_meta->fieldMappings[$prop_name];
else
$prop_info = array();
if (is_array($prop_val))
{
$return_arr[$prop_name] = $prop_val;
}
else if (!is_object($prop_val))
{
if ($prop_info['type'] == "array")
$return_arr[$prop_name] = (array)$prop_val;
else
$return_arr[$prop_name] = (string)$prop_val;
}
else if ($prop_val instanceof \DateTime)
{
$return_arr[$prop_name] = $prop_val->getTimestamp();
}
else if ($deep)
{
if ($prop_val instanceof \Doctrine\Common\Collections\Collection)
{
$return_val = array();
if (count($prop_val) > 0)
{
foreach($prop_val as $val_obj)
{
if ($form_mode)
{
$obj_meta = $em->getClassMetadata(get_class($val_obj));
$id_field = $obj_meta->identifier;
if ($id_field && count($id_field) == 1)
$return_val[] = $val_obj->{$id_field[0]};
}
else
{
$return_val[] = $val_obj->toArray(FALSE);
}
}
}
$return_arr[$prop_name] = $return_val;
}
else
{
$return_arr[$prop_name] = $prop_val->toArray(FALSE);
}
}
}
}
return $return_arr;
}
/* Save (A Docrine 1 Classic) */
public function save()
{
$em = self::getEntityManager();
$em->persist($this);
$em->flush($this);
}
/* Delete (A Docrine 1 Classic) */
public function delete($hard_delete = FALSE)
{
$em = \Zend_Registry::get('em');
// Support for soft-deletion.
if (!$hard_delete && property_exists($this, 'deleted_at'))
{
// Determine type of deleted field.
$class_meta = $em->getClassMetadata(get_called_class());
$deleted_at_type = $class_meta->fieldMappings['deleted_at']['type'];
if ($deleted_at_type == "datetime")
$this->deleted_at = new \DateTime('NOW');
else
$this->deleted_at = true;
$this->save();
}
else
{
$em = \Zend_Registry::get('em');
$em->remove($this);
$em->flush();
}
}
public function hardDelete()
{
return $this->delete(TRUE);
}
public function detach()
{
$em = \Zend_Registry::get('em');
$em->detach($this);
return $this;
}
public function merge()
{
$em = \Zend_Registry::get('em');
$em->merge($this);
return $this;
}
/**
* Static functions
*/
public static function getEntityManager()
{
static $em;
if ($em === NULL)
$em = \Zend_Registry::get('em');
return $em;
}
/* Fetch the global entity manager to get a repository class. */
public static function getRepository()
{
$class = get_called_class();
$em = self::getEntityManager();
return $em->getRepository($class);
}
/* Fetch an array of the current entities. */
public static function fetchAll()
{
$repo = self::getRepository();
return $repo->findAll();
}
public static function fetchArray($order_by = NULL, $order_dir = 'ASC')
{
$class = get_called_class();
$em = self::getEntityManager();
$qb = $em->createQueryBuilder()
->select('e')
->from($class, 'e');
if ($order_by)
$qb->orderBy('e.'.str_replace('e.', '', $order_by), $order_dir);
return $qb->getQuery()->getArrayResult();
}
/* Generic dropdown builder function (can be overridden for specialized use cases). */
public static function fetchSelect($add_blank = FALSE, \Closure $display = NULL, $pk = 'id', $order_by = 'name')
{
$select = array();
// Specify custom text in the $add_blank parameter to override.
if ($add_blank !== FALSE)
$select[''] = ($add_blank === TRUE) ? 'Select...' : $add_blank;
// Build query for records.
$class = get_called_class();
$em = self::getEntityManager();
$qb = $em->createQueryBuilder()->from($class, 'e');
if ($display === NULL)
$qb->select('e.'.$pk)->addSelect('e.name')->orderBy('e.'.$order_by, 'ASC');
else
$qb->select('e')->orderBy('e.'.$order_by, 'ASC');
$results = $qb->getQuery()->getArrayResult();
// Assemble select values and, if necessary, call $display callback.
foreach((array)$results as $result)
{
$key = $result[$pk];
$value = ($display === NULL) ? $result['name'] : $display($result);
$select[$key] = $value;
}
return $select;
}
/* Find a specific item by primary key. */
public static function find($id)
{
$repo = self::getRepository();
return $repo->find($id);
}
/* Reset auto-increment key (MySQL Only). */
public static function resetAutoIncrement()
{
$em = \Zend_Registry::get('em');
$table_name = $em->getClassMetadata(get_called_class())->getTableName();
$conn = $em->getConnection();
return $conn->query('ALTER TABLE '.$conn->quoteIdentifier($table_name).' AUTO_INCREMENT = 1');
}
<?php
namespace DF\Doctrine;
class Entity implements \ArrayAccess
{
/**
* Magic methods.
*/
public function __get($key)
{
$method_name = $this->_getMethodName($key, 'get');
if (method_exists($this, $method_name))
return $this->$method_name();
else
return $this->_getVar($key);
}
public function __set($key, $value)
{
$method_name = $this->_getMethodName($key, 'set');
if (method_exists($this, $method_name))
return $this->$method_name($value);
else
return $this->_setVar($key, $value);
}
public function __call($method, $arguments)
{
if (substr($method, 0, 3) == "get") {
$var = $this->_getVarName(substr($method, 3));
return $this->_getVar($var);
}
else if (substr($method, 0, 3) == "set") {
$var = $this->_getVarName(substr($method, 3));
$this->_setVar($var, $arguments[0]);
return $this;
}
}
protected function _getVar($var)
{
if (property_exists($this, $var))
return $this->$var;
else
return NULL;
}
protected function _setVar($var, $value)
{
if (property_exists($this, $var))
$this->$var = $value;
}
// Converts "varNameBlah" to "var_name_blah".
protected function _getVarName($var)
{
return strtolower(preg_replace('~(?<=\\w)([A-Z])~', '_$1', $var));
}
// Converts "getvar_name_blah" to "getVarNameBlah".
protected function _getMethodName($var, $prefix = '')
{
return $prefix.str_replace(" ", "", ucwords(strtr($var, "_-", " ")));
}
/**
* ArrayAccess implementation
*/
public function offsetExists($offset)
{
return property_exists($this, $offset);
}
public function offsetSet($key, $value)
{
$method_name = $this->_getMethodName($key, 'set');
if (method_exists($this, $method_name))
return $this->$method_name($value);
else
return $this->_setVar($key, $value);
}
public function offsetGet($key)
{
$method_name = $this->_getMethodName($key, 'get');
if (method_exists($this, $method_name))
return $this->$method_name();
else
return $this->_getVar($key);
}
public function offsetUnset($offset)
{
if (property_exists($this, $offset))
unset($this->$offset);
}
/**
* FromArray (A Doctrine 1 Classic)
*/
public function fromArray($source)
{
$em = \Zend_Registry::get('em');
$metafactory = $em->getMetadataFactory();
$meta = $metafactory->getMetadataFor(get_called_class());
$mapped_fields = array();
if ($meta->associationMappings)
{
foreach($meta->associationMappings as $mapping_name => $mapping_info)
{
$entity = $mapping_info['targetEntity'];
if (isset($mapping_info['joinTable']))
{
$mapped_fields[$mapping_info['fieldName']] = array(
'type' => 'many',
'entity' => $entity,
'is_owning_side' => ($mapping_info['isOwningSide'] == 1),
'mappedBy' => $mapping_info['mappedBy'],
);
}
else if (isset($mapping_info['joinColumns']))
{
foreach($mapping_info['joinColumns'] as $col)
{
$col_name = $col['name'];
$col_name = (isset($meta->fieldNames[$col_name])) ? $meta->fieldNames[$col_name] : $col_name;
$mapped_fields[$col_name] = array(
'name' => $mapping_name,
'type' => 'one',
'entity' => $entity,
);
}
}
}
}
foreach((array)$source as $field => $value)
{
if (isset($mapped_fields[$field]))
{
$mapping = $mapped_fields[$field];
if ($mapping['type'] == "one")
{
$field_name = $mapping['name'];
if (empty($value))
{
$this->$field_name = NULL;
}
else if ($value != $this->$field)
{
$obj_class = $mapping['entity'];
$obj = $obj_class::find($value);
if ($obj instanceof $obj_class)
$this->$field_name = $obj;
}
}
else if ($mapping['type'] == "many")
{
$obj_class = $mapping['entity'];
if ($mapping['is_owning_side'])
{
$this->$field->clear();
if ($value)
{
foreach((array)$value as $field_id)
{
if(($field_item = $obj_class::find((int)$field_id)) instanceof $obj_class)
{
$this->$field->add($field_item);
}
}
}
}
else
{
$foreign_field = $mapping['mappedBy'];
if (count($this->$field) > 0)
{
foreach($this->$field as $record)
{
$record->$foreign_field->removeElement($this);
$em->persist($record);
}
}
foreach((array)$value as $field_id)
{
if(($record = $obj_class::find((int)$field_id)) instanceof $obj_class)
{
$record->$foreign_field->add($this);
$em->persist($record);
}
}
$em->flush();
}
}
}
else
{
if (!isset($meta->fieldMappings[$field]))
$field_info = array();
else
$field_info = $meta->fieldMappings[$field];
switch($field_info['type'])
{
case "datetime":
case "date":
if (!($value instanceof \DateTime))
{
if ($value)
{
if (!is_numeric($value))
$value = strtotime($value.' UTC');
$value = \DateTime::createFromFormat(\DateTime::ISO8601, gmdate(\DateTime::ISO8601, (int)$value));
}
else
{
$value = NULL;
}
}
break;
case "string":
if ($field_info['length'] && strlen($value) > $field_info['length'])
$value = substr($value, 0, $field_info['length']);
break;
case "decimal":
case "float":
if ($value !== NULL && !is_float($value))
$value = (float)$value;
break;
case "integer":
case "smallint":
case "bigint":
if ($value !== NULL)
$value = (int)$value;
break;
case "boolean":
if ($value !== NULL)
$value = (bool)$value;
break;
}
$this->__set($field, $value);
}
}
return $this;
}
/**
* ToArray (A Doctrine 1 Classic)
* @param $deep Iterate through collections associated with this item.
* @param $form_mode Return values in a format suitable for ZendForm setDefault function.
*/
public function toArray($deep = FALSE, $form_mode = FALSE)
{
$return_arr = array();
$em = \Zend_Registry::get('em');
$class_meta = $em->getClassMetadata(get_called_class());
$reflect = new \ReflectionClass($this);
$props = $reflect->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED);
if ($props)
{
foreach($props as $property)
{
$property->setAccessible(true);
$prop_name = $property->getName();
$prop_val = $property->getValue($this);
if (isset($class_meta->fieldMappings[$prop_name]))
$prop_info = $class_meta->fieldMappings[$prop_name];
else
$prop_info = array();
if (is_array($prop_val))
{
$return_arr[$prop_name] = $prop_val;
}
else if (!is_object($prop_val))
{
if ($prop_info['type'] == "array")
$return_arr[$prop_name] = (array)$prop_val;
else
$return_arr[$prop_name] = (string)$prop_val;
}
else if ($prop_val instanceof \DateTime)
{
$return_arr[$prop_name] = $prop_val->getTimestamp();
}
else if ($deep)
{
if ($prop_val instanceof \Doctrine\Common\Collections\Collection)
{
$return_val = array();
if (count($prop_val) > 0)
{
foreach($prop_val as $val_obj)
{
if ($form_mode)
{
$obj_meta = $em->getClassMetadata(get_class($val_obj));
$id_field = $obj_meta->identifier;
if ($id_field && count($id_field) == 1)
$return_val[] = $val_obj->{$id_field[0]};
}
else
{
$return_val[] = $val_obj->toArray(FALSE);
}
}
}
$return_arr[$prop_name] = $return_val;
}
else
{
$return_arr[$prop_name] = $prop_val->toArray(FALSE);
}
}
}
}
return $return_arr;
}
/* Save (A Docrine 1 Classic) */
public function save()
{
$em = self::getEntityManager();
$em->persist($this);
$em->flush($this);
}
/* Delete (A Docrine 1 Classic) */
public function delete($hard_delete = FALSE)
{
$em = \Zend_Registry::get('em');
// Support for soft-deletion.
if (!$hard_delete && property_exists($this, 'deleted_at'))
{
// Determine type of deleted field.
$class_meta = $em->getClassMetadata(get_called_class());
$deleted_at_type = $class_meta->fieldMappings['deleted_at']['type'];
if ($deleted_at_type == "datetime")
$this->deleted_at = new \DateTime('NOW');
else
$this->deleted_at = true;
$this->save();
}
else
{
$em = \Zend_Registry::get('em');
$em->remove($this);
$em->flush();
}
}
public function hardDelete()
{
return $this->delete(TRUE);
}
public function detach()
{
$em = \Zend_Registry::get('em');
$em->detach($this);
return $this;
}
public function merge()
{
$em = \Zend_Registry::get('em');
$em->merge($this);
return $this;
}
/**
* Static functions
*/
public static function getEntityManager()
{
static $em;
if ($em === NULL)
$em = \Zend_Registry::get('em');
return $em;
}
/* Fetch the global entity manager to get a repository class. */
public static function getRepository()
{
$class = get_called_class();
$em = self::getEntityManager();
return $em->getRepository($class);
}
/* Fetch an array of the current entities. */
public static function fetchAll()
{
$repo = self::getRepository();
return $repo->findAll();
}
public static function fetchArray($order_by = NULL, $order_dir = 'ASC')
{
$class = get_called_class();
$em = self::getEntityManager();
$qb = $em->createQueryBuilder()
->select('e')
->from($class, 'e');
if ($order_by)
$qb->orderBy('e.'.str_replace('e.', '', $order_by), $order_dir);
return $qb->getQuery()->getArrayResult();
}
/* Generic dropdown builder function (can be overridden for specialized use cases). */
public static function fetchSelect($add_blank = FALSE, \Closure $display = NULL, $pk = 'id', $order_by = 'name')
{
$select = array();
// Specify custom text in the $add_blank parameter to override.
if ($add_blank !== FALSE)
$select[''] = ($add_blank === TRUE) ? 'Select...' : $add_blank;
// Build query for records.
$class = get_called_class();
$em = self::getEntityManager();
$qb = $em->createQueryBuilder()->from($class, 'e');
if ($display === NULL)
$qb->select('e.'.$pk)->addSelect('e.name')->orderBy('e.'.$order_by, 'ASC');
else
$qb->select('e')->orderBy('e.'.$order_by, 'ASC');
$results = $qb->getQuery()->getArrayResult();
// Assemble select values and, if necessary, call $display callback.
foreach((array)$results as $result)
{
$key = $result[$pk];
$value = ($display === NULL) ? $result['name'] : $display($result);
$select[$key] = $value;
}
return $select;
}
/* Find a specific item by primary key. */
public static function find($id)
{
$repo = self::getRepository();
return $repo->find($id);
}
/* Reset auto-increment key (MySQL Only). */
public static function resetAutoIncrement()
{
$em = \Zend_Registry::get('em');
$table_name = $em->getClassMetadata(get_called_class())->getTableName();
$conn = $em->getConnection();
return $conn->query('ALTER TABLE '.$conn->quoteIdentifier($table_name).' AUTO_INCREMENT = 1');
}
}

View File

@ -1,27 +1,27 @@
<?php
namespace DF\Doctrine\Filter;
use Doctrine\ORM\Mapping\ClassMetaData,
Doctrine\ORM\Query\Filter\SQLFilter;
class SoftDelete extends SQLFilter
{
public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
{
if (!isset($targetEntity->fieldMappings['deleted_at']))
return '';
// Check for whether filter is being called from within a proxy and exempt from filter if so.
$has_proxy = FALSE;
$backtrace = debug_backtrace();
foreach($backtrace as $log)
{
if (stristr($log['class'], 'Proxy') !== FALSE)
$has_proxy = TRUE;
}
if ($has_proxy)
return '';
else
return $targetTableAlias.'.deleted_at IS NULL';
}
<?php
namespace DF\Doctrine\Filter;
use Doctrine\ORM\Mapping\ClassMetaData,
Doctrine\ORM\Query\Filter\SQLFilter;
class SoftDelete extends SQLFilter
{
public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
{
if (!isset($targetEntity->fieldMappings['deleted_at']))
return '';
// Check for whether filter is being called from within a proxy and exempt from filter if so.
$has_proxy = FALSE;
$backtrace = debug_backtrace();
foreach($backtrace as $log)
{
if (stristr($log['class'], 'Proxy') !== FALSE)
$has_proxy = TRUE;
}
if ($has_proxy)
return '';
else
return $targetTableAlias.'.deleted_at IS NULL';
}
}

View File

@ -1,26 +1,26 @@
<?php
namespace DF\Doctrine\Functions;
use \Doctrine\ORM\Query\AST\Functions\FunctionNode;
use \Doctrine\ORM\Query\SqlWalker;
use \Doctrine\ORM\Query\Parser;
use \Doctrine\ORM\Query\Lexer;
/**
* RandFunction ::= "RAND" "(" ")"
*/
class Rand extends FunctionNode
{
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(SqlWalker $sqlWalker)
{
return 'RAND()';
}
<?php
namespace DF\Doctrine\Functions;
use \Doctrine\ORM\Query\AST\Functions\FunctionNode;
use \Doctrine\ORM\Query\SqlWalker;
use \Doctrine\ORM\Query\Parser;
use \Doctrine\ORM\Query\Lexer;
/**
* RandFunction ::= "RAND" "(" ")"
*/
class Rand extends FunctionNode
{
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(SqlWalker $sqlWalker)
{
return 'RAND()';
}
}

View File

@ -1,27 +1,27 @@
<?php
namespace DF\Doctrine\Logger;
class EchoSQL extends \Doctrine\DBAL\Logging\EchoSQLLogger
{
public function startQuery($sql, array $params = null, array $types = null)
{
echo $sql.PHP_EOL;
if ($params) {
var_dump($params);
}
if ($types) {
var_dump($types);
}
$memory = memory_get_usage();
$mb = round($memory / (1024 * 1024), 4).'M';
echo $mb.'/'.ini_get('memory_limit').PHP_EOL;
}
public function stopQuery()
{}
<?php
namespace DF\Doctrine\Logger;
class EchoSQL extends \Doctrine\DBAL\Logging\EchoSQLLogger
{
public function startQuery($sql, array $params = null, array $types = null)
{
echo $sql.PHP_EOL;
if ($params) {
var_dump($params);
}
if ($types) {
var_dump($types);
}
$memory = memory_get_usage();
$mb = round($memory / (1024 * 1024), 4).'M';
echo $mb.'/'.ini_get('memory_limit').PHP_EOL;
}
public function stopQuery()
{}
}

View File

@ -1,71 +1,71 @@
<?php
/**
* DoctrineExtensions Paginate
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to kontakt@beberlei.de so I can send you a copy immediately.
*/
namespace DF\Doctrine\Paginate;
use Doctrine\ORM\Query\TreeWalkerAdapter,
Doctrine\ORM\Query\AST\SelectStatement,
Doctrine\ORM\Query\AST\SelectExpression,
Doctrine\ORM\Query\AST\PathExpression,
Doctrine\ORM\Query\AST\AggregateExpression;
class CountWalker extends TreeWalkerAdapter
{
/**
* Walks down a SelectStatement AST node, modifying it to retrieve a COUNT
*
* @param SelectStatement $AST
* @return void
*/
public function walkSelectStatement(SelectStatement $AST)
{
$parent = null;
$parentName = null;
foreach ($this->_getQueryComponents() AS $dqlAlias => $qComp)
{
// skip mixed data in query
if (isset($qComp['resultVariable']))
{
continue;
}
if ($qComp['parent'] === null && $qComp['nestingLevel'] == 0)
{
$parent = $qComp;
$parentName = $dqlAlias;
break;
}
}
$pathExpression = new PathExpression(
PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $parentName,
$parent['metadata']->getSingleIdentifierFieldName()
);
$pathExpression->type = PathExpression::TYPE_STATE_FIELD;
$AST->selectClause->selectExpressions = array(
new SelectExpression(
new AggregateExpression('count', $pathExpression, true), null
)
);
// ORDER BY is not needed, only increases query execution through unnecessary sorting.
$AST->orderByClause = null;
// GROUP BY will break things, we are trying to get a count of all
$AST->groupByClause = null;
}
<?php
/**
* DoctrineExtensions Paginate
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to kontakt@beberlei.de so I can send you a copy immediately.
*/
namespace DF\Doctrine\Paginate;
use Doctrine\ORM\Query\TreeWalkerAdapter,
Doctrine\ORM\Query\AST\SelectStatement,
Doctrine\ORM\Query\AST\SelectExpression,
Doctrine\ORM\Query\AST\PathExpression,
Doctrine\ORM\Query\AST\AggregateExpression;
class CountWalker extends TreeWalkerAdapter
{
/**
* Walks down a SelectStatement AST node, modifying it to retrieve a COUNT
*
* @param SelectStatement $AST
* @return void
*/
public function walkSelectStatement(SelectStatement $AST)
{
$parent = null;
$parentName = null;
foreach ($this->_getQueryComponents() AS $dqlAlias => $qComp)
{
// skip mixed data in query
if (isset($qComp['resultVariable']))
{
continue;
}
if ($qComp['parent'] === null && $qComp['nestingLevel'] == 0)
{
$parent = $qComp;
$parentName = $dqlAlias;
break;
}
}
$pathExpression = new PathExpression(
PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $parentName,
$parent['metadata']->getSingleIdentifierFieldName()
);
$pathExpression->type = PathExpression::TYPE_STATE_FIELD;
$AST->selectClause->selectExpressions = array(
new SelectExpression(
new AggregateExpression('count', $pathExpression, true), null
)
);
// ORDER BY is not needed, only increases query execution through unnecessary sorting.
$AST->orderByClause = null;
// GROUP BY will break things, we are trying to get a count of all
$AST->groupByClause = null;
}
}

View File

@ -1,76 +1,76 @@
<?php
/**
* DF MSSQL Adapter Class
*/
namespace DF\Doctrine\Platform;
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Schema\Index,
Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Types\Type;
class Mssql extends \Doctrine\DBAL\Platforms\SQLServer2008Platform
{
/**
* @override
*/
public function getAlterTableSQL(TableDiff $diff)
{
static $schema;
// Initialize schema.
if ($schema === NULL)
{
$em = \Zend_Registry::get('em');
$sm = $em->getConnection()->getSchemaManager();
$schema = $sm->createSchema();
}
$current_table = $schema->getTable($diff->name);
$sql = array();
$queryParts = array();
if ($diff->newName !== false) {
$queryParts[] = 'RENAME TO ' . $diff->newName;
}
foreach ($diff->addedColumns AS $fieldName => $column) {
$queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
}
foreach ($diff->removedColumns AS $column) {
$queryParts[] = 'DROP COLUMN ' . $column->getQuotedName($this);
}
foreach ($diff->changedColumns AS $columnDiff)
{
// Check for columns that aren't really different (custom types).
$current_column = $current_table->getColumn($columnDiff->oldColumnName)->toArray();
$column = $columnDiff->column->toArray();
$current_def = $current_column['type']->getSqlDeclaration($current_column, $this);
$new_def = $column['type']->getSqlDeclaration($column, $this);
if ($new_def != $current_def)
$queryParts[] = 'ALTER COLUMN '.$columnDiff->oldColumnName.' '.$new_def;
}
foreach ($diff->renamedColumns AS $oldColumnName => $column) {
$sql[] = "EXEC sp_rename @objname = '".$diff->name.".".$oldColumnName."', @newname = '".$column->getQuotedName($this)."', @objtype = 'COLUMN'";
}
foreach ($queryParts as $query) {
$sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query;
}
$sql = array_merge($sql, $this->_getAlterTableIndexForeignKeySQL($diff));
return $sql;
}
public function getBooleanTypeDeclarationSQL(array $field)
{
return 'SMALLINT';
}
<?php
/**
* DF MSSQL Adapter Class
*/
namespace DF\Doctrine\Platform;
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Schema\Index,
Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Types\Type;
class Mssql extends \Doctrine\DBAL\Platforms\SQLServer2008Platform
{
/**
* @override
*/
public function getAlterTableSQL(TableDiff $diff)
{
static $schema;
// Initialize schema.
if ($schema === NULL)
{
$em = \Zend_Registry::get('em');
$sm = $em->getConnection()->getSchemaManager();
$schema = $sm->createSchema();
}
$current_table = $schema->getTable($diff->name);
$sql = array();
$queryParts = array();
if ($diff->newName !== false) {
$queryParts[] = 'RENAME TO ' . $diff->newName;
}
foreach ($diff->addedColumns AS $fieldName => $column) {
$queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
}
foreach ($diff->removedColumns AS $column) {
$queryParts[] = 'DROP COLUMN ' . $column->getQuotedName($this);
}
foreach ($diff->changedColumns AS $columnDiff)
{
// Check for columns that aren't really different (custom types).
$current_column = $current_table->getColumn($columnDiff->oldColumnName)->toArray();
$column = $columnDiff->column->toArray();
$current_def = $current_column['type']->getSqlDeclaration($current_column, $this);
$new_def = $column['type']->getSqlDeclaration($column, $this);
if ($new_def != $current_def)
$queryParts[] = 'ALTER COLUMN '.$columnDiff->oldColumnName.' '.$new_def;
}
foreach ($diff->renamedColumns AS $oldColumnName => $column) {
$sql[] = "EXEC sp_rename @objname = '".$diff->name.".".$oldColumnName."', @newname = '".$column->getQuotedName($this)."', @objtype = 'COLUMN'";
}
foreach ($queryParts as $query) {
$sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query;
}
$sql = array_merge($sql, $this->_getAlterTableIndexForeignKeySQL($diff));
return $sql;
}
public function getBooleanTypeDeclarationSQL(array $field)
{
return 'SMALLINT';
}
}

View File

@ -1,33 +1,33 @@
<?php
namespace DF\Doctrine\Type;
use Doctrine\DBAL\Types\ArrayType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* My custom datatype.
*/
class Json extends ArrayType
{
const TYPENAME = 'json';
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return json_encode($value);
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ($value === null)
return null;
$value = (is_resource($value)) ? stream_get_contents($value, -1) : $value;
return json_decode((string)$value, 1);
}
public function getName()
{
return self::TYPENAME;
}
<?php
namespace DF\Doctrine\Type;
use Doctrine\DBAL\Types\ArrayType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* My custom datatype.
*/
class Json extends ArrayType
{
const TYPENAME = 'json';
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return json_encode($value);
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ($value === null)
return null;
$value = (is_resource($value)) ? stream_get_contents($value, -1) : $value;
return json_decode((string)$value, 1);
}
public function getName()
{
return self::TYPENAME;
}
}

View File

@ -1,29 +1,29 @@
<?php
namespace DF\Doctrine\Type;
use Doctrine\DBAL\Types\ArrayType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* "Soft Array" datatype - same as Array, but with silent failure.
*/
class SoftArray extends ArrayType
{
const TYPENAME = 'array';
public function convertToPHPValue($value, \Doctrine\DBAL\Platforms\AbstractPlatform $platform)
{
if ($value === null)
return null;
$value = (is_resource($value)) ? stream_get_contents($value) : $value;
$val = @unserialize($value);
return $val;
}
public function getName()
{
return self::TYPENAME;
}
<?php
namespace DF\Doctrine\Type;
use Doctrine\DBAL\Types\ArrayType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* "Soft Array" datatype - same as Array, but with silent failure.
*/
class SoftArray extends ArrayType
{
const TYPENAME = 'array';
public function convertToPHPValue($value, \Doctrine\DBAL\Platforms\AbstractPlatform $platform)
{
if ($value === null)
return null;
$value = (is_resource($value)) ? stream_get_contents($value) : $value;
$val = @unserialize($value);
return $val;
}
public function getName()
{
return self::TYPENAME;
}
}

View File

@ -1,41 +1,41 @@
<?php
namespace DF\Doctrine\Type;
use \Doctrine\DBAL\Types\DateTimeType;
use \Doctrine\DBAL\Platforms\AbstractPlatform;
use \Doctrine\DBAL\Types\ConversionException;
class UTCDateTime extends DateTimeType
{
static private $utc = null;
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if ($value === null) {
return null;
}
$utc = (self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC'));
$value->setTimezone($utc);
return $value->format($platform->getDateTimeFormatString());
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ($value === null) {
return null;
}
$val = \DateTime::createFromFormat(
$platform->getDateTimeFormatString(),
$value,
(self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC'))
);
if (!$val) {
throw ConversionException::conversionFailed($value, $this->getName());
}
return $val;
}
<?php
namespace DF\Doctrine\Type;
use \Doctrine\DBAL\Types\DateTimeType;
use \Doctrine\DBAL\Platforms\AbstractPlatform;
use \Doctrine\DBAL\Types\ConversionException;
class UTCDateTime extends DateTimeType
{
static private $utc = null;
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if ($value === null) {
return null;
}
$utc = (self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC'));
$value->setTimezone($utc);
return $value->format($platform->getDateTimeFormatString());
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ($value === null) {
return null;
}
$val = \DateTime::createFromFormat(
$platform->getDateTimeFormatString(),
$value,
(self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC'))
);
if (!$val) {
throw ConversionException::conversionFailed($value, $this->getName());
}
return $val;
}
}

View File

@ -1,39 +1,39 @@
<?php
namespace DF\Doctrine\Type;
use Doctrine\DBAL\Types\IntegerType;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* "UNIX Timestamp Date/Time" datatype - same as DateTime, but stored as an integer (for BC)
*/
class UnixDateTime extends IntegerType
{
const TYPENAME = 'unixdatetime';
public function getName()
{
return self::TYPENAME;
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if ($value !== NULL)
{
if ($value instanceof \DateTime)
return $value->getTimestamp();
else
return (int)$value;
}
return NULL;
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ((int)$value)
return \DateTime::createFromFormat(\DateTime::ISO8601, date(\DateTime::ISO8601, (int)$value));
else
return NULL;
}
<?php
namespace DF\Doctrine\Type;
use Doctrine\DBAL\Types\IntegerType;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* "UNIX Timestamp Date/Time" datatype - same as DateTime, but stored as an integer (for BC)
*/
class UnixDateTime extends IntegerType
{
const TYPENAME = 'unixdatetime';
public function getName()
{
return self::TYPENAME;
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if ($value !== NULL)
{
if ($value instanceof \DateTime)
return $value->getTimestamp();
else
return (int)$value;
}
return NULL;
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ((int)$value)
return \DateTime::createFromFormat(\DateTime::ISO8601, date(\DateTime::ISO8601, (int)$value));
else
return NULL;
}
}

View File

@ -1,46 +1,46 @@
<?php
/**
* Encryption Handler
*/
namespace DF;
define("DF_ENCRYPTION_KEY", "1ad1afc09c07f162fe993a88b5c9fbb4");
define("DF_ENCRYPTION_CIPHER", MCRYPT_RIJNDAEL_128);
class Encryption
{
public static function encrypt($string)
{
// Create initialization vector.
$iv_size = mcrypt_get_iv_size(DF_ENCRYPTION_CIPHER, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
// Trim encryption key to size supported by this cipher.
$key = substr(DF_ENCRYPTION_KEY, 0, mcrypt_get_key_size(DF_ENCRYPTION_CIPHER, MCRYPT_MODE_ECB));
$encrypted_string = mcrypt_encrypt(DF_ENCRYPTION_CIPHER, $key, trim($string), MCRYPT_MODE_ECB, $iv);
// Package the encrypted string for easy storage.
return base64_encode($encrypted_string).'|'.base64_encode($iv);
}
public static function decrypt($string)
{
// Unpackage the encoded, encrypted string.
list($encoded_string, $encoded_iv) = explode('|', $string);
$encrypted_string = base64_decode($encoded_string);
$iv = base64_decode($encoded_iv);
// Trim encryption key to size supported by this cipher.
$key = substr(DF_ENCRYPTION_KEY, 0, mcrypt_get_key_size(DF_ENCRYPTION_CIPHER, MCRYPT_MODE_ECB));
return trim(mcrypt_decrypt(DF_ENCRYPTION_CIPHER, $key, $encrypted_string, MCRYPT_MODE_ECB, $iv));
}
public static function digest($string)
{
return sha1($string.DF_ENCRYPTION_KEY);
}
<?php
/**
* Encryption Handler
*/
namespace DF;
define("DF_ENCRYPTION_KEY", "1ad1afc09c07f162fe993a88b5c9fbb4");
define("DF_ENCRYPTION_CIPHER", MCRYPT_RIJNDAEL_128);
class Encryption
{
public static function encrypt($string)
{
// Create initialization vector.
$iv_size = mcrypt_get_iv_size(DF_ENCRYPTION_CIPHER, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
// Trim encryption key to size supported by this cipher.
$key = substr(DF_ENCRYPTION_KEY, 0, mcrypt_get_key_size(DF_ENCRYPTION_CIPHER, MCRYPT_MODE_ECB));
$encrypted_string = mcrypt_encrypt(DF_ENCRYPTION_CIPHER, $key, trim($string), MCRYPT_MODE_ECB, $iv);
// Package the encrypted string for easy storage.
return base64_encode($encrypted_string).'|'.base64_encode($iv);
}
public static function decrypt($string)
{
// Unpackage the encoded, encrypted string.
list($encoded_string, $encoded_iv) = explode('|', $string);
$encrypted_string = base64_decode($encoded_string);
$iv = base64_decode($encoded_iv);
// Trim encryption key to size supported by this cipher.
$key = substr(DF_ENCRYPTION_KEY, 0, mcrypt_get_key_size(DF_ENCRYPTION_CIPHER, MCRYPT_MODE_ECB));
return trim(mcrypt_decrypt(DF_ENCRYPTION_CIPHER, $key, $encrypted_string, MCRYPT_MODE_ECB, $iv));
}
public static function digest($string)
{
return sha1($string.DF_ENCRYPTION_KEY);
}
}

View File

@ -0,0 +1,3 @@
<?php
namespace DF;
class Exception extends \Exception {}

View File

@ -1,7 +1,7 @@
<?php
/**
* Any type of "Display-Only" exception
*/
namespace DF\Exception;
<?php
/**
* Any type of "Display-Only" exception
*/
namespace DF\Exception;
class DisplayOnly extends \Exception {}

View File

@ -0,0 +1,3 @@
<?php
namespace DF\Exception;
class NotLoggedIn extends \Exception {}

View File

@ -1,7 +1,7 @@
<?php
/**
* Permission Denied exception
*/
namespace DF\Exception;
<?php
/**
* Permission Denied exception
*/
namespace DF\Exception;
class PermissionDenied extends \Exception {}

View File

@ -0,0 +1,3 @@
<?php
namespace DF\Exception;
class Severe extends \Exception {}

View File

@ -0,0 +1,3 @@
<?php
namespace DF\Exception;
class Warning extends \Exception {}

View File

@ -1,307 +1,307 @@
<?php
/**
* Class with static methods for exporting data into various formats.
*/
namespace DF;
class Export
{
/**
* CSV
**/
public static function csv($table_data, $headers_first_row = TRUE, $file_name = "ExportedData")
{
self::exportToCSV($table_data, $headers_first_row, $file_name);
}
public static function exportToCSV($table_data, $headers_first_row = TRUE, $file_name = "ExportedData")
{
// Header data associated with CSV files.
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", FALSE);
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=".$file_name.".csv");
echo self::convertToCSV($table_data, $headers_first_row);
exit;
}
public static function convertToCSV($table_data, $headers_first_row = FALSE)
{
$final_display = array();
$row_count = 0;
foreach($table_data as $table_row)
{
$row_count++;
$col_count = 0;
$display_row1 = array();
$display_row2 = array();
foreach($table_row as $table_col => $table_val)
{
$col_count++;
if (!$headers_first_row && $row_count == 1)
{
$display_row1[] = '"'.self::filterTexttoCSV($table_col).'"';
}
$display_row2[] = '"'.self::filterTexttoCSV($table_val).'"';
}
if ($display_row1)
{
$final_display[] = implode(',', $display_row1);
}
if ($display_row2)
{
$final_display[] = implode(',', $display_row2);
}
}
return implode("\n", $final_display);
}
public static function filterTextToCSV($text)
{
return str_replace('"', '""', $text);
}
/**
* Excel
*/
public static function excel($data, $version = 'Excel2007')
{
$doc = new \PHPExcel();
$doc->setActiveSheetIndex(0);
$sheet = $doc->getActiveSheet();
$sheet->setTitle('Exported Data');
$sheet->fromArray($data);
$version_specific = array(
'xlsx' => array(
'writer' => 'Excel2007',
'extension' => '.xlsx',
'mime-type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
),
'xls' => array(
'writer' => 'Excel5',
'extension' => '.xls',
'mime-type' => 'application/vnd.ms-excel',
),
'csv' => array(
'writer' => 'CSV',
'extension' => '.csv',
'mime-type' => 'text/csv',
),
'html' => array(
'writer' => 'HTML',
'extension' => '.html',
'mime-type' => 'text/html',
),
'pdf' => array(
'writer' => 'PDF',
'extension' => '.pdf',
'mime-type' => 'application/pdf',
),
);
$filename = 'Exported Data ('.date('Y-m-d').')';
$filename .= $version_specific[$version]['extension'];
$mime_type = $version_specific[$version]['mime-type'];
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", FALSE);
header("Content-Type: ".$mime_type);
header("Content-Disposition: attachment; filename=".$filename);
$writer = \PHPExcel_IOFactory::createWriter($doc, $version_specific[$version]['writer']);
$writer->save('php://output');
}
/**
* JSON
**/
public static function json($table_data)
{
return \Zend_Json::encode($table_data);
}
public static function exportToJSON($table_data)
{
return \Zend_Json::encode($table_data);
}
/**
* PDF
*/
public static function getPdfFonts()
{
$fonts_by_name = array(
'courier' => \Zend_Pdf_Font::FONT_COURIER,
'courier_bold' => \Zend_Pdf_Font::FONT_COURIER_BOLD,
'helvetica' => \Zend_Pdf_Font::FONT_HELVETICA,
'helvetica_bold' => \Zend_Pdf_Font::FONT_HELVETICA_BOLD,
'helvetica_oblique' => \Zend_Pdf_Font::FONT_HELVETICA_OBLIQUE,
);
$fonts_by_path = array(
'trebuchet' => DF_INCLUDE_STATIC.'/fonts/trebuc.ttf',
'trebuchet_bold' => DF_INCLUDE_STATIC.'/fonts/trebucbd.ttf',
'trebuchet_italic' => DF_INCLUDE_STATIC.'/fonts/trebucit.ttf',
'trebuchet_bolditalic' => DF_INCLUDE_STATIC.'/fonts/trebucbi.ttf',
'tahoma' => DF_INCLUDE_STATIC.'/fonts/tahoma.ttf',
'tahoma_bold' => DF_INCLUDE_STATIC.'/fonts/tahomabd.ttf',
'barcode' => DF_INCLUDE_STATIC.'/fonts/FRE3OF9X.TTF',
);
$font_results = array();
foreach($fonts_by_name as $font_key => $font_name)
{
$font_results[$font_key] = \Zend_Pdf_Font::fontWithName($font_name);
}
foreach($fonts_by_path as $font_key => $font_path)
{
if (file_exists($font_path))
$font_results[$font_key] = \Zend_Pdf_Font::fontWithPath($font_path);
}
return $font_results;
}
public static function displayPdf($pdf_obj)
{
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", FALSE);
header("Content-type: application/pdf");
echo $pdf_obj->render();
exit;
}
/**
* XML to Array
*/
public static function XmlToArray($xml)
{
$values = $index = $array = array();
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $xml, $values, $index);
xml_parser_free($parser);
$i = 0;
$name = $values[$i]['tag'];
$array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : '';
$array[$name] = self::_struct_to_array($values, $i);
return $array;
}
protected static function _struct_to_array($values, &$i)
{
$child = array();
if (isset($values[$i]['value'])) array_push($child, $values[$i]['value']);
while ($i++ < count($values)) {
switch ($values[$i]['type']) {
case 'cdata':
array_push($child, $values[$i]['value']);
break;
case 'complete':
$name = $values[$i]['tag'];
if(!empty($name)){
$child[$name]= ($values[$i]['value'])?($values[$i]['value']):'';
if(isset($values[$i]['attributes'])) {
$child[$name] = $values[$i]['attributes'];
}
}
break;
case 'open':
$name = $values[$i]['tag'];
$size = isset($child[$name]) ? sizeof($child[$name]) : 0;
$child[$name][$size] = self::_struct_to_array($values, $i);
break;
case 'close':
return $child;
break;
}
}
return $child;
}
public static function ArrayToXml($array)
{
$xml_info = new \SimpleXMLElement('<?xml version="1.0"?><return></return>');
self::_arr_to_xml($array, $xml_info);
return $xml_info->asXML();
}
protected static function _arr_to_xml($array, &$xml)
{
foreach((array)$array as $key => $value)
{
if(is_array($value))
{
$key = is_numeric($key) ? "item$key" : $key;
$subnode = $xml->addChild("$key");
self::_arr_to_xml($value, $subnode);
}
else
{
$key = is_numeric($key) ? "item$key" : $key;
$xml->addChild("$key", htmlspecialchars($value));
}
}
}
/**
* iCal
*/
public static function iCal($options)
{
$defaults = array(
'priority' => 0,
'uid' => date('Ymd').'T'.date('His').'-'.rand().'-dsa.tamu.edu',
'organizer' => 'noreply@dsa.tamu.edu',
'reminder' => '-PT15M',
'name' => 'Event',
'desc' => 'Event Invitation',
'location' => 'TBD',
);
$options = array_merge($defaults, $options);
$ical_lines = array(
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN',
'METHOD:REQUEST',
'BEGIN:VEVENT',
'ORGANIZER:MAILTO:'.$options['organizer'],
'UID:'.$options['uid'], // required by Outlok
'DTSTAMP:'.date('Ymd').'T'.date('His').'Z', // required by Outlook
'CREATED:'.date('Ymd').'T'.date('His').'Z', // required by Outlook
'LAST-MODIFIED:'.date('Ymd').'T'.date('His').'Z', // required by Outlook
'DTSTART:'.date('Ymd', $options['start_timestamp']).'T'.date('His', $options['start_timestamp']).'Z',
'DTEND:'.date('Ymd', $options['end_timestamp']).'T'.date('His', $options['end_timestamp']).'Z',
'SUMMARY:'.$options['name'],
'DESCRIPTION:'.$options['desc'],
'LOCATION:'.$options['location'],
'PRIORITY:'.$options['priority'],
'CLASS:PUBLIC',
'TRANSP:OPAQUE',
'TRIGGER:'.$options['reminder'],
'END:VEVENT',
'END:VCALENDAR',
);
return trim(implode("\r\n", $ical_lines));
}
<?php
/**
* Class with static methods for exporting data into various formats.
*/
namespace DF;
class Export
{
/**
* CSV
**/
public static function csv($table_data, $headers_first_row = TRUE, $file_name = "ExportedData")
{
self::exportToCSV($table_data, $headers_first_row, $file_name);
}
public static function exportToCSV($table_data, $headers_first_row = TRUE, $file_name = "ExportedData")
{
// Header data associated with CSV files.
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", FALSE);
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=".$file_name.".csv");
echo self::convertToCSV($table_data, $headers_first_row);
exit;
}
public static function convertToCSV($table_data, $headers_first_row = FALSE)
{
$final_display = array();
$row_count = 0;
foreach($table_data as $table_row)
{
$row_count++;
$col_count = 0;
$display_row1 = array();
$display_row2 = array();
foreach($table_row as $table_col => $table_val)
{
$col_count++;
if (!$headers_first_row && $row_count == 1)
{
$display_row1[] = '"'.self::filterTexttoCSV($table_col).'"';
}
$display_row2[] = '"'.self::filterTexttoCSV($table_val).'"';
}
if ($display_row1)
{
$final_display[] = implode(',', $display_row1);
}
if ($display_row2)
{
$final_display[] = implode(',', $display_row2);
}
}
return implode("\n", $final_display);
}
public static function filterTextToCSV($text)
{
return str_replace('"', '""', $text);
}
/**
* Excel
*/
public static function excel($data, $version = 'Excel2007')
{
$doc = new \PHPExcel();
$doc->setActiveSheetIndex(0);
$sheet = $doc->getActiveSheet();
$sheet->setTitle('Exported Data');
$sheet->fromArray($data);
$version_specific = array(
'xlsx' => array(
'writer' => 'Excel2007',
'extension' => '.xlsx',
'mime-type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
),
'xls' => array(
'writer' => 'Excel5',
'extension' => '.xls',
'mime-type' => 'application/vnd.ms-excel',
),
'csv' => array(
'writer' => 'CSV',
'extension' => '.csv',
'mime-type' => 'text/csv',
),
'html' => array(
'writer' => 'HTML',
'extension' => '.html',
'mime-type' => 'text/html',
),
'pdf' => array(
'writer' => 'PDF',
'extension' => '.pdf',
'mime-type' => 'application/pdf',
),
);
$filename = 'Exported Data ('.date('Y-m-d').')';
$filename .= $version_specific[$version]['extension'];
$mime_type = $version_specific[$version]['mime-type'];
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", FALSE);
header("Content-Type: ".$mime_type);
header("Content-Disposition: attachment; filename=".$filename);
$writer = \PHPExcel_IOFactory::createWriter($doc, $version_specific[$version]['writer']);
$writer->save('php://output');
}
/**
* JSON
**/
public static function json($table_data)
{
return \Zend_Json::encode($table_data);
}
public static function exportToJSON($table_data)
{
return \Zend_Json::encode($table_data);
}
/**
* PDF
*/
public static function getPdfFonts()
{
$fonts_by_name = array(
'courier' => \Zend_Pdf_Font::FONT_COURIER,
'courier_bold' => \Zend_Pdf_Font::FONT_COURIER_BOLD,
'helvetica' => \Zend_Pdf_Font::FONT_HELVETICA,
'helvetica_bold' => \Zend_Pdf_Font::FONT_HELVETICA_BOLD,
'helvetica_oblique' => \Zend_Pdf_Font::FONT_HELVETICA_OBLIQUE,
);
$fonts_by_path = array(
'trebuchet' => DF_INCLUDE_STATIC.'/fonts/trebuc.ttf',
'trebuchet_bold' => DF_INCLUDE_STATIC.'/fonts/trebucbd.ttf',
'trebuchet_italic' => DF_INCLUDE_STATIC.'/fonts/trebucit.ttf',
'trebuchet_bolditalic' => DF_INCLUDE_STATIC.'/fonts/trebucbi.ttf',
'tahoma' => DF_INCLUDE_STATIC.'/fonts/tahoma.ttf',
'tahoma_bold' => DF_INCLUDE_STATIC.'/fonts/tahomabd.ttf',
'barcode' => DF_INCLUDE_STATIC.'/fonts/FRE3OF9X.TTF',
);
$font_results = array();
foreach($fonts_by_name as $font_key => $font_name)
{
$font_results[$font_key] = \Zend_Pdf_Font::fontWithName($font_name);
}
foreach($fonts_by_path as $font_key => $font_path)
{
if (file_exists($font_path))
$font_results[$font_key] = \Zend_Pdf_Font::fontWithPath($font_path);
}
return $font_results;
}
public static function displayPdf($pdf_obj)
{
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", FALSE);
header("Content-type: application/pdf");
echo $pdf_obj->render();
exit;
}
/**
* XML to Array
*/
public static function XmlToArray($xml)
{
$values = $index = $array = array();
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $xml, $values, $index);
xml_parser_free($parser);
$i = 0;
$name = $values[$i]['tag'];
$array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : '';
$array[$name] = self::_struct_to_array($values, $i);
return $array;
}
protected static function _struct_to_array($values, &$i)
{
$child = array();
if (isset($values[$i]['value'])) array_push($child, $values[$i]['value']);
while ($i++ < count($values)) {
switch ($values[$i]['type']) {
case 'cdata':
array_push($child, $values[$i]['value']);
break;
case 'complete':
$name = $values[$i]['tag'];
if(!empty($name)){
$child[$name]= ($values[$i]['value'])?($values[$i]['value']):'';
if(isset($values[$i]['attributes'])) {
$child[$name] = $values[$i]['attributes'];
}
}
break;
case 'open':
$name = $values[$i]['tag'];
$size = isset($child[$name]) ? sizeof($child[$name]) : 0;
$child[$name][$size] = self::_struct_to_array($values, $i);
break;
case 'close':
return $child;
break;
}
}
return $child;
}
public static function ArrayToXml($array)
{
$xml_info = new \SimpleXMLElement('<?xml version="1.0"?><return></return>');
self::_arr_to_xml($array, $xml_info);
return $xml_info->asXML();
}
protected static function _arr_to_xml($array, &$xml)
{
foreach((array)$array as $key => $value)
{
if(is_array($value))
{
$key = is_numeric($key) ? "item$key" : $key;
$subnode = $xml->addChild("$key");
self::_arr_to_xml($value, $subnode);
}
else
{
$key = is_numeric($key) ? "item$key" : $key;
$xml->addChild("$key", htmlspecialchars($value));
}
}
}
/**
* iCal
*/
public static function iCal($options)
{
$defaults = array(
'priority' => 0,
'uid' => date('Ymd').'T'.date('His').'-'.rand().'-dsa.tamu.edu',
'organizer' => 'noreply@dsa.tamu.edu',
'reminder' => '-PT15M',
'name' => 'Event',
'desc' => 'Event Invitation',
'location' => 'TBD',
);
$options = array_merge($defaults, $options);
$ical_lines = array(
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN',
'METHOD:REQUEST',
'BEGIN:VEVENT',
'ORGANIZER:MAILTO:'.$options['organizer'],
'UID:'.$options['uid'], // required by Outlok
'DTSTAMP:'.date('Ymd').'T'.date('His').'Z', // required by Outlook
'CREATED:'.date('Ymd').'T'.date('His').'Z', // required by Outlook
'LAST-MODIFIED:'.date('Ymd').'T'.date('His').'Z', // required by Outlook
'DTSTART:'.date('Ymd', $options['start_timestamp']).'T'.date('His', $options['start_timestamp']).'Z',
'DTEND:'.date('Ymd', $options['end_timestamp']).'T'.date('His', $options['end_timestamp']).'Z',
'SUMMARY:'.$options['name'],
'DESCRIPTION:'.$options['desc'],
'LOCATION:'.$options['location'],
'PRIORITY:'.$options['priority'],
'CLASS:PUBLIC',
'TRANSP:OPAQUE',
'TRIGGER:'.$options['reminder'],
'END:VEVENT',
'END:VCALENDAR',
);
return trim(implode("\r\n", $ical_lines));
}
}

408
app/library/DF/File.php → phalcon/library/DF/File.php Executable file → Normal file
View File

@ -1,205 +1,205 @@
<?php
/**
* Static class that facilitates the uploading, reading and deletion of files in a controlled directory.
*/
namespace DF;
class File
{
// Add a suffix to a file *before* its extension.
public static function addSuffix($file_name, $suffix)
{
$file_parts = pathinfo($file_name);
$new_file_name = $file_parts['filename'].$suffix.'.'.$file_parts['extension'];
if ($file_parts['dirname'])
return $file_parts['dirname'].DIRECTORY_SEPARATOR.$new_file_name;
else
return $new_file_name;
}
public static function getFileExtension($file_name)
{
// Significantly more performant than using pathinfo function.
return substr($file_name, strrpos($file_name, '.')+1);
}
public static function getFilePath($file_name)
{
if (is_readable($file_name) || stristr($file_name, DF_UPLOAD_FOLDER) !== FALSE)
return $file_name;
else
return DF_UPLOAD_FOLDER.'/'.str_replace('..','',$file_name);
}
public static function getFileUrl($file_name)
{
if (defined('DF_UPLOAD_URL'))
return DF_UPLOAD_URL.'/'.$file_name;
else
return \DF\Url::content($file_name);
}
public static function isValidFile($uploaded_file, $allowed_extensions = NULL)
{
$is_valid_upload = (!empty($uploaded_file) && $uploaded_file['error'] == UPLOAD_ERR_OK);
if (!is_null($allowed_extensions))
{
$file_extension = self::getFileExtension($uploaded_file['name']);
$is_valid_extension = in_array($file_extension, $allowed_extensions);
}
else
{
$is_valid_extension = TRUE;
}
return $is_valid_upload && $is_valid_extension;
}
public static function moveUploadedFile($uploaded_file, $file_name = '')
{
if (!self::isValidFile($uploaded_file))
{
switch($uploaded_file['error'])
{
case UPLOAD_ERR_INI_SIZE:
throw new \DF\Exception\DisplayOnly('File Upload Error: The file you are attempting to upload is larger than allowed (upload_max_filesize).');
break;
case UPLOAD_ERR_FORM_SIZE:
throw new \DF\Exception\DisplayOnly('File Upload Error: The file you are attempting to upload is larger than allowed (MAX_FILE_SIZE).');
break;
case UPLOAD_ERR_PARTIAL:
throw new \DF\Exception\DisplayOnly('File Upload Error: The file you are attempting to upload was only partially uploaded.');
break;
case UPLOAD_ERR_NO_FILE:
throw new \DF\Exception\DisplayOnly('File Upload Error: No file was uploaded.');
break;
case UPLOAD_ERR_NO_TMP_DIR:
throw new \DF\Exception\DisplayOnly('File Upload Error: Missing a temporary folder.');
break;
case UPLOAD_ERR_CANT_WRITE:
throw new \DF\Exception\DisplayOnly('File Upload Error: Failed to write file to disk.');
break;
case UPLOAD_ERR_EXTENSION:
throw new \DF\Exception\DisplayOnly('File Upload Error: Upload stopped by extension.');
break;
default:
throw new \DF\Exception\DisplayOnly('File Upload Error: No file was specified.');
break;
}
exit;
}
if (empty($file_name))
{
$file_name = basename($uploaded_file['name']);
}
// Replace .??? with the correct file extension if listed.
$file_name = str_replace('.???', '.'.self::getFileExtension($uploaded_file['name']), $file_name);
$upload_path = self::getFilePath($file_name);
if (move_uploaded_file($uploaded_file['tmp_name'], $upload_path))
{
return $file_name;
}
else
{
throw new \DF\Exception\DisplayOnly('File Upload Error: Could not upload the file requested.');
exit;
}
}
public static function createFileFromData($file_name, $file_data)
{
file_put_contents(self::getFilePath($file_name), $file_data);
return $file_name;
}
public static function getFilePointer($file_name)
{
return fopen(self::getFilePath($file_name), 'r');
}
public static function getFileContents($file_name)
{
return file_get_contents(self::getFilePath($file_name));
}
public static function getCSV($file_name)
{
@ini_set('auto_detect_line_endings', 1);
$csv_data = array();
$handle = fopen(self::getFilePath($file_name), "r");
while (($data = fgetcsv($handle)) !== FALSE)
{
$csv_data[] = $data;
}
fclose($handle);
return $csv_data;
}
// Returns a "clean" array with the first row's text as the column names.
public static function getCleanCSV($file_name)
{
$csv_data = self::getCSV($file_name);
$clean_data = array();
if ($csv_data)
{
$headers = array();
$row_num = 0;
$col_num = 0;
$header_row = array_shift($csv_data);
foreach($header_row as $csv_col)
{
$field_name = strtolower(preg_replace("/[^a-zA-Z0-9_]/", "", $csv_col));
if (!empty($field_name))
$headers[$col_num] = $field_name;
$col_num++;
}
foreach($csv_data as $csv_row)
{
$col_num = 0;
$clean_row = array();
foreach($csv_row as $csv_col)
{
$col_name = (isset($headers[$col_num])) ? $headers[$col_num] : $col_num;
$clean_row[$col_name] = $csv_col;
$col_num++;
}
$clean_data[] = $clean_row;
$row_num++;
}
}
return $clean_data;
}
public static function renameFile($old_file, $new_file)
{
$old_file_path = self::getFilePath($old_file);
$new_file_path = self::getFilePath($new_file);
rename($old_file_path, $new_file_path);
return $new_file;
}
public static function deleteFile($file_name)
{
unlink(self::getFilePath($file_name));
}
<?php
/**
* Static class that facilitates the uploading, reading and deletion of files in a controlled directory.
*/
namespace DF;
class File
{
// Add a suffix to a file *before* its extension.
public static function addSuffix($file_name, $suffix)
{
$file_parts = pathinfo($file_name);
$new_file_name = $file_parts['filename'].$suffix.'.'.$file_parts['extension'];
if ($file_parts['dirname'])
return $file_parts['dirname'].DIRECTORY_SEPARATOR.$new_file_name;
else
return $new_file_name;
}
public static function getFileExtension($file_name)
{
// Significantly more performant than using pathinfo function.
return substr($file_name, strrpos($file_name, '.')+1);
}
public static function getFilePath($file_name)
{
if (is_readable($file_name) || stristr($file_name, DF_UPLOAD_FOLDER) !== FALSE)
return $file_name;
else
return DF_UPLOAD_FOLDER.'/'.str_replace('..','',$file_name);
}
public static function getFileUrl($file_name)
{
if (defined('DF_UPLOAD_URL'))
return DF_UPLOAD_URL.'/'.$file_name;
else
return \DF\Url::content($file_name);
}
public static function isValidFile($uploaded_file, $allowed_extensions = NULL)
{
$is_valid_upload = (!empty($uploaded_file) && $uploaded_file['error'] == UPLOAD_ERR_OK);
if (!is_null($allowed_extensions))
{
$file_extension = self::getFileExtension($uploaded_file['name']);
$is_valid_extension = in_array($file_extension, $allowed_extensions);
}
else
{
$is_valid_extension = TRUE;
}
return $is_valid_upload && $is_valid_extension;
}
public static function moveUploadedFile($uploaded_file, $file_name = '')
{
if (!self::isValidFile($uploaded_file))
{
switch($uploaded_file['error'])
{
case UPLOAD_ERR_INI_SIZE:
throw new \DF\Exception\DisplayOnly('File Upload Error: The file you are attempting to upload is larger than allowed (upload_max_filesize).');
break;
case UPLOAD_ERR_FORM_SIZE:
throw new \DF\Exception\DisplayOnly('File Upload Error: The file you are attempting to upload is larger than allowed (MAX_FILE_SIZE).');
break;
case UPLOAD_ERR_PARTIAL:
throw new \DF\Exception\DisplayOnly('File Upload Error: The file you are attempting to upload was only partially uploaded.');
break;
case UPLOAD_ERR_NO_FILE:
throw new \DF\Exception\DisplayOnly('File Upload Error: No file was uploaded.');
break;
case UPLOAD_ERR_NO_TMP_DIR:
throw new \DF\Exception\DisplayOnly('File Upload Error: Missing a temporary folder.');
break;
case UPLOAD_ERR_CANT_WRITE:
throw new \DF\Exception\DisplayOnly('File Upload Error: Failed to write file to disk.');
break;
case UPLOAD_ERR_EXTENSION:
throw new \DF\Exception\DisplayOnly('File Upload Error: Upload stopped by extension.');
break;
default:
throw new \DF\Exception\DisplayOnly('File Upload Error: No file was specified.');
break;
}
exit;
}
if (empty($file_name))
{
$file_name = basename($uploaded_file['name']);
}
// Replace .??? with the correct file extension if listed.
$file_name = str_replace('.???', '.'.self::getFileExtension($uploaded_file['name']), $file_name);
$upload_path = self::getFilePath($file_name);
if (move_uploaded_file($uploaded_file['tmp_name'], $upload_path))
{
return $file_name;
}
else
{
throw new \DF\Exception\DisplayOnly('File Upload Error: Could not upload the file requested.');
exit;
}
}
public static function createFileFromData($file_name, $file_data)
{
file_put_contents(self::getFilePath($file_name), $file_data);
return $file_name;
}
public static function getFilePointer($file_name)
{
return fopen(self::getFilePath($file_name), 'r');
}
public static function getFileContents($file_name)
{
return file_get_contents(self::getFilePath($file_name));
}
public static function getCSV($file_name)
{
@ini_set('auto_detect_line_endings', 1);
$csv_data = array();
$handle = fopen(self::getFilePath($file_name), "r");
while (($data = fgetcsv($handle)) !== FALSE)
{
$csv_data[] = $data;
}
fclose($handle);
return $csv_data;
}
// Returns a "clean" array with the first row's text as the column names.
public static function getCleanCSV($file_name)
{
$csv_data = self::getCSV($file_name);
$clean_data = array();
if ($csv_data)
{
$headers = array();
$row_num = 0;
$col_num = 0;
$header_row = array_shift($csv_data);
foreach($header_row as $csv_col)
{
$field_name = strtolower(preg_replace("/[^a-zA-Z0-9_]/", "", $csv_col));
if (!empty($field_name))
$headers[$col_num] = $field_name;
$col_num++;
}
foreach($csv_data as $csv_row)
{
$col_num = 0;
$clean_row = array();
foreach($csv_row as $csv_col)
{
$col_name = (isset($headers[$col_num])) ? $headers[$col_num] : $col_num;
$clean_row[$col_name] = $csv_col;
$col_num++;
}
$clean_data[] = $clean_row;
$row_num++;
}
}
return $clean_data;
}
public static function renameFile($old_file, $new_file)
{
$old_file_path = self::getFilePath($old_file);
$new_file_path = self::getFilePath($new_file);
rename($old_file_path, $new_file_path);
return $new_file;
}
public static function deleteFile($file_name)
{
unlink(self::getFilePath($file_name));
}
}

View File

@ -1,20 +1,20 @@
<?php
namespace DF\Filter;
class Float implements \Zend_Filter_Interface
{
/**
* Defined by Zend_Filter_Interface
*
* Returns (float) $value
*
* @param string $value
* @return float
*/
public function filter($value)
{
$value = (string)$value;
$value = preg_replace('#[^0-9\.\-]#', '', $value);
return (float)$value;
}
<?php
namespace DF\Filter;
class Float implements \Zend_Filter_Interface
{
/**
* Defined by Zend_Filter_Interface
*
* Returns (float) $value
*
* @param string $value
* @return float
*/
public function filter($value)
{
$value = (string)$value;
$value = preg_replace('#[^0-9\.\-]#', '', $value);
return (float)$value;
}
}

110
app/library/DF/Flash.php → phalcon/library/DF/Flash.php Executable file → Normal file
View File

@ -1,56 +1,56 @@
<?php
/**
* Quick message queue
*/
namespace DF;
class Flash
{
const SUCCESS = 'success';
const WARNING = 'warning';
const ERROR = 'error';
const INFO = 'info';
public static function addMessage($message, $level = self::INFO)
{
$session = \DF\Session::get('alerts');
$color_chart = array(
'green' => 'success',
'success' => 'success',
'yellow' => 'warning',
'warning' => 'warning',
'red' => 'error',
'error' => 'error',
'info' => 'info',
'blue' => 'info',
'default' => 'info',
);
$messages = (array)$session->messages;
$messages[] = array(
'message' => $message,
'color' => (isset($color_chart[$level])) ? $color_chart[$level] : $color_chart['default'],
);
$session->messages = $messages;
}
public static function hasMessages()
{
$session = \DF\Session::get('alerts');
$messages = (array)$session->messages;
return count($messages) > 0;
}
public static function getMessages()
{
$session = \DF\Session::get('alerts');
$messages = (array)$session->messages;
unset($session->messages);
return (count($messages) > 0) ? $messages : false;
}
<?php
/**
* Quick message queue
*/
namespace DF;
class Flash
{
const SUCCESS = 'success';
const WARNING = 'warning';
const ERROR = 'error';
const INFO = 'info';
public static function addMessage($message, $level = self::INFO)
{
$session = \DF\Session::get('alerts');
$color_chart = array(
'green' => 'success',
'success' => 'success',
'yellow' => 'warning',
'warning' => 'warning',
'red' => 'error',
'error' => 'error',
'info' => 'info',
'blue' => 'info',
'default' => 'info',
);
$messages = (array)$session->messages;
$messages[] = array(
'message' => $message,
'color' => (isset($color_chart[$level])) ? $color_chart[$level] : $color_chart['default'],
);
$session->messages = $messages;
}
public static function hasMessages()
{
$session = \DF\Session::get('alerts');
$messages = (array)$session->messages;
return count($messages) > 0;
}
public static function getMessages()
{
$session = \DF\Session::get('alerts');
$messages = (array)$session->messages;
unset($session->messages);
return (count($messages) > 0) ? $messages : false;
}
}

View File

@ -1,333 +1,333 @@
<?php
namespace DF;
class Form extends \Zend_Form
{
/**
* Custom override of the Zend_Form constructor
*/
public function __construct($options = null)
{
$this->getPluginLoader(\Zend_Form::DECORATOR)->addPrefixPath('\DF\Form\Decorator\\', 'DF/Form/Decorator');
$this->getPluginLoader(\Zend_Form::ELEMENT)->addPrefixPath('\DF\Form\Element\\', 'DF/Form/Element');
$this->addElementPrefixPath('\DF\Validate\\', 'DF/Validate', \Zend_Form_Element::VALIDATE);
$this->addElementPrefixPath('\DF\Filter\\', 'DF/Filter', \Zend_Form_Element::FILTER);
$this->setElementFilters(array('StringTrim'));
if ($options instanceof \Zend_Config)
$options = $options->toArray();
if (is_array($options) && isset($options['groups']))
{
foreach($options['groups'] as $group_key => $group)
{
// Special handling for items named "submit".
if ($group_key == "submit")
$group_key = "submit_grp";
$group_elements = (array)$group['elements'];
unset($group['elements']);
$options['displayGroups'][$group_key] = array(
'elements' => array(),
'options' => $group,
);
foreach($group_elements as $element_key => $element_info)
{
$options['displayGroups'][$group_key]['elements'][] = $element_key;
$options['elements'][$element_key] = $element_info;
}
}
unset($options['groups']);
}
// Check for default value.
$defaults = array();
foreach((array)$options['elements'] as $element_name => $element_info)
{
if (isset($element_info[1]['default']))
{
$defaults[$element_name] = $element_info[1]['default'];
unset($options['elements'][$element_name][1]['default']);
}
}
parent::__construct($options);
$this->setDefaults($defaults);
}
public function isSubForm()
{
return FALSE;
}
public function setDefault($name, $value)
{
$name = (string) $name;
if ($element = $this->getElement($name))
{
$element->setAttrib('df_raw_value', $value);
}
return parent::setDefault($name, $value);
}
protected function _dissolveArrayValue($value, $arrayPath)
{
return (array)parent::_dissolveArrayValue($value, $arrayPath);
}
public function clearAllDecorators()
{
$this->clearDecorators();
foreach($this->getElements() as $element)
$element->clearDecorators();
foreach($this->getDisplayGroups() as $group)
$group->clearDecorators();
foreach($this->getSubForms() as $form)
{
if ($form instanceof self)
$form->clearAllDecorators();
else
$form->clearDecorators();
}
return $this;
}
protected function preRender(\Zend_View_Interface &$view = null)
{
foreach($this->getElements() as $element)
{
$element->setDecorators(array(
array(
'SpanFormErrors',
array(
'class' => 'help-block error',
'escape' => FALSE,
'placement' => \Zend_Form_Decorator_Abstract::PREPEND,
),
),
array(
'Description',
array(
'tag' => 'span',
'class' => 'help-block '.$errors,
'escape' => FALSE,
'placement' => \Zend_Form_Decorator_Abstract::PREPEND,
)
),
));
if ($element instanceof \Zend_Form_Element_File)
{
$element->addDecorators(array(
array(
'FormFileEdit',
array(
'placement' => \Zend_Form_Decorator_Abstract::APPEND,
),
),
));
}
else
{
$element->addDecorators(array(
array(
'ViewHelper',
array(
'placement' => \Zend_Form_Decorator_Abstract::APPEND,
),
),
));
}
if (!($element instanceof \Zend_Form_Element_Button || $element instanceof \Zend_Form_Element_Submit))
{
$element->addDecorators(array(
array(
'Label',
array(
'escape' => FALSE,
'optionalSuffix' => ':',
'requiredSuffix' => '<span style="color: #FF0000;">*</span>:',
),
),
array(
'HtmlTag',
array(
'tag' => 'div',
'class' => 'clearfix control-group',
),
),
));
}
if( $element instanceOf \Zend_Form_Element_Hidden )
{
$element->setDecorators(array(
'ViewHelper',
));
}
}
$subform_decorators = array(
array(
'Description',
array(
'tag' => 'span',
'class' => 'help-block in-fieldset',
'escape' => FALSE,
)
),
array(
'FormElements',
array(
'tag' => '',
)
),
);
$group_decorators = array_merge($subform_decorators, array(
array('Fieldset'),
));
if (!$this->isSubForm())
{
$this->setDecorators(array(
array('FormErrors'),
array('FormElements'),
array('Form', array(
'class' => 'form-stacked df-form',
)),
));
}
$this->setDisplayGroupDecorators($group_decorators);
$this->setSubFormDecorators($subform_decorators);
}
public function render(\Zend_View_Interface $view = null)
{
$view_mode = $GLOBALS['df_form_mode'];
if ($view_mode == "view" || $view_mode == "message")
$this->preRenderView($view);
else
$this->preRender($view);
return parent::render($view);
}
public function renderSpecial(\Zend_View_Interface $view = null, $view_mode = 'edit')
{
$GLOBALS['df_form_mode'] = $view_mode;
$return_value = $this->render($view);
$GLOBALS['df_form_mode'] = NULL;
return $return_value;
}
public function renderView(\Zend_View_Interface $view = null)
{
return $this->renderSpecial($view, 'view');
}
public function renderMessage(\Zend_View_Interface $view = null)
{
return $this->renderSpecial($view, 'message');
}
/**
* Read-only view
*/
public function preRenderView(\Zend_View_Interface $view = null)
{
foreach($this->getElements() as $element)
{
$element->setDecorators(array(
'FormView',
));
if ($element instanceof \Zend_Form_Element_Button ||
$element instanceof \Zend_Form_Element_Submit ||
$element instanceof \Zend_Form_Element_Hidden ||
$element instanceof Form\Element\Markup)
{
// Don't show these types of elements in this view
$element->clearDecorators();
}
else if ($element instanceof \Zend_Form_Element_File)
{
// Add a fake "Form File View" decorator, since Zend_Form_Element_File needs it.
$element->addDecorators(array(
'FormFileView',
));
}
}
$group_decorators = array(
array('FormElements'),
array('FormView'),
);
$this->setDecorators($group_decorators);
$this->setDisplayGroupDecorators($group_decorators);
$this->setSubFormDecorators($group_decorators);
}
/**
* File upload processing
*/
public function processFiles($destination_folder, $file_name_prefix = '')
{
$return_fields = array();
// Check for upload directory.
$base_dir = DF_UPLOAD_FOLDER.DIRECTORY_SEPARATOR.$destination_folder;
if (!file_exists($base_dir))
@mkdir($base_dir);
foreach($this->getElements() as $element_name => $element)
{
if ($element instanceof \Zend_Form_Element_File)
{
$element_name_clean = preg_replace('#[^a-zA-Z0-9\_]#', '', $element_name);
$file_names = (array)$element->getFileName();
$original_files = (array)$element->getOriginalValue();
if (!empty($file_names))
{
$i = 1;
foreach($file_names as $file_path_original)
{
$new_file_name = ($file_name_prefix) ? $file_name_prefix.'_' : '';
$new_file_name .= date('Ymd_His').'_'.mt_rand(100, 999).'_'.$element_name_clean.'_'.$i.'.'.File::getFileExtension($file_path_original);
$new_file_path_short = $destination_folder.DIRECTORY_SEPARATOR.$new_file_name;
$new_file_path_full = DF_UPLOAD_FOLDER.DIRECTORY_SEPARATOR.$new_file_path_short;
if (!is_writable(dirname($new_file_path_full)))
throw new \DF\Exception('New directory not writable.');
@rename($file_path_original, $new_file_path_full);
$return_fields[$element_name][$i] = $new_file_path_short;
$i++;
}
}
}
}
return $return_fields;
}
<?php
namespace DF;
class Form extends \Zend_Form
{
/**
* Custom override of the Zend_Form constructor
*/
public function __construct($options = null)
{
$this->getPluginLoader(\Zend_Form::DECORATOR)->addPrefixPath('\DF\Form\Decorator\\', 'DF/Form/Decorator');
$this->getPluginLoader(\Zend_Form::ELEMENT)->addPrefixPath('\DF\Form\Element\\', 'DF/Form/Element');
$this->addElementPrefixPath('\DF\Validate\\', 'DF/Validate', \Zend_Form_Element::VALIDATE);
$this->addElementPrefixPath('\DF\Filter\\', 'DF/Filter', \Zend_Form_Element::FILTER);
$this->setElementFilters(array('StringTrim'));
if ($options instanceof \Zend_Config)
$options = $options->toArray();
if (is_array($options) && isset($options['groups']))
{
foreach($options['groups'] as $group_key => $group)
{
// Special handling for items named "submit".
if ($group_key == "submit")
$group_key = "submit_grp";
$group_elements = (array)$group['elements'];
unset($group['elements']);
$options['displayGroups'][$group_key] = array(
'elements' => array(),
'options' => $group,
);
foreach($group_elements as $element_key => $element_info)
{
$options['displayGroups'][$group_key]['elements'][] = $element_key;
$options['elements'][$element_key] = $element_info;
}
}
unset($options['groups']);
}
// Check for default value.
$defaults = array();
foreach((array)$options['elements'] as $element_name => $element_info)
{
if (isset($element_info[1]['default']))
{
$defaults[$element_name] = $element_info[1]['default'];
unset($options['elements'][$element_name][1]['default']);
}
}
parent::__construct($options);
$this->setDefaults($defaults);
}
public function isSubForm()
{
return FALSE;
}
public function setDefault($name, $value)
{
$name = (string) $name;
if ($element = $this->getElement($name))
{
$element->setAttrib('df_raw_value', $value);
}
return parent::setDefault($name, $value);
}
protected function _dissolveArrayValue($value, $arrayPath)
{
return (array)parent::_dissolveArrayValue($value, $arrayPath);
}
public function clearAllDecorators()
{
$this->clearDecorators();
foreach($this->getElements() as $element)
$element->clearDecorators();
foreach($this->getDisplayGroups() as $group)
$group->clearDecorators();
foreach($this->getSubForms() as $form)
{
if ($form instanceof self)
$form->clearAllDecorators();
else
$form->clearDecorators();
}
return $this;
}
protected function preRender(\Zend_View_Interface &$view = null)
{
foreach($this->getElements() as $element)
{
$element->setDecorators(array(
array(
'SpanFormErrors',
array(
'class' => 'help-block error',
'escape' => FALSE,
'placement' => \Zend_Form_Decorator_Abstract::PREPEND,
),
),
array(
'Description',
array(
'tag' => 'span',
'class' => 'help-block '.$errors,
'escape' => FALSE,
'placement' => \Zend_Form_Decorator_Abstract::PREPEND,
)
),
));
if ($element instanceof \Zend_Form_Element_File)
{
$element->addDecorators(array(
array(
'FormFileEdit',
array(
'placement' => \Zend_Form_Decorator_Abstract::APPEND,
),
),
));
}
else
{
$element->addDecorators(array(
array(
'ViewHelper',
array(
'placement' => \Zend_Form_Decorator_Abstract::APPEND,
),
),
));
}
if (!($element instanceof \Zend_Form_Element_Button || $element instanceof \Zend_Form_Element_Submit))
{
$element->addDecorators(array(
array(
'Label',
array(
'escape' => FALSE,
'optionalSuffix' => ':',
'requiredSuffix' => '<span style="color: #FF0000;">*</span>:',
),
),
array(
'HtmlTag',
array(
'tag' => 'div',
'class' => 'clearfix control-group',
),
),
));
}
if( $element instanceOf \Zend_Form_Element_Hidden )
{
$element->setDecorators(array(
'ViewHelper',
));
}
}
$subform_decorators = array(
array(
'Description',
array(
'tag' => 'span',
'class' => 'help-block in-fieldset',
'escape' => FALSE,
)
),
array(
'FormElements',
array(
'tag' => '',
)
),
);
$group_decorators = array_merge($subform_decorators, array(
array('Fieldset'),
));
if (!$this->isSubForm())
{
$this->setDecorators(array(
array('FormErrors'),
array('FormElements'),
array('Form', array(
'class' => 'form-stacked df-form',
)),
));
}
$this->setDisplayGroupDecorators($group_decorators);
$this->setSubFormDecorators($subform_decorators);
}
public function render(\Zend_View_Interface $view = null)
{
$view_mode = $GLOBALS['df_form_mode'];
if ($view_mode == "view" || $view_mode == "message")
$this->preRenderView($view);
else
$this->preRender($view);
return parent::render($view);
}
public function renderSpecial(\Zend_View_Interface $view = null, $view_mode = 'edit')
{
$GLOBALS['df_form_mode'] = $view_mode;
$return_value = $this->render($view);
$GLOBALS['df_form_mode'] = NULL;
return $return_value;
}
public function renderView(\Zend_View_Interface $view = null)
{
return $this->renderSpecial($view, 'view');
}
public function renderMessage(\Zend_View_Interface $view = null)
{
return $this->renderSpecial($view, 'message');
}
/**
* Read-only view
*/
public function preRenderView(\Zend_View_Interface $view = null)
{
foreach($this->getElements() as $element)
{
$element->setDecorators(array(
'FormView',
));
if ($element instanceof \Zend_Form_Element_Button ||
$element instanceof \Zend_Form_Element_Submit ||
$element instanceof \Zend_Form_Element_Hidden ||
$element instanceof Form\Element\Markup)
{
// Don't show these types of elements in this view
$element->clearDecorators();
}
else if ($element instanceof \Zend_Form_Element_File)
{
// Add a fake "Form File View" decorator, since Zend_Form_Element_File needs it.
$element->addDecorators(array(
'FormFileView',
));
}
}
$group_decorators = array(
array('FormElements'),
array('FormView'),
);
$this->setDecorators($group_decorators);
$this->setDisplayGroupDecorators($group_decorators);
$this->setSubFormDecorators($group_decorators);
}
/**
* File upload processing
*/
public function processFiles($destination_folder, $file_name_prefix = '')
{
$return_fields = array();
// Check for upload directory.
$base_dir = DF_UPLOAD_FOLDER.DIRECTORY_SEPARATOR.$destination_folder;
if (!file_exists($base_dir))
@mkdir($base_dir);
foreach($this->getElements() as $element_name => $element)
{
if ($element instanceof \Zend_Form_Element_File)
{
$element_name_clean = preg_replace('#[^a-zA-Z0-9\_]#', '', $element_name);
$file_names = (array)$element->getFileName();
$original_files = (array)$element->getOriginalValue();
if (!empty($file_names))
{
$i = 1;
foreach($file_names as $file_path_original)
{
$new_file_name = ($file_name_prefix) ? $file_name_prefix.'_' : '';
$new_file_name .= date('Ymd_His').'_'.mt_rand(100, 999).'_'.$element_name_clean.'_'.$i.'.'.File::getFileExtension($file_path_original);
$new_file_path_short = $destination_folder.DIRECTORY_SEPARATOR.$new_file_name;
$new_file_path_full = DF_UPLOAD_FOLDER.DIRECTORY_SEPARATOR.$new_file_path_short;
if (!is_writable(dirname($new_file_path_full)))
throw new \DF\Exception('New directory not writable.');
@rename($file_path_original, $new_file_path_full);
$return_fields[$element_name][$i] = $new_file_path_short;
$i++;
}
}
}
}
return $return_fields;
}
}

View File

@ -1,39 +1,39 @@
<?php
namespace DF\Form;
class Custom extends \DF\Form
{
private $_parameters;
public function setParameters(array $parameters)
{
foreach( $parameters as $key => $value )
$this->setParameter((string)$key, $value);
return $this;
}
public function setParameter($key, $value)
{
$this->_parameters[(string)$key] = $value;
return $this;
}
public function getParameter($key, $default = null)
{
if( isset($this->_parameters[(string)$key]) )
return $this->_parameters[(string)$key];
else
return $default;
}
public function getParameters()
{
return (array)$this->_parameters;
}
public function save()
{
throw new \DF\Exception\Warning("Save function not implemented.");
}
<?php
namespace DF\Form;
class Custom extends \DF\Form
{
private $_parameters;
public function setParameters(array $parameters)
{
foreach( $parameters as $key => $value )
$this->setParameter((string)$key, $value);
return $this;
}
public function setParameter($key, $value)
{
$this->_parameters[(string)$key] = $value;
return $this;
}
public function getParameter($key, $default = null)
{
if( isset($this->_parameters[(string)$key]) )
return $this->_parameters[(string)$key];
else
return $default;
}
public function getParameters()
{
return (array)$this->_parameters;
}
public function save()
{
throw new \DF\Exception\Warning("Save function not implemented.");
}
}

View File

@ -1,38 +1,38 @@
<?php
namespace DF\Form\Decorator;
class FormFileEdit extends \Zend_Form_Decorator_File implements \Zend_Form_Decorator_Marker_File_Interface
{
public function render($content)
{
$form_field = parent::render($content);
$element = $this->getElement();
$value = $element->getOriginalValue();
if (defined('DF_UPLOAD_URL') && DF_UPLOAD_URL)
$url_base = DF_UPLOAD_URL;
else
$url_base = \DF\Url::content();
if ($value)
{
$form_field .= '</dd><dd class="warning"><b>Note:</b> You have already uploaded the file(s) listed below. To keep these files, leave this field blank.';
if (!is_array($value))
$value = array($value);
$i = 0;
foreach($value as $existing_file)
{
$i++;
$file_url = $url_base.'/'.$existing_file;
$form_field .= '<div>#'.$i.': <a href="'.$file_url.'" target="_blank">Download File</a></div>';
}
$form_field .= '</dd>';
}
return $form_field;
}
}
<?php
namespace DF\Form\Decorator;
class FormFileEdit extends \Zend_Form_Decorator_File implements \Zend_Form_Decorator_Marker_File_Interface
{
public function render($content)
{
$form_field = parent::render($content);
$element = $this->getElement();
$value = $element->getOriginalValue();
if (defined('DF_UPLOAD_URL') && DF_UPLOAD_URL)
$url_base = DF_UPLOAD_URL;
else
$url_base = \DF\Url::content();
if ($value)
{
$form_field .= '</dd><dd class="warning"><b>Note:</b> You have already uploaded the file(s) listed below. To keep these files, leave this field blank.';
if (!is_array($value))
$value = array($value);
$i = 0;
foreach($value as $existing_file)
{
$i++;
$file_url = $url_base.'/'.$existing_file;
$form_field .= '<div>#'.$i.': <a href="'.$file_url.'" target="_blank">Download File</a></div>';
}
$form_field .= '</dd>';
}
return $form_field;
}
}

View File

@ -1,37 +1,37 @@
<?php
namespace DF\Form\Decorator;
class SpanFormErrors extends \Zend_Form_Decorator_Abstract
{
/**
* Render errors
*
* @param string $content
* @return string
*/
public function render($content)
{
$element = $this->getElement();
$view = $element->getView();
if (null === $view) {
return $content;
}
$errors = $element->getMessages();
if (empty($errors)) {
return $content;
}
$separator = $this->getSeparator();
$placement = $this->getPlacement();
$errors = $view->spanFormErrors($errors, $this->getOptions());
switch ($placement) {
case self::APPEND:
return $content . $separator . $errors;
case self::PREPEND:
return $errors . $separator . $content;
}
}
}
<?php
namespace DF\Form\Decorator;
class SpanFormErrors extends \Zend_Form_Decorator_Abstract
{
/**
* Render errors
*
* @param string $content
* @return string
*/
public function render($content)
{
$element = $this->getElement();
$view = $element->getView();
if (null === $view) {
return $content;
}
$errors = $element->getMessages();
if (empty($errors)) {
return $content;
}
$separator = $this->getSeparator();
$placement = $this->getPlacement();
$errors = $view->spanFormErrors($errors, $this->getOptions());
switch ($placement) {
case self::APPEND:
return $content . $separator . $errors;
case self::PREPEND:
return $errors . $separator . $content;
}
}
}

View File

@ -1,19 +1,19 @@
<?php
/**
* UNIX Timestamp Form Element
*/
namespace DF\Form\Element;
class File extends \Zend_Form_Element_File
{
protected $_original_value;
public function setValue($value)
{
$this->_original_value = $value;
}
public function getOriginalValue()
{
return $this->_original_value;
}
<?php
/**
* UNIX Timestamp Form Element
*/
namespace DF\Form\Element;
class File extends \Zend_Form_Element_File
{
protected $_original_value;
public function setValue($value)
{
$this->_original_value = $value;
}
public function getOriginalValue()
{
return $this->_original_value;
}
}

View File

@ -1,15 +1,15 @@
<?php
/**
* UNIX Timestamp Form Element
*/
namespace DF\Form\Element;
class Markup extends \Zend_Form_Element
{
public $helper = 'formMarkup';
public function getValue()
{
return NULL;
}
<?php
/**
* UNIX Timestamp Form Element
*/
namespace DF\Form\Element;
class Markup extends \Zend_Form_Element
{
public $helper = 'formMarkup';
public function getValue()
{
return NULL;
}
}

View File

@ -1,61 +1,61 @@
<?php
/**
* UNIX Timestamp Form Element
*/
namespace DF\Form\Element;
class UnixDate extends \Zend_Form_Element_Xhtml
{
public $helper = 'formUnixDate';
public $field_timestamp;
public $field_year;
public $field_month;
public $field_day;
public function setValue($value)
{
if (is_numeric($value))
$timestamp = $value;
elseif (is_string($value))
$timestamp = strtotime($value.' UTC');
elseif ($value instanceof \DateTime)
$timestamp = $value->getTimestamp();
elseif (is_array($value))
$timestamp = self::processArray($value);
else if (!$value)
$timestamp = 0;
else
throw new \Exception('Invalid date value provided');
$this->field_timestamp = (int)$timestamp;
$this->field_year = ($timestamp) ? gmdate('Y', $timestamp) : '';
$this->field_month = ($timestamp) ? gmdate('m', $timestamp) : '';
$this->field_day = ($timestamp) ? gmdate('d', $timestamp) : '';
return $this;
}
public function getValue()
{
return $this->field_timestamp;
}
public static function processArray($value, $default_timestamp = null)
{
$default_timestamp = $default_timestamp ?: time();
if (empty($value['month']) && empty($value['day']) && empty($value['year']))
{
return $default_timestamp;
}
else
{
$month = (!empty($value['month'])) ? (int)$value['month'] : gmdate('m', $default_timestamp);
$day = (!empty($value['day'])) ? (int)$value['day'] : gmdate('d', $default_timestamp);
$year = (!empty($value['year'])) ? (int)$value['year'] : gmdate('Y', $default_timestamp);
return strtotime($month.'/'.$day.'/'.$year.' 00:00:00 UTC');
}
}
<?php
/**
* UNIX Timestamp Form Element
*/
namespace DF\Form\Element;
class UnixDate extends \Zend_Form_Element_Xhtml
{
public $helper = 'formUnixDate';
public $field_timestamp;
public $field_year;
public $field_month;
public $field_day;
public function setValue($value)
{
if (is_numeric($value))
$timestamp = $value;
elseif (is_string($value))
$timestamp = strtotime($value.' UTC');
elseif ($value instanceof \DateTime)
$timestamp = $value->getTimestamp();
elseif (is_array($value))
$timestamp = self::processArray($value);
else if (!$value)
$timestamp = 0;
else
throw new \Exception('Invalid date value provided');
$this->field_timestamp = (int)$timestamp;
$this->field_year = ($timestamp) ? gmdate('Y', $timestamp) : '';
$this->field_month = ($timestamp) ? gmdate('m', $timestamp) : '';
$this->field_day = ($timestamp) ? gmdate('d', $timestamp) : '';
return $this;
}
public function getValue()
{
return $this->field_timestamp;
}
public static function processArray($value, $default_timestamp = null)
{
$default_timestamp = $default_timestamp ?: time();
if (empty($value['month']) && empty($value['day']) && empty($value['year']))
{
return $default_timestamp;
}
else
{
$month = (!empty($value['month'])) ? (int)$value['month'] : gmdate('m', $default_timestamp);
$day = (!empty($value['day'])) ? (int)$value['day'] : gmdate('d', $default_timestamp);
$year = (!empty($value['year'])) ? (int)$value['year'] : gmdate('Y', $default_timestamp);
return strtotime($month.'/'.$day.'/'.$year.' 00:00:00 UTC');
}
}
}

View File

@ -1,68 +1,68 @@
<?php
/**
* UNIX Timestamp Form Element
*/
namespace DF\Form\Element;
class UnixDateTime extends \Zend_Form_Element_Xhtml
{
public $helper = 'formUnixDateTime';
public $field_timestamp = 0;
public $field_year;
public $field_month;
public $field_day;
public $field_hour;
public $field_minute;
public $field_meridian;
public function setValue($value)
{
if (is_numeric($value))
$timestamp = $value;
elseif (is_string($value))
$timestamp = strtotime($value);
elseif ($value instanceof \DateTime)
$timestamp = $value->getTimestamp();
elseif (is_array($value))
$timestamp = self::processArray($value);
else if (!$value)
$timestamp = 0;
else
throw new \Exception('Invalid date value provided');
$this->field_timestamp = (int)$timestamp;
$this->field_year = ($timestamp) ? date('Y', $timestamp) : '';
$this->field_month = ($timestamp) ? date('m', $timestamp) : '';
$this->field_day = ($timestamp) ? date('d', $timestamp) : '';
$this->field_hour = ($timestamp) ? date('g', $timestamp) : '';
$this->field_minute = ($timestamp) ? date('i', $timestamp) : '';
$this->field_meridian = ($timestamp) ? date('a', $timestamp) : '';
return $this;
}
public function getValue()
{
return $this->field_timestamp;
}
public static function processArray($value, $default_timestamp = null)
{
$default_timestamp = $default_timestamp ?: time();
$month = (isset($value['month'])) ? (int)$value['month'] : date('m', $default_timestamp);
$day = (isset($value['day'])) ? (int)$value['day'] : date('d', $default_timestamp);
$year = (isset($value['year'])) ? (int)$value['year'] : date('Y', $default_timestamp);
$hour = (isset($value['hour'])) ? (int)$value['hour'] : date('g', $default_timestamp);
$minute = (isset($value['minute'])) ? (int)$value['minute'] : date('i', $default_timestamp);
$meridian = (isset($value['meridian'])) ? $value['meridian'] : date('a', $default_timestamp);
return strtotime($month.'/'.$day.'/'.$year.' '.$hour.':'.str_pad($minute, 2, '0', STR_PAD_LEFT).' '.$meridian);
}
<?php
/**
* UNIX Timestamp Form Element
*/
namespace DF\Form\Element;
class UnixDateTime extends \Zend_Form_Element_Xhtml
{
public $helper = 'formUnixDateTime';
public $field_timestamp = 0;
public $field_year;
public $field_month;
public $field_day;
public $field_hour;
public $field_minute;
public $field_meridian;
public function setValue($value)
{
if (is_numeric($value))
$timestamp = $value;
elseif (is_string($value))
$timestamp = strtotime($value);
elseif ($value instanceof \DateTime)
$timestamp = $value->getTimestamp();
elseif (is_array($value))
$timestamp = self::processArray($value);
else if (!$value)
$timestamp = 0;
else
throw new \Exception('Invalid date value provided');
$this->field_timestamp = (int)$timestamp;
$this->field_year = ($timestamp) ? date('Y', $timestamp) : '';
$this->field_month = ($timestamp) ? date('m', $timestamp) : '';
$this->field_day = ($timestamp) ? date('d', $timestamp) : '';
$this->field_hour = ($timestamp) ? date('g', $timestamp) : '';
$this->field_minute = ($timestamp) ? date('i', $timestamp) : '';
$this->field_meridian = ($timestamp) ? date('a', $timestamp) : '';
return $this;
}
public function getValue()
{
return $this->field_timestamp;
}
public static function processArray($value, $default_timestamp = null)
{
$default_timestamp = $default_timestamp ?: time();
$month = (isset($value['month'])) ? (int)$value['month'] : date('m', $default_timestamp);
$day = (isset($value['day'])) ? (int)$value['day'] : date('d', $default_timestamp);
$year = (isset($value['year'])) ? (int)$value['year'] : date('Y', $default_timestamp);
$hour = (isset($value['hour'])) ? (int)$value['hour'] : date('g', $default_timestamp);
$minute = (isset($value['minute'])) ? (int)$value['minute'] : date('i', $default_timestamp);
$meridian = (isset($value['meridian'])) ? $value['meridian'] : date('a', $default_timestamp);
return strtotime($month.'/'.$day.'/'.$year.' '.$hour.':'.str_pad($minute, 2, '0', STR_PAD_LEFT).' '.$meridian);
}
}

View File

@ -1,9 +1,9 @@
<?php
namespace DF\Form;
class SubForm extends \DF\Form
{
public function isSubForm()
{
return TRUE;
}
<?php
namespace DF\Form;
class SubForm extends \DF\Form
{
public function isSubForm()
{
return TRUE;
}
}

View File

@ -1,95 +1,95 @@
<?php
/**
* Image management utility class.
*/
namespace DF;
class Image
{
public static function resizeImage($source_file, $dest_file, $width, $height)
{
if (!is_readable($source_file))
$source_file = File::getFilePath($source_file);
if (!is_readable($dest_file))
$dest_file = File::getFilePath($dest_file);
if (!file_exists($source_file))
throw new Exception('Original image file not found!');
$source_extension = strtolower(File::getFileExtension($source_file));
$dest_extension = strtolower(File::getFileExtension($dest_file));
switch($source_extension)
{
case 'jpg':
case 'jpeg':
$image = imagecreatefromjpeg($source_file);
break;
case 'gif':
$image = imagecreatefromgif($source_file);
break;
case 'png':
$image = imagecreatefrompng($source_file);
break;
}
$image_width = imagesx($image);
$image_height = imagesy($image);
// Don't resize if the uploaded picture if smaller than the requirements.
if ($image_width <= $width && $image_height <= $height)
{
$resized_image = $image;
if ($dest_extension == 'png')
{
imagealphablending($resized_image, false);
imagesavealpha($resized_image, true);
$transparent = imagecolorallocatealpha($resized_image, 255, 255, 255, 127);
imagefilledrectangle($resized_image, 0, 0, $resized_width, $resized_height, $transparent);
}
}
else
{
// Create file resized to the proper proportions.
$resized_ratio_width = $width / $image_width;
$resized_ratio_height = $height / $image_height;
$resized_ratio = min($resized_ratio_width, $resized_ratio_height);
$resized_width = round($image_width * $resized_ratio);
$resized_height = round($image_height * $resized_ratio);
$resized_image = imagecreatetruecolor($resized_width, $resized_height);
if ($dest_extension == 'png')
{
imagealphablending($resized_image, false);
imagesavealpha($resized_image, true);
$transparent = imagecolorallocatealpha($resized_image, 255, 255, 255, 127);
imagefilledrectangle($resized_image, 0, 0, $resized_width, $resized_height, $transparent);
}
imagecopyresampled($resized_image, $image, 0, 0, 0, 0, $resized_width, $resized_height, $image_width, $image_height);
}
switch($dest_extension)
{
case 'jpg':
case 'jpeg':
imagejpeg($resized_image, $dest_file, 90);
break;
case 'gif':
imagegif($resized_image, $dest_file);
break;
case 'png':
imagepng($resized_image, $dest_file, 5);
break;
}
}
<?php
/**
* Image management utility class.
*/
namespace DF;
class Image
{
public static function resizeImage($source_file, $dest_file, $width, $height)
{
if (!is_readable($source_file))
$source_file = File::getFilePath($source_file);
if (!is_readable($dest_file))
$dest_file = File::getFilePath($dest_file);
if (!file_exists($source_file))
throw new Exception('Original image file not found!');
$source_extension = strtolower(File::getFileExtension($source_file));
$dest_extension = strtolower(File::getFileExtension($dest_file));
switch($source_extension)
{
case 'jpg':
case 'jpeg':
$image = imagecreatefromjpeg($source_file);
break;
case 'gif':
$image = imagecreatefromgif($source_file);
break;
case 'png':
$image = imagecreatefrompng($source_file);
break;
}
$image_width = imagesx($image);
$image_height = imagesy($image);
// Don't resize if the uploaded picture if smaller than the requirements.
if ($image_width <= $width && $image_height <= $height)
{
$resized_image = $image;
if ($dest_extension == 'png')
{
imagealphablending($resized_image, false);
imagesavealpha($resized_image, true);
$transparent = imagecolorallocatealpha($resized_image, 255, 255, 255, 127);
imagefilledrectangle($resized_image, 0, 0, $resized_width, $resized_height, $transparent);
}
}
else
{
// Create file resized to the proper proportions.
$resized_ratio_width = $width / $image_width;
$resized_ratio_height = $height / $image_height;
$resized_ratio = min($resized_ratio_width, $resized_ratio_height);
$resized_width = round($image_width * $resized_ratio);
$resized_height = round($image_height * $resized_ratio);
$resized_image = imagecreatetruecolor($resized_width, $resized_height);
if ($dest_extension == 'png')
{
imagealphablending($resized_image, false);
imagesavealpha($resized_image, true);
$transparent = imagecolorallocatealpha($resized_image, 255, 255, 255, 127);
imagefilledrectangle($resized_image, 0, 0, $resized_width, $resized_height, $transparent);
}
imagecopyresampled($resized_image, $image, 0, 0, 0, 0, $resized_width, $resized_height, $image_width, $image_height);
}
switch($dest_extension)
{
case 'jpg':
case 'jpeg':
imagejpeg($resized_image, $dest_file, 90);
break;
case 'gif':
imagegif($resized_image, $dest_file);
break;
case 'png':
imagepng($resized_image, $dest_file, 5);
break;
}
}
}

View File

@ -1,83 +1,83 @@
<?php
/**
* Autoloader with namespace absolute path caching
*/
namespace DF;
class Loader
{
static $autoload_classes = array();
public static function loadClass($class_name)
{
if (strpos($class_name, '\\') === 0)
$class_name = substr($class_name, 1);
// Look through pre-assigned list of include paths first.
foreach(self::$autoload_classes as $class_prefix => $class_dir)
{
if (strpos($class_name, $class_prefix) === 0)
{
// Special handling for Doctrine 2.2 proxies.
if ($class_prefix == "Proxy")
{
$find = array('\\', 'Proxy');
$replace = array('', 'Proxy'.DIRECTORY_SEPARATOR);
$class_path = $class_dir.DIRECTORY_SEPARATOR.str_replace($find, $replace, $class_name).'.php';
}
else
{
$find = array('\\', '_');
$replace = array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR);
$class_path = $class_dir.DIRECTORY_SEPARATOR.str_replace($find, $replace, $class_name).'.php';
}
if (@include($class_path))
return true;
else
break;
}
}
// Try loading the flat filename (some legacy classes)
$class_path = $class_name.'.php';
if (@include($class_path))
return true;
// Try loading the directory-separated filename (other legacy classes).
$class_path = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
if (@include($class_path))
return true;
return false;
}
public static function register($class_paths)
{
if ($class_paths instanceof \Zend_Config)
$class_paths = $class_paths->toArray();
foreach((array)$class_paths as $class_prefix => $class_dir)
{
self::$autoload_classes[$class_prefix] = $class_dir;
}
// Force an update of the include path.
$include_path = array();
$include_path[] = DF_INCLUDE_LIB;
$include_path[] = DF_INCLUDE_LIB.DIRECTORY_SEPARATOR.'ThirdParty';
if (defined('DF_INCLUDE_LIB_LOCAL'))
{
$include_path[] = DF_INCLUDE_LIB_LOCAL;
$include_path[] = DF_INCLUDE_LIB_LOCAL.DIRECTORY_SEPARATOR.'ThirdParty';
}
$include_path[] = get_include_path();
set_include_path(implode(PATH_SEPARATOR, $include_path));
spl_autoload_register(array(__CLASS__, 'loadClass'));
spl_autoload_register();
}
<?php
/**
* Autoloader with namespace absolute path caching
*/
namespace DF;
class Loader
{
static $autoload_classes = array();
public static function loadClass($class_name)
{
if (strpos($class_name, '\\') === 0)
$class_name = substr($class_name, 1);
// Look through pre-assigned list of include paths first.
foreach(self::$autoload_classes as $class_prefix => $class_dir)
{
if (strpos($class_name, $class_prefix) === 0)
{
// Special handling for Doctrine 2.2 proxies.
if ($class_prefix == "Proxy")
{
$find = array('\\', 'Proxy');
$replace = array('', 'Proxy'.DIRECTORY_SEPARATOR);
$class_path = $class_dir.DIRECTORY_SEPARATOR.str_replace($find, $replace, $class_name).'.php';
}
else
{
$find = array('\\', '_');
$replace = array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR);
$class_path = $class_dir.DIRECTORY_SEPARATOR.str_replace($find, $replace, $class_name).'.php';
}
if (@include($class_path))
return true;
else
break;
}
}
// Try loading the flat filename (some legacy classes)
$class_path = $class_name.'.php';
if (@include($class_path))
return true;
// Try loading the directory-separated filename (other legacy classes).
$class_path = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
if (@include($class_path))
return true;
return false;
}
public static function register($class_paths)
{
if ($class_paths instanceof \Zend_Config)
$class_paths = $class_paths->toArray();
foreach((array)$class_paths as $class_prefix => $class_dir)
{
self::$autoload_classes[$class_prefix] = $class_dir;
}
// Force an update of the include path.
$include_path = array();
$include_path[] = DF_INCLUDE_LIB;
$include_path[] = DF_INCLUDE_LIB.DIRECTORY_SEPARATOR.'ThirdParty';
if (defined('DF_INCLUDE_LIB_LOCAL'))
{
$include_path[] = DF_INCLUDE_LIB_LOCAL;
$include_path[] = DF_INCLUDE_LIB_LOCAL.DIRECTORY_SEPARATOR.'ThirdParty';
}
$include_path[] = get_include_path();
set_include_path(implode(PATH_SEPARATOR, $include_path));
spl_autoload_register(array(__CLASS__, 'loadClass'));
spl_autoload_register();
}
}

114
app/library/DF/Menu.php → phalcon/library/DF/Menu.php Executable file → Normal file
View File

@ -1,58 +1,58 @@
<?php
namespace DF;
class Menu
{
protected $menus;
/**
* @param array $menus Associative array of menus
*/
public function __construct(array $menus = array())
{
foreach($menus as $name => $structure)
{
$this->addMenu($name, $structure);
}
}
/**
*
* @param string $name
* @return boolean
*/
public function hasMenu($name = 'default')
{
return isset($this->menus[$name]);
}
/**
*
* @param string $name
* @return Zend_Navigation
*/
public function getMenu($name = 'default')
{
if( $this->hasMenu($name) )
{
$menu = $this->menus[$name];
if(!($menu instanceof Navigation))
$menu = $this->menus[$name] = new Navigation($menu);
return $menu;
}
}
/**
*
* @param string $name
* @param Zend_Navigation|array $structure
*/
public function addMenu($name, $structure)
{
if(is_array($structure))
$structure = $structure;
$this->menus[$name] = $structure;
}
<?php
namespace DF;
class Menu
{
protected $menus;
/**
* @param array $menus Associative array of menus
*/
public function __construct(array $menus = array())
{
foreach($menus as $name => $structure)
{
$this->addMenu($name, $structure);
}
}
/**
*
* @param string $name
* @return boolean
*/
public function hasMenu($name = 'default')
{
return isset($this->menus[$name]);
}
/**
*
* @param string $name
* @return Zend_Navigation
*/
public function getMenu($name = 'default')
{
if( $this->hasMenu($name) )
{
$menu = $this->menus[$name];
if(!($menu instanceof Navigation))
$menu = $this->menus[$name] = new Navigation($menu);
return $menu;
}
}
/**
*
* @param string $name
* @param Zend_Navigation|array $structure
*/
public function addMenu($name, $structure)
{
if(is_array($structure))
$structure = $structure;
$this->menus[$name] = $structure;
}
}

View File

@ -1,191 +1,191 @@
<?php
/**
* Messenger Class (E-mail Delivery)
*/
namespace DF;
class Messenger
{
/**
* New messenger method.
* Uses an expandable array of options and supports direct template rendering and subject prepending.
*/
public static function send($message_options)
{
$config = \Zend_Registry::get('config');
$default_options = array(
'reply_to' => NULL,
'delivery_date' => NULL,
'options' => NULL,
);
$options = array_merge($default_options, $message_options);
// Render the template as the message if a template is specified.
if (isset($options['template']))
{
$layout = new \Zend_Layout();
$layout->setLayoutPath($config->application->resources->layout->layoutPath);
$layout->setLayout('message');
$view_renderer = Application\Bootstrap::getNewView(FALSE);
$view = $view_renderer->view;
if (isset($options['module']))
$view_script_path = DF_INCLUDE_MODULES.DIRECTORY_SEPARATOR.$options['module'].DIRECTORY_SEPARATOR.'messages';
else
$view_script_path = $config->application->mail->templates;
$view->setScriptPath($view_script_path);
$view->subject = $options['subject'];
$view->assign((array)$options['vars']);
$layout->content = $view->render($options['template'].'.phtml');
$options['message'] = $layout->render();
}
else if (isset($options['body']) && !isset($options['message']))
{
$options['message'] = $options['body'];
unset($options['body']);
}
// Append the system name as a prefix to the message.
if (!isset($options['no_prefix']) || $options['no_prefix'] == FALSE)
{
$app_name = $config->application->name;
$options['subject'] = $app_name.': '.$options['subject'];
}
self::sendMail($options);
}
// Deliver a message.
public static function sendMail()
{
// Do not deliver mail on development environments.
if (DF_APPLICATION_ENV == "development" && !defined('DF_FORCE_EMAIL'))
return;
// Allow support for legacy argument style or new style.
$args = func_get_args();
if (func_num_args() == 1)
{
$options = $args[0];
}
else
{
$options = array_merge(array(
'to' => $args[0],
'subject' => $args[1],
'message' => $args[2],
'reply_to' => $args[3],
'delivery_date' => $args[4],
), $args[5]);
}
$config = \Zend_Registry::get('config');
$mail_config = $config->application->mail->toArray();
$validator = new \Zend_Validate_EmailAddress();
if (isset($mail_config['use_smtp']) && $mail_config['use_smtp'])
{
$smtp_config = $config->apis->smtp->toArray();
$smtp_server = $smtp_config['server'];
unset($smtp_config['server']);
$transport = new \Zend_Mail_Transport_Smtp($smtp_server, $smtp_config);
}
else
{
$transport = new \Zend_Mail_Transport_Sendmail();
}
if (!is_array($options['to']))
$options['to'] = array($options['to']);
foreach((array)$options['to'] as $mail_to_addr)
{
if ($mail_to_addr && $validator->isValid($mail_to_addr))
{
$mail = new \Zend_Mail();
$mail->setSubject($options['subject']);
$from_addr = (isset($options['from'])) ? $options['from'] : $mail_config['from_addr'];
$from_name = (isset($options['from_name'])) ? $options['from_name'] : $mail_config['from_name'];
$mail->setFrom($from_addr, $from_name);
if (isset($mail_config['bounce_addr']))
$mail->setReturnPath($mail_config['bounce_addr']);
// Include a specific "Direct replies to" header if specified.
if ($options['reply_to'] && $validator->isValid($options['reply_to']))
$mail->setReplyTo($options['reply_to']);
else if (isset($mail_config['reply_to']) && $mail_config['reply_to'])
$mail->setReplyTo($mail_config['reply_to']);
// Change the type of the e-mail's body if specified in the options.
if (isset($options['text_only']) && $options['text_only'])
$mail->setBodyText(strip_tags($options['message']));
else
$mail->setBodyHtml($options['message'], NULL, \Zend_Mime::ENCODING_8BIT);
// Add attachment if specified in options.
if (isset($options['attachments']))
{
foreach((array)$options['attachments'] as $attachment)
{
if ($attachment instanceof \Zend_Mime_Part)
$mail->addAttachment($attachment);
else
$mail->addAttachment(self::attachFile($attachment));
}
}
// Modify the mail type if specified.
if (isset($options['type']))
$mail->setType($options['type']);
$mail->addTo($mail_to_addr);
$mail->send($transport);
}
}
}
// Get a file attachment object for use in main messenging functions.
public static function attachFile($file_path, $file_name = NULL, $mime_type = NULL)
{
if (!file_exists($file_path))
throw new Exception('File not found for attachment!');
// Get the name of the file.
$file_name = (!is_null($file_name)) ? $file_name : basename($file_path);
// Compose the attachment object.
$at = new \Zend_Mime_Part(file_get_contents($file_path));
if (!is_null($mime_type))
$at->type = $mime_type;
$at->filename = $file_name;
$at->disposition = \Zend_Mime::DISPOSITION_INLINE;
$at->encoding = \Zend_Mime::ENCODING_BASE64;
return $at;
}
// Attach an iCalendar invitation.
public static function attachInvite($ics_data)
{
// Compose the attachment object.
$at = new \Zend_Mime_Part($ics_data);
$at->type = 'text/calendar';
$at->filename = 'calendar.ics';
$at->disposition = \Zend_Mime::DISPOSITION_INLINE;
$at->encoding = \Zend_Mime::ENCODING_8BIT;
return $at;
}
<?php
/**
* Messenger Class (E-mail Delivery)
*/
namespace DF;
class Messenger
{
/**
* New messenger method.
* Uses an expandable array of options and supports direct template rendering and subject prepending.
*/
public static function send($message_options)
{
$config = \Zend_Registry::get('config');
$default_options = array(
'reply_to' => NULL,
'delivery_date' => NULL,
'options' => NULL,
);
$options = array_merge($default_options, $message_options);
// Render the template as the message if a template is specified.
if (isset($options['template']))
{
$layout = new \Zend_Layout();
$layout->setLayoutPath($config->application->resources->layout->layoutPath);
$layout->setLayout('message');
$view_renderer = Application\Bootstrap::getNewView(FALSE);
$view = $view_renderer->view;
if (isset($options['module']))
$view_script_path = DF_INCLUDE_MODULES.DIRECTORY_SEPARATOR.$options['module'].DIRECTORY_SEPARATOR.'messages';
else
$view_script_path = $config->application->mail->templates;
$view->setScriptPath($view_script_path);
$view->subject = $options['subject'];
$view->assign((array)$options['vars']);
$layout->content = $view->render($options['template'].'.phtml');
$options['message'] = $layout->render();
}
else if (isset($options['body']) && !isset($options['message']))
{
$options['message'] = $options['body'];
unset($options['body']);
}
// Append the system name as a prefix to the message.
if (!isset($options['no_prefix']) || $options['no_prefix'] == FALSE)
{
$app_name = $config->application->name;
$options['subject'] = $app_name.': '.$options['subject'];
}
self::sendMail($options);
}
// Deliver a message.
public static function sendMail()
{
// Do not deliver mail on development environments.
if (DF_APPLICATION_ENV == "development" && !defined('DF_FORCE_EMAIL'))
return;
// Allow support for legacy argument style or new style.
$args = func_get_args();
if (func_num_args() == 1)
{
$options = $args[0];
}
else
{
$options = array_merge(array(
'to' => $args[0],
'subject' => $args[1],
'message' => $args[2],
'reply_to' => $args[3],
'delivery_date' => $args[4],
), $args[5]);
}
$config = \Zend_Registry::get('config');
$mail_config = $config->application->mail->toArray();
$validator = new \Zend_Validate_EmailAddress();
if (isset($mail_config['use_smtp']) && $mail_config['use_smtp'])
{
$smtp_config = $config->apis->smtp->toArray();
$smtp_server = $smtp_config['server'];
unset($smtp_config['server']);
$transport = new \Zend_Mail_Transport_Smtp($smtp_server, $smtp_config);
}
else
{
$transport = new \Zend_Mail_Transport_Sendmail();
}
if (!is_array($options['to']))
$options['to'] = array($options['to']);
foreach((array)$options['to'] as $mail_to_addr)
{
if ($mail_to_addr && $validator->isValid($mail_to_addr))
{
$mail = new \Zend_Mail();
$mail->setSubject($options['subject']);
$from_addr = (isset($options['from'])) ? $options['from'] : $mail_config['from_addr'];
$from_name = (isset($options['from_name'])) ? $options['from_name'] : $mail_config['from_name'];
$mail->setFrom($from_addr, $from_name);
if (isset($mail_config['bounce_addr']))
$mail->setReturnPath($mail_config['bounce_addr']);
// Include a specific "Direct replies to" header if specified.
if ($options['reply_to'] && $validator->isValid($options['reply_to']))
$mail->setReplyTo($options['reply_to']);
else if (isset($mail_config['reply_to']) && $mail_config['reply_to'])
$mail->setReplyTo($mail_config['reply_to']);
// Change the type of the e-mail's body if specified in the options.
if (isset($options['text_only']) && $options['text_only'])
$mail->setBodyText(strip_tags($options['message']));
else
$mail->setBodyHtml($options['message'], NULL, \Zend_Mime::ENCODING_8BIT);
// Add attachment if specified in options.
if (isset($options['attachments']))
{
foreach((array)$options['attachments'] as $attachment)
{
if ($attachment instanceof \Zend_Mime_Part)
$mail->addAttachment($attachment);
else
$mail->addAttachment(self::attachFile($attachment));
}
}
// Modify the mail type if specified.
if (isset($options['type']))
$mail->setType($options['type']);
$mail->addTo($mail_to_addr);
$mail->send($transport);
}
}
}
// Get a file attachment object for use in main messenging functions.
public static function attachFile($file_path, $file_name = NULL, $mime_type = NULL)
{
if (!file_exists($file_path))
throw new Exception('File not found for attachment!');
// Get the name of the file.
$file_name = (!is_null($file_name)) ? $file_name : basename($file_path);
// Compose the attachment object.
$at = new \Zend_Mime_Part(file_get_contents($file_path));
if (!is_null($mime_type))
$at->type = $mime_type;
$at->filename = $file_name;
$at->disposition = \Zend_Mime::DISPOSITION_INLINE;
$at->encoding = \Zend_Mime::ENCODING_BASE64;
return $at;
}
// Attach an iCalendar invitation.
public static function attachInvite($ics_data)
{
// Compose the attachment object.
$at = new \Zend_Mime_Part($ics_data);
$at->type = 'text/calendar';
$at->filename = 'calendar.ics';
$at->disposition = \Zend_Mime::DISPOSITION_INLINE;
$at->encoding = \Zend_Mime::ENCODING_8BIT;
return $at;
}
}

View File

@ -1,53 +1,53 @@
<?php
namespace DF;
/**
* Lightweight mobile device detection.
*/
class Mobile
{
public static function isMobile()
{
$mobile_browser = 0;
if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
{
$mobile_browser++;
}
if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE']))))
{
$mobile_browser++;
}
$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
$mobile_agents = array(
'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda ','xda-');
if (in_array($mobile_ua,$mobile_agents))
{
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini') > 0)
{
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows') > 0)
{
$mobile_browser = 0;
}
return ($mobile_browser > 0);
}
<?php
namespace DF;
/**
* Lightweight mobile device detection.
*/
class Mobile
{
public static function isMobile()
{
$mobile_browser = 0;
if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
{
$mobile_browser++;
}
if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE']))))
{
$mobile_browser++;
}
$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
$mobile_agents = array(
'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda ','xda-');
if (in_array($mobile_ua,$mobile_agents))
{
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini') > 0)
{
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows') > 0)
{
$mobile_browser = 0;
}
return ($mobile_browser > 0);
}
}

View File

@ -1,222 +1,222 @@
<?php
namespace DF;
class Navigation extends \Zend_Navigation
{
public function depthOfMenu($nav_item = NULL)
{
$nav_item = (is_null($nav_item)) ? $this : $nav_item;
$depth_num = 1;
$children_depths = array();
foreach($nav_item as $item)
{
if( $item->isActive(true) && $item->hasChildren() )
{
foreach($item as $child)
{
$children_depths[] = $this->depthOfMenu(array($child));
}
}
}
if ($children_depths)
{
$depth_num += max($children_depths);
}
return $depth_num;
}
public function hasActiveChildren($levels = 0, \Zend_Navigation_Page $items = null)
{
if( $items == null )
$items = $this;
foreach( $items as $item )
{
if( $item->isActive(true) && $item->hasChildren() )
{
if( $levels != 0 )
$this->hasActiveChildren($levels - 1, $item);
else
return true;
}
}
return false;
}
public function render(array $options = array())
{
$defaults = array(
'levels' => -1,
);
$options = array_merge($defaults, $options);
$items = array();
foreach( $this as $item )
{
$items[] = $this->_navRender($item, (int)$options['levels'] - 1, '', 'here');
}
if( empty($items) )
{
return "";
}
else
{
$retval = '<ul>'.implode("\n", $items).'</ul>';
return $retval;
}
}
public function renderActiveChildren(array $options = array())
{
$defaults = array(
'levels' => -1,
);
$options = array_merge($defaults, $options);
$childrenRetVal = '';
foreach( $this as $item )
{
if( $item->isActive(true) && $item->hasChildren() )
{
foreach( $item as $child )
{
$childrenRetVal .= $this->_navRender($child, $options['levels'] - 1, '', 'here');
}
}
}
if( $childrenRetVal == '' )
return "";
else
$retval .= $childrenRetVal;
return $retval;
}
public function getActiveChildren(array $options = array())
{
$defaults = array(
'levels' => -1,
);
$options = array_merge($defaults, $options);
$children = array();
foreach($this as $item)
{
if( $item->isActive(true) && $item->hasChildren() )
{
foreach($item as $child)
{
$children[] = $child;
}
}
}
return ($children) ? $children : array();
}
protected function _navRender(\Zend_Navigation_Page $page, $levels = -1, $class = '', $currentClass = 'here')
{
if( !self::_checkPermission($page) )
return '';
$class = str_replace('here', '', $class);
if( self::_isPageActive($page) )
{
$class = $class . " " . $currentClass;
if (!$page->hasChildren()) $class = $class . " nochildren";
}
$retval = '';
$page_label = $page->getLabel();
$retval .= ($page_label) ? '<a href="'.$page->getHref().'" class="'.$class.'">'.$page_label.'</a>' : '';
if( $page->hasChildren() && $levels != 0 )
{
$sub_retval = '';
foreach( $page as $child )
{
$sub_retval .= $this->_navRender($child, $levels - 1, $class, $currentClass);
}
if (!empty($sub_retval))
$retval .= '<ul>'.$sub_retval.'</ul>';
}
if (isset($page->show_only_with_subpages) && !$sub_retval)
return '';
if (!empty($retval))
return '<li>'.$retval.'</li>';
else
return '';
}
protected static function _checkPermission(\Zend_Navigation_Page $page)
{
if(isset($page->permission))
{
$acl = Acl::getInstance();
if (isset($page->is_dept) && $page->is_dept && method_exists($acl, 'isAllowedInDepartment'))
return $acl->isAllowedInDepartment($page->permission);
else
return $acl->isAllowed($page->permission);
}
return true;
}
protected static function _isPageActive(\Zend_Navigation_Page $page)
{
if( $page->isActive(true) )
return true;
static $current_params;
if($page instanceof \Zend_Navigation_Page_Mvc)
{
if( !isset($current_params) )
$current_params = \Zend_Controller_Front::getInstance()->getRequest()->getParams();
$menu_params = $page->getParams();
if ($param = $page->getModule())
{
$menu_params['module'] = $param;
}
if ($param = $page->getController())
{
$menu_params['controller'] = $param;
}
if ($param = $page->getAction())
{
$menu_params['action'] = $param;
}
$intersection = array_intersect_assoc($menu_params, $current_params);
$intersection_diff = array_diff_assoc($menu_params, $intersection);
if( empty($intersection_diff) )
{
$page->setActive();
}
}
elseif($page instanceOf \Zend_Navigation_Page_Uri)
{
if( isset($_SERVER['REQUEST_URI']) && preg_match("#^".preg_quote($page->getHref(), '#')."#i", $_SERVER['REQUEST_URI']) )
{
$page->setActive();
}
}
return $page->isActive(true);
}
<?php
namespace DF;
class Navigation extends \Zend_Navigation
{
public function depthOfMenu($nav_item = NULL)
{
$nav_item = (is_null($nav_item)) ? $this : $nav_item;
$depth_num = 1;
$children_depths = array();
foreach($nav_item as $item)
{
if( $item->isActive(true) && $item->hasChildren() )
{
foreach($item as $child)
{
$children_depths[] = $this->depthOfMenu(array($child));
}
}
}
if ($children_depths)
{
$depth_num += max($children_depths);
}
return $depth_num;
}
public function hasActiveChildren($levels = 0, \Zend_Navigation_Page $items = null)
{
if( $items == null )
$items = $this;
foreach( $items as $item )
{
if( $item->isActive(true) && $item->hasChildren() )
{
if( $levels != 0 )
$this->hasActiveChildren($levels - 1, $item);
else
return true;
}
}
return false;
}
public function render(array $options = array())
{
$defaults = array(
'levels' => -1,
);
$options = array_merge($defaults, $options);
$items = array();
foreach( $this as $item )
{
$items[] = $this->_navRender($item, (int)$options['levels'] - 1, '', 'here');
}
if( empty($items) )
{
return "";
}
else
{
$retval = '<ul>'.implode("\n", $items).'</ul>';
return $retval;
}
}
public function renderActiveChildren(array $options = array())
{
$defaults = array(
'levels' => -1,
);
$options = array_merge($defaults, $options);
$childrenRetVal = '';
foreach( $this as $item )
{
if( $item->isActive(true) && $item->hasChildren() )
{
foreach( $item as $child )
{
$childrenRetVal .= $this->_navRender($child, $options['levels'] - 1, '', 'here');
}
}
}
if( $childrenRetVal == '' )
return "";
else
$retval .= $childrenRetVal;
return $retval;
}
public function getActiveChildren(array $options = array())
{
$defaults = array(
'levels' => -1,
);
$options = array_merge($defaults, $options);
$children = array();
foreach($this as $item)
{
if( $item->isActive(true) && $item->hasChildren() )
{
foreach($item as $child)
{
$children[] = $child;
}
}
}
return ($children) ? $children : array();
}
protected function _navRender(\Zend_Navigation_Page $page, $levels = -1, $class = '', $currentClass = 'here')
{
if( !self::_checkPermission($page) )
return '';
$class = str_replace('here', '', $class);
if( self::_isPageActive($page) )
{
$class = $class . " " . $currentClass;
if (!$page->hasChildren()) $class = $class . " nochildren";
}
$retval = '';
$page_label = $page->getLabel();
$retval .= ($page_label) ? '<a href="'.$page->getHref().'" class="'.$class.'">'.$page_label.'</a>' : '';
if( $page->hasChildren() && $levels != 0 )
{
$sub_retval = '';
foreach( $page as $child )
{
$sub_retval .= $this->_navRender($child, $levels - 1, $class, $currentClass);
}
if (!empty($sub_retval))
$retval .= '<ul>'.$sub_retval.'</ul>';
}
if (isset($page->show_only_with_subpages) && !$sub_retval)
return '';
if (!empty($retval))
return '<li>'.$retval.'</li>';
else
return '';
}
protected static function _checkPermission(\Zend_Navigation_Page $page)
{
if(isset($page->permission))
{
$acl = Acl::getInstance();
if (isset($page->is_dept) && $page->is_dept && method_exists($acl, 'isAllowedInDepartment'))
return $acl->isAllowedInDepartment($page->permission);
else
return $acl->isAllowed($page->permission);
}
return true;
}
protected static function _isPageActive(\Zend_Navigation_Page $page)
{
if( $page->isActive(true) )
return true;
static $current_params;
if($page instanceof \Zend_Navigation_Page_Mvc)
{
if( !isset($current_params) )
$current_params = \Zend_Controller_Front::getInstance()->getRequest()->getParams();
$menu_params = $page->getParams();
if ($param = $page->getModule())
{
$menu_params['module'] = $param;
}
if ($param = $page->getController())
{
$menu_params['controller'] = $param;
}
if ($param = $page->getAction())
{
$menu_params['action'] = $param;
}
$intersection = array_intersect_assoc($menu_params, $current_params);
$intersection_diff = array_diff_assoc($menu_params, $intersection);
if( empty($intersection_diff) )
{
$page->setActive();
}
}
elseif($page instanceOf \Zend_Navigation_Page_Uri)
{
if( isset($_SERVER['REQUEST_URI']) && preg_match("#^".preg_quote($page->getHref(), '#')."#i", $_SERVER['REQUEST_URI']) )
{
$page->setActive();
}
}
return $page->isActive(true);
}
}

View File

View File

@ -1,118 +1,118 @@
<?php
namespace DF;
class Search
{
protected $_query;
protected $_fields;
public function __construct($from)
{
if (is_array($from))
{
$this->_query = Doctrine_Query::create();
foreach($from as $class)
{
$this->_query->from($from);
}
}
else
{
$this->_query = Doctrine_Query::create()->from($from);
}
}
public function setSearchFields($fields)
{
$this->_fields = $fields;
}
public function setSearchTerms($searchterms)
{
if (empty($searchterms))
{
\DF\Flash::addMessage('Please enter at least one search term.');
return false;
}
$quoted = array();
// get quoted strings from search terms
preg_match_all('/\"[^"]+\"/', $searchterms, $allmatches);
// pull out from other terms
if (count($allmatches) > 0)
{
$flat = array();
foreach($allmatches as $matchset)
{
$flat = array_merge($flat,array_unique($matchset));
}
$quoted = str_replace(array('"'),'',$flat);
$searchterms = preg_replace('/\"[^"]+\"/', '', $searchterms);
}
// break apart search terms
$terms = array_filter(explode(' ',$searchterms));
// combine with quoted strings
$terms = array_merge($terms,$quoted);
if (is_array($this->_fields))
{
$fields = $this->_fields;
}
else
{
$fields = $this->_query->getFieldNames();
}
$ors = array();
foreach($fields as $field)
{
foreach($terms as $term)
{
$ors[] = "($field LIKE '%$term%')";
}
}
$this->_query->addWhere('('.implode(' OR ', $ors).')');
return true;
}
public function setSort($sortfields)
{
if (is_array($sortfields))
{
foreach($sortfields as $sort)
{
$this->_query->addOrderBy($sort);
}
}
}
public function excludeDeleted()
{
$this->_query->addWhere('deleted_at IS NULL');
}
public function includeIds(Array $id_array)
{
//$list = implode(',',$id_array);
$this->_query->addWhereIn('id', $id_array);
}
public function execute($page = 1, $per_page = -1)
{
if( $per_page < 1 )
{
return array(
'pager' => null,
'results' => $this->_query->execute(),
);
}
else
{
$pager = new Doctrine_Pager($this->_query, $page, $per_page);
return array(
'pager' => $pager,
'results' => $pager->execute(),
);
}
}
<?php
namespace DF;
class Search
{
protected $_query;
protected $_fields;
public function __construct($from)
{
if (is_array($from))
{
$this->_query = Doctrine_Query::create();
foreach($from as $class)
{
$this->_query->from($from);
}
}
else
{
$this->_query = Doctrine_Query::create()->from($from);
}
}
public function setSearchFields($fields)
{
$this->_fields = $fields;
}
public function setSearchTerms($searchterms)
{
if (empty($searchterms))
{
\DF\Flash::addMessage('Please enter at least one search term.');
return false;
}
$quoted = array();
// get quoted strings from search terms
preg_match_all('/\"[^"]+\"/', $searchterms, $allmatches);
// pull out from other terms
if (count($allmatches) > 0)
{
$flat = array();
foreach($allmatches as $matchset)
{
$flat = array_merge($flat,array_unique($matchset));
}
$quoted = str_replace(array('"'),'',$flat);
$searchterms = preg_replace('/\"[^"]+\"/', '', $searchterms);
}
// break apart search terms
$terms = array_filter(explode(' ',$searchterms));
// combine with quoted strings
$terms = array_merge($terms,$quoted);
if (is_array($this->_fields))
{
$fields = $this->_fields;
}
else
{
$fields = $this->_query->getFieldNames();
}
$ors = array();
foreach($fields as $field)
{
foreach($terms as $term)
{
$ors[] = "($field LIKE '%$term%')";
}
}
$this->_query->addWhere('('.implode(' OR ', $ors).')');
return true;
}
public function setSort($sortfields)
{
if (is_array($sortfields))
{
foreach($sortfields as $sort)
{
$this->_query->addOrderBy($sort);
}
}
}
public function excludeDeleted()
{
$this->_query->addWhere('deleted_at IS NULL');
}
public function includeIds(Array $id_array)
{
//$list = implode(',',$id_array);
$this->_query->addWhereIn('id', $id_array);
}
public function execute($page = 1, $per_page = -1)
{
if( $per_page < 1 )
{
return array(
'pager' => null,
'results' => $this->_query->execute(),
);
}
else
{
$pager = new Doctrine_Pager($this->_query, $page, $per_page);
return array(
'pager' => $pager,
'results' => $pager->execute(),
);
}
}
}

View File

@ -0,0 +1,148 @@
<?php
namespace DF\Service;
use \Doctrine\Common\ClassLoader;
use \Doctrine\DBAL\Types\Type;
class Doctrine
{
public static function init($options)
{
if(empty($options))
return false;
// Register custom data types.
Type::addType('json', 'DF\Doctrine\Type\Json');
Type::addType('unixdatetime', 'DF\Doctrine\Type\UnixDateTime');
Type::overrideType('array', 'DF\Doctrine\Type\SoftArray');
Type::overrideType('datetime', 'DF\Doctrine\Type\UTCDateTime');
// Fetch and store entity manager.
$em = self::getEntityManager();
$conn = $em->getConnection();
$platform = $conn->getDatabasePlatform();
$platform->markDoctrineTypeCommented(Type::getType('json'));
$platform->markDoctrineTypeCommented(Type::getType('unixdatetime'));
return $em;
}
protected static function getEntityManager()
{
$options = $this->getOptions();
$config = new \Doctrine\ORM\Configuration;
$app_config = \Zend_Registry::get('config');
$options['conn'] = $app_config->db->toArray();
// Handling for class names specified as platform types.
if ($options['conn']['platform'])
{
$class_obj = new \ReflectionClass($options['conn']['platform']);
$options['conn']['platform'] = $class_obj->newInstance();
}
// Special handling for the utf8mb4 type.
if ($options['conn']['driver'] == 'pdo_mysql' && $options['conn']['charset'] == 'utf8mb4')
{
$options['conn']['platform'] = new \DF\Doctrine\Platform\MysqlUnicode;
}
$metadata_driver = $config->newDefaultAnnotationDriver($options['modelPath']);
$config->setMetadataDriverImpl($metadata_driver);
$regen_proxies = FALSE;
if (DF_APPLICATION_ENV == "production" && !DF_IS_COMMAND_LINE)
{
$cache = new \DF\Doctrine\Cache;
$cache->setNamespace('doctrine_');
// Clear cache in case of updated production code.
$upload_reference_path = DF_INCLUDE_BASE.DIRECTORY_SEPARATOR . '.env';
$update_reference_path = DF_INCLUDE_BASE.DIRECTORY_SEPARATOR . '.updated';
if (!file_exists($update_reference_path))
{
@file_put_contents($update_reference_path, 'This file is automatically modified to track proxy regeneration.');
@touch($upload_reference_path);
}
clearstatcache();
$last_upload_time = (int)@filemtime($upload_reference_path);
$last_update_time = (int)@filemtime($update_reference_path);
if ($last_upload_time >= $last_update_time)
{
@touch($update_reference_path);
// Flush the cache.
$cache->flushAll();
// Clear the proxy directory.
$proxy_dir = $options['proxyPath'];
@mkdir($proxy_dir);
$files = glob($proxy_dir.DIRECTORY_SEPARATOR.'*.php');
foreach((array)$files as $file)
@unlink($file);
// Trigger proxy regeneration below.
$regen_proxies = TRUE;
$config->setAutoGenerateProxyClasses(TRUE);
}
}
else
{
$cache = new \Doctrine\Common\Cache\ArrayCache;
}
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
$config->setResultCacheImpl($cache);
$config->setProxyDir($options['proxyPath']);
$config->setProxyNamespace($options['proxyNamespace']);
if (!$regen_proxies)
$config->setAutoGenerateProxyClasses($options['autoGenerateProxies']);
if (isset($options['conn']['debug']) && $options['conn']['debug'])
$config->setSQLLogger(new \DF\Doctrine\Logger\EchoSQL);
$config->addFilter('softdelete', '\DF\Doctrine\Filter\SoftDelete');
$config->addCustomNumericFunction('RAND', '\DF\Doctrine\Functions\Rand');
$evm = new \Doctrine\Common\EventManager();
$em = \Doctrine\ORM\EntityManager::create($options['conn'], $config, $evm);
$em->getFilters()->enable("softdelete");
// Trigger proxy regeneration.
if ($regen_proxies)
{
$metadatas = $em->getMetadataFactory()->getAllMetadata();
$em->getProxyFactory()->generateProxyClasses($metadatas);
}
// Try the connection before rendering the page.
try
{
$em->getConnection()->connect();
}
catch(\Exception $e)
{
$db_config_location = str_replace(DF_INCLUDE_ROOT, '', DF_INCLUDE_APP).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'application.conf.php';
\DF\Application\Maintenance::display('
<h2>Database Error</h2>
<p>The system could not connect to the database. Verify that the information listed in "<i>'.$db_config_location.'</i>" is correct.</p>
<blockquote>'.$e->getMessage().'</blockquote>
');
exit;
}
return $em;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,21 +1,21 @@
<?php
/**
* Gravatar - Globally Recognized Avatars Connector
*/
namespace DF\Service;
class Gravatar
{
public static function get($email, $size=50, $default='mm')
{
$grav_prefix = (DF_IS_SECURE) ? 'https://secure.gravatar.com' : 'http://www.gravatar.com';
$url_params = array(
'd' => $default,
'r' => 'g',
'size' => $size,
);
$grav_url = $grav_prefix.'/avatar/'.md5(strtolower($email)).'?'.http_build_query($url_params);
return htmlspecialchars($grav_url);
}
<?php
/**
* Gravatar - Globally Recognized Avatars Connector
*/
namespace DF\Service;
class Gravatar
{
public static function get($email, $size=50, $default='mm')
{
$grav_prefix = (DF_IS_SECURE) ? 'https://secure.gravatar.com' : 'http://www.gravatar.com';
$url_params = array(
'd' => $default,
'r' => 'g',
'size' => $size,
);
$grav_url = $grav_prefix.'/avatar/'.md5(strtolower($email)).'?'.http_build_query($url_params);
return htmlspecialchars($grav_url);
}
}

View File

@ -1,62 +1,62 @@
<?php
/**
* DF_Session:
* Extender for session management
*/
namespace DF;
class Session
{
public static function start()
{
static $is_started = false;
if (DF_IS_COMMAND_LINE)
return false;
if (!$is_started)
$is_started = session_start();
return $is_started;
}
public static function get($namespace = 'default')
{
return self::getNamespace($namespace);
}
public static function getNamespace($namespace = 'default')
{
if (!self::start())
return new \stdClass;
static $sessions = array();
$session_name = self::getNamespaceName($namespace);
if (!isset($sessions[$session_name]))
{
if (DF_IS_COMMAND_LINE)
$sessions[$session_name] = new \stdClass;
else
$sessions[$session_name] = new \DF\Session\Instance($session_name);
}
return $sessions[$session_name];
}
public static function getNamespaceName($suffix = 'default')
{
$app_hash = strtoupper(substr(md5(DF_INCLUDE_BASE), 0, 5));
return 'DF_'.$app_hash.'_'.$suffix;
}
public static function suspend()
{
@session_write_close();
}
public static function resume()
{
@session_start();
}
<?php
/**
* DF_Session:
* Extender for session management
*/
namespace DF;
class Session
{
public static function start()
{
static $is_started = false;
if (DF_IS_COMMAND_LINE)
return false;
if (!$is_started)
$is_started = session_start();
return $is_started;
}
public static function get($namespace = 'default')
{
return self::getNamespace($namespace);
}
public static function getNamespace($namespace = 'default')
{
if (!self::start())
return new \stdClass;
static $sessions = array();
$session_name = self::getNamespaceName($namespace);
if (!isset($sessions[$session_name]))
{
if (DF_IS_COMMAND_LINE)
$sessions[$session_name] = new \stdClass;
else
$sessions[$session_name] = new \DF\Session\Instance($session_name);
}
return $sessions[$session_name];
}
public static function getNamespaceName($suffix = 'default')
{
$app_hash = strtoupper(substr(md5(DF_INCLUDE_BASE), 0, 5));
return 'DF_'.$app_hash.'_'.$suffix;
}
public static function suspend()
{
@session_write_close();
}
public static function resume()
{
@session_start();
}
}

View File

@ -1,22 +1,22 @@
<?php
namespace DF\Test;
/**
* @backupGlobals disabled
*/
class TestCase extends \Zend_Test_PHPUnit_ControllerTestCase
{
public function setUp()
{
$this->bootstrap = \Zend_Registry::get('application');
parent::setUp();
}
public function tearDown()
{
$this->resetRequest();
$this->resetResponse();
parent::tearDown();
}
<?php
namespace DF\Test;
/**
* @backupGlobals disabled
*/
class TestCase extends \Zend_Test_PHPUnit_ControllerTestCase
{
public function setUp()
{
$this->bootstrap = \Zend_Registry::get('application');
parent::setUp();
}
public function tearDown()
{
$this->resetRequest();
$this->resetResponse();
parent::tearDown();
}
}

View File

@ -1,272 +1,272 @@
<?php
namespace DF;
class Url
{
static $base_url;
/**
* Returns the baseUrl
*
* @throws \Zend_Exception
* @return string
*/
public static function baseUrl()
{
if (self::$base_url !== NULL)
{
return self::$base_url;
}
else
{
$config = \Zend_Registry::get('config');
if ($config->application->base_url)
{
$base_url = $config->application->base_url;
if (DF_IS_SECURE)
$base_url = str_replace('http://', 'https://', $base_url);
return $base_url;
}
else
{
$base_url = \Zend_Controller_Front::getInstance()->getBaseUrl();
return self::domain(TRUE) . $base_url;
}
}
}
public static function setBaseUrl($new_base_url)
{
self::$base_url = $new_base_url;
$router = self::getRouter();
$front = $router->getFrontController();
$front->setBaseUrl($new_base_url);
}
// Conversion from '//' scheme-independent URL to scheme-explicit URLs
static $original_base_url;
public static function forceSchemePrefix()
{
if (!empty(self::$original_base_url))
return null;
self::$original_base_url = self::baseUrl();
$new_base_url = self::addSchemePrefix(self::$original_base_url);
self::setBaseUrl($new_base_url);
}
public static function restoreNonPrefixed()
{
self::setBaseUrl(self::$original_base_url);
self::$original_base_url = null;
}
public static function addSchemePrefix($url)
{
if (substr($url, 0, 2) == '//')
return 'http'.((DF_IS_SECURE) ? 's:' : ':').$url;
return $url;
}
// Return path to static content.
public static function content($file_name = NULL)
{
if (defined('DF_URL_STATIC'))
$static_url_base = DF_URL_STATIC;
else
$static_url_base = self::baseUrl().'/static';
if ($file_name !== NULL)
return $static_url_base.'/'.$file_name;
else
return $static_url_base;
}
// Return path to uploaded file.
public static function file($file_name = NULL)
{
if (defined('DF_UPLOAD_URL'))
{
$static_url_base = self::baseUrl().DF_UPLOAD_URL;
if ($file_name !== NULL)
return $static_url_base.'/'.$file_name;
else
return $static_url_base;
}
else
{
return self::content($file_name);
}
}
public static function cdn($library_name, $library_version)
{
$cdn_base = '//ajax.googleapis.com/ajax/libs';
switch($library_name)
{
case 'jquery':
return $cdn_base.'/jquery/'.$library_version.'/jquery.min.js';
break;
case 'jqueryui':
return $cdn_base.'/jqueryui/'.$library_version.'/jquery-ui.min.js';
break;
}
}
public static function domain($includeScheme = false)
{
if (!empty($_SERVER['HTTP_HOST']))
{
$domain = $_SERVER['HTTP_HOST'];
if ($includeScheme)
$domain = 'http' . ((DF_IS_SECURE) ? 's' : '') . '://' . $domain;
return $domain;
}
return '';
}
/**
* Returns the referring URL, or, if no referring url, return the default
* url set (by default "false").
*
* @param string $default
* @return string
*/
public static function referrer($default = false)
{
if( isset($_SERVER['HTTP_REFERER']) )
return $_SERVER['HTTP_REFERER'];
else
return $default;
}
public static function current($includeSchemeDomain = TRUE, $include_request_uri = TRUE)
{
$prefix = '';
if($includeSchemeDomain)
{
$prefix = 'http' . (DF_IS_SECURE ? 's' : '') . '://' . $_SERVER['HTTP_HOST'];
}
$uri = '';
if (isset($_SERVER['REQUEST_URI']))
{
$uri = $_SERVER['REQUEST_URI'];
}
else
{
$uri = self::route($request->getParams()).self::arrayToGetString($_GET);
}
if (!$include_request_uri && strstr($uri, '?') !== FALSE)
{
$uri = substr($uri, 0, strpos($uri, '?'));
}
return $prefix.$uri;
}
/**
* Generate a URL based on a route
*
* @param array $options variables to pass to the router
* @param string $route which route to process
* @param boolean $reset reset automatic variable assignment
* @param boolean $encode url_encode() all pieces of the url
* @param array $get array of values for a ?get=string to be appended to the URL
* @return string Generated URL
*/
public static function route(array $options = array(), $route = null, $reset = true, $encode = true, array $get = array())
{
$target = '';
if (isset($options['#target']))
{
$target = '#'.str_replace('#', '', $options['#target']);
unset($options['#target']);
}
$justice_friends = self::getRouter();
return $justice_friends->assemble($options, $route, $reset, $encode).self::arrayToGetString($get).$target;
}
/**
* @return \Zend_Controller_Router_Interface|\Zend_Controller_Router_Rewrite
* @throws \Zend_Controller_Exception
* @throws \Zend_Exception
*/
public static function getRouter()
{
static $router;
if (!$router)
{
$front = \Zend_Controller_Front::getInstance();
$request = $front->getRequest();
if (!$request)
{
$request = new \Zend_Controller_Request_Http;
$front->setRequest($request);
}
$config = \Zend_Registry::get('config');
if ($config->application->base_url)
$request->setBaseUrl($config->application->base_url);
$router = $front->getRouter();
if (!$router)
{
$router = new \Zend_Controller_Router_Rewrite;
$front->setRouter($router);
}
$router->addDefaultRoutes();
}
return $router;
}
// Route to a URL without resetting the current routing path.
public static function routeFromHere($options = array())
{
$options = (is_array($options)) ? $options : array('action' => $options);
return self::route($options, NULL, FALSE);
}
protected static function arrayToGetString(array $get, $preserve_existing_get = false)
{
$get_string = array();
if($preserve_existing_get === true)
{
foreach( (array)$_GET as $key => $value )
{
$get_string[$key] = urlencode($key) . '=' . urlencode($value);
}
}
foreach( (array)$get as $key => $value )
{
$get_string[$key] = urlencode($key) . '=' . urlencode($value);
}
if(count($get_string) > 0)
$get_string = '?' . implode('&', $get_string);
else
$get_string = '';
return $get_string;
}
<?php
namespace DF;
class Url
{
static $base_url;
/**
* Returns the baseUrl
*
* @throws \Zend_Exception
* @return string
*/
public static function baseUrl()
{
if (self::$base_url !== NULL)
{
return self::$base_url;
}
else
{
$config = \Zend_Registry::get('config');
if ($config->application->base_url)
{
$base_url = $config->application->base_url;
if (DF_IS_SECURE)
$base_url = str_replace('http://', 'https://', $base_url);
return $base_url;
}
else
{
$base_url = \Zend_Controller_Front::getInstance()->getBaseUrl();
return self::domain(TRUE) . $base_url;
}
}
}
public static function setBaseUrl($new_base_url)
{
self::$base_url = $new_base_url;
$router = self::getRouter();
$front = $router->getFrontController();
$front->setBaseUrl($new_base_url);
}
// Conversion from '//' scheme-independent URL to scheme-explicit URLs
static $original_base_url;
public static function forceSchemePrefix()
{
if (!empty(self::$original_base_url))
return null;
self::$original_base_url = self::baseUrl();
$new_base_url = self::addSchemePrefix(self::$original_base_url);
self::setBaseUrl($new_base_url);
}
public static function restoreNonPrefixed()
{
self::setBaseUrl(self::$original_base_url);
self::$original_base_url = null;
}
public static function addSchemePrefix($url)
{
if (substr($url, 0, 2) == '//')
return 'http'.((DF_IS_SECURE) ? 's:' : ':').$url;
return $url;
}
// Return path to static content.
public static function content($file_name = NULL)
{
if (defined('DF_URL_STATIC'))
$static_url_base = DF_URL_STATIC;
else
$static_url_base = self::baseUrl().'/static';
if ($file_name !== NULL)
return $static_url_base.'/'.$file_name;
else
return $static_url_base;
}
// Return path to uploaded file.
public static function file($file_name = NULL)
{
if (defined('DF_UPLOAD_URL'))
{
$static_url_base = self::baseUrl().DF_UPLOAD_URL;
if ($file_name !== NULL)
return $static_url_base.'/'.$file_name;
else
return $static_url_base;
}
else
{
return self::content($file_name);
}
}
public static function cdn($library_name, $library_version)
{
$cdn_base = '//ajax.googleapis.com/ajax/libs';
switch($library_name)
{
case 'jquery':
return $cdn_base.'/jquery/'.$library_version.'/jquery.min.js';
break;
case 'jqueryui':
return $cdn_base.'/jqueryui/'.$library_version.'/jquery-ui.min.js';
break;
}
}
public static function domain($includeScheme = false)
{
if (!empty($_SERVER['HTTP_HOST']))
{
$domain = $_SERVER['HTTP_HOST'];
if ($includeScheme)
$domain = 'http' . ((DF_IS_SECURE) ? 's' : '') . '://' . $domain;
return $domain;
}
return '';
}
/**
* Returns the referring URL, or, if no referring url, return the default
* url set (by default "false").
*
* @param string $default
* @return string
*/
public static function referrer($default = false)
{
if( isset($_SERVER['HTTP_REFERER']) )
return $_SERVER['HTTP_REFERER'];
else
return $default;
}
public static function current($includeSchemeDomain = TRUE, $include_request_uri = TRUE)
{
$prefix = '';
if($includeSchemeDomain)
{
$prefix = 'http' . (DF_IS_SECURE ? 's' : '') . '://' . $_SERVER['HTTP_HOST'];
}
$uri = '';
if (isset($_SERVER['REQUEST_URI']))
{
$uri = $_SERVER['REQUEST_URI'];
}
else
{
$uri = self::route($request->getParams()).self::arrayToGetString($_GET);
}
if (!$include_request_uri && strstr($uri, '?') !== FALSE)
{
$uri = substr($uri, 0, strpos($uri, '?'));
}
return $prefix.$uri;
}
/**
* Generate a URL based on a route
*
* @param array $options variables to pass to the router
* @param string $route which route to process
* @param boolean $reset reset automatic variable assignment
* @param boolean $encode url_encode() all pieces of the url
* @param array $get array of values for a ?get=string to be appended to the URL
* @return string Generated URL
*/
public static function route(array $options = array(), $route = null, $reset = true, $encode = true, array $get = array())
{
$target = '';
if (isset($options['#target']))
{
$target = '#'.str_replace('#', '', $options['#target']);
unset($options['#target']);
}
$justice_friends = self::getRouter();
return $justice_friends->assemble($options, $route, $reset, $encode).self::arrayToGetString($get).$target;
}
/**
* @return \Zend_Controller_Router_Interface|\Zend_Controller_Router_Rewrite
* @throws \Zend_Controller_Exception
* @throws \Zend_Exception
*/
public static function getRouter()
{
static $router;
if (!$router)
{
$front = \Zend_Controller_Front::getInstance();
$request = $front->getRequest();
if (!$request)
{
$request = new \Zend_Controller_Request_Http;
$front->setRequest($request);
}
$config = \Zend_Registry::get('config');
if ($config->application->base_url)
$request->setBaseUrl($config->application->base_url);
$router = $front->getRouter();
if (!$router)
{
$router = new \Zend_Controller_Router_Rewrite;
$front->setRouter($router);
}
$router->addDefaultRoutes();
}
return $router;
}
// Route to a URL without resetting the current routing path.
public static function routeFromHere($options = array())
{
$options = (is_array($options)) ? $options : array('action' => $options);
return self::route($options, NULL, FALSE);
}
protected static function arrayToGetString(array $get, $preserve_existing_get = false)
{
$get_string = array();
if($preserve_existing_get === true)
{
foreach( (array)$_GET as $key => $value )
{
$get_string[$key] = urlencode($key) . '=' . urlencode($value);
}
}
foreach( (array)$get as $key => $value )
{
$get_string[$key] = urlencode($key) . '=' . urlencode($value);
}
if(count($get_string) > 0)
$get_string = '?' . implode('&', $get_string);
else
$get_string = '';
return $get_string;
}
}

View File

@ -1,288 +1,288 @@
<?php
/**
* Miscellaneous Utilities Class
**/
namespace DF;
class Utilities
{
public static function getNewsFeed($feed_url, $cache_name = NULL, $cache_expires = 900)
{
if (!is_null($cache_name))
{
$feed_cache = \DF\Cache::get('feed_'.$cache_name);
}
if (!$feed_cache)
{
// Catch the occasional error when the RSS feed is malformed or the HTTP request times out.
try
{
$http_client = \Zend_Feed::getHttpClient();
$http_client->setConfig(array('timeout' => 60));
$news_feed = new \Zend_Feed_Rss($feed_url);
}
catch(Exception $e)
{
$news_feed = NULL;
}
if (!is_null($news_feed))
{
$latest_news = array();
$article_num = 0;
foreach ($news_feed as $item)
{
$article_num++;
// Process categories.
$categories_raw = (is_array($item->category)) ? $item->category : array($item->category);
$categories = array();
foreach($categories_raw as $category)
{
$categories[] = $category->__toString();
}
// Process main description.
$description = trim($item->description()); // Remove extraneous tags.
// $description = preg_replace('/[^(\x20-\x7F)]+/',' ', $description); // Strip "exotic" non-ASCII characters.
// $description = preg_replace('/<a[^(>)]+>read more<\/a>/i', '', $description); // Remove "read more" link.
$news_item = array(
'num' => $article_num,
'title' => $item->title(),
'timestamp' => strtotime($item->pubDate()),
'description' => $description,
'link' => $item->link(),
'categories' => $categories,
);
$latest_news[] = $news_item;
}
$latest_news = array_slice($latest_news, 0, 10);
if (!is_null($cache_name))
{
\DF\Cache::set($latest_news, 'feed_'.$cache_name, array('feeds', $cache_name));
}
}
}
else
{
$latest_news = $feed_cache;
}
return $latest_news;
}
/**
* Random Image
*/
public static function randomImage($static_dir)
{
$img = null;
$folder = DF_INCLUDE_STATIC.DIRECTORY_SEPARATOR.$static_dir;
$extList = array(
'gif' => 'image/gif',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
);
$handle = opendir($folder);
while ($file = readdir($handle))
{
$file_info = pathinfo($file);
$file_ext = strtolower($file_info['extension']);
if (isset($extList[$file_ext]))
$fileList[] = $file;
}
closedir($handle);
if (count($fileList) > 0)
{
$imageNumber = time() % count($fileList);
$img = $fileList[$imageNumber];
}
return \DF\Url::content($static_dir.'/'.$img);
}
/**
* Password Generation
*/
const PASSWORD_LENGTH = 9;
// Replacement for print_r.
public static function print_r($var, $return = FALSE)
{
$return_value = '<pre style="font-size: 13px; font-family: Consolas, Courier New, Courier, monospace; color: #000; background: #EFEFEF; border: 1px solid #CCC; padding: 5px;">';
$return_value .= print_r($var, TRUE);
$return_value .= '</pre>';
if ($return)
{
return $return_value;
}
else
{
echo $return_value;
}
}
/**
* Number handling
*/
public static function ceiling($value, $precision = 0) {
return ceil($value * pow(10, $precision)) / pow(10, $precision);
}
public static function floor($value, $precision = 0) {
return floor($value * pow(10, $precision)) / pow(10, $precision);
}
public static function money_format($number)
{
if ($number < 0)
return '-$'.number_format(abs($number), 2);
else
return '$'.number_format($number, 2);
}
public static function getFiscalYear($timestamp = NULL)
{
if ($timestamp === NULL)
$timestamp = time();
$fiscal_year = intval(date('Y', $timestamp));
$fiscal_month = intval(date('m', $timestamp));
if ($fiscal_month >= 9)
$fiscal_year++;
return $fiscal_year;
}
/**
* Security
*/
public static function generatePassword($char_length = self::PASSWORD_LENGTH)
{
// String of all possible characters. Avoids using certain letters and numbers that closely resemble others.
$numeric_chars = str_split('234679');
$uppercase_chars = str_split('ACDEFGHJKLMNPQRTWXYZ');
$lowercase_chars = str_split('acdefghjkmnpqrtwxyz');
$chars = array($numeric_chars, $uppercase_chars, $lowercase_chars);
$password = '';
for($i = 1; $i <= $char_length; $i++)
{
$char_array = $chars[$i % 3];
$password .= $char_array[mt_rand(0, count($char_array)-1)];
}
return str_shuffle($password);
}
// Get the plain-english value of a given timestamp.
public static function timeToText($timestamp)
{
return self::timeDifferenceText(0, $timestamp);
}
// Get the plain-english difference between two timestamps.
public static function timeDifferenceText($timestamp1, $timestamp2, $precision = 1)
{
$time_diff = abs($timestamp1 - $timestamp2);
$diff_text = "";
if ($time_diff < 60)
{
$time_num = intval($time_diff);
$time_unit = 'second';
}
else if ($time_diff >= 60 && $time_diff < 3600)
{
$time_num = round($time_diff / 60, $precision);
$time_unit = 'minute';
}
else if ($time_diff >= 3600 && $time_diff < 216000)
{
$time_num = round($time_diff / 3600, $precision);
$time_unit = 'hour';
}
else if ($time_diff >= 216000 && $time_diff < 10368000)
{
$time_num = round($time_diff / 86400);
$time_unit = 'day';
}
else
{
$time_num = round($time_diff / 2592000);
$time_unit = 'month';
}
$diff_text = $time_num.' '.$time_unit.(($time_num != 1)?'s':'');
return $diff_text;
}
/**
* Truncate text (adding "..." if needed)
*/
public static function truncateText($text, $limit = 80, $pad = '...')
{
if (strlen($text) <= $limit)
{
return $text;
}
else
{
$wrapped_text = wordwrap($text, $limit, "{N}", TRUE);
$shortened_text = substr($wrapped_text, 0, strpos($wrapped_text, "{N}"));
// Prevent the padding string from bumping up against punctuation.
$punctuation = array('.',',',';','?','!');
if (in_array(substr($shortened_text, -1), $punctuation))
{
$shortened_text = substr($shortened_text, 0, -1);
}
return $shortened_text.$pad;
}
}
public static function truncateUrl($url, $length=40)
{
$url = str_replace(array('http://', 'https://', 'www.'), array('', '', ''), $url);
return self::truncateText(rtrim($url, '/'), $length);
}
/**
* Array Combiner (useful for configuration files)
*/
public static function pairs($array)
{
return array_combine($array, $array);
}
public static function columns($array, $num_cols = 2, $preserve_keys = true)
{
$items_total = (int)count($array);
$items_per_col = ceil($items_total / $num_cols);
return array_chunk($array, $items_per_col, $preserve_keys);
}
public static function rows($array, $num_per_row = 3, $preserve_keys = true)
{
return array_chunk($array, $num_per_row, $preserve_keys);
}
}
<?php
/**
* Miscellaneous Utilities Class
**/
namespace DF;
class Utilities
{
public static function getNewsFeed($feed_url, $cache_name = NULL, $cache_expires = 900)
{
if (!is_null($cache_name))
{
$feed_cache = \DF\Cache::get('feed_'.$cache_name);
}
if (!$feed_cache)
{
// Catch the occasional error when the RSS feed is malformed or the HTTP request times out.
try
{
$http_client = \Zend_Feed::getHttpClient();
$http_client->setConfig(array('timeout' => 60));
$news_feed = new \Zend_Feed_Rss($feed_url);
}
catch(Exception $e)
{
$news_feed = NULL;
}
if (!is_null($news_feed))
{
$latest_news = array();
$article_num = 0;
foreach ($news_feed as $item)
{
$article_num++;
// Process categories.
$categories_raw = (is_array($item->category)) ? $item->category : array($item->category);
$categories = array();
foreach($categories_raw as $category)
{
$categories[] = $category->__toString();
}
// Process main description.
$description = trim($item->description()); // Remove extraneous tags.
// $description = preg_replace('/[^(\x20-\x7F)]+/',' ', $description); // Strip "exotic" non-ASCII characters.
// $description = preg_replace('/<a[^(>)]+>read more<\/a>/i', '', $description); // Remove "read more" link.
$news_item = array(
'num' => $article_num,
'title' => $item->title(),
'timestamp' => strtotime($item->pubDate()),
'description' => $description,
'link' => $item->link(),
'categories' => $categories,
);
$latest_news[] = $news_item;
}
$latest_news = array_slice($latest_news, 0, 10);
if (!is_null($cache_name))
{
\DF\Cache::set($latest_news, 'feed_'.$cache_name, array('feeds', $cache_name));
}
}
}
else
{
$latest_news = $feed_cache;
}
return $latest_news;
}
/**
* Random Image
*/
public static function randomImage($static_dir)
{
$img = null;
$folder = DF_INCLUDE_STATIC.DIRECTORY_SEPARATOR.$static_dir;
$extList = array(
'gif' => 'image/gif',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
);
$handle = opendir($folder);
while ($file = readdir($handle))
{
$file_info = pathinfo($file);
$file_ext = strtolower($file_info['extension']);
if (isset($extList[$file_ext]))
$fileList[] = $file;
}
closedir($handle);
if (count($fileList) > 0)
{
$imageNumber = time() % count($fileList);
$img = $fileList[$imageNumber];
}
return \DF\Url::content($static_dir.'/'.$img);
}
/**
* Password Generation
*/
const PASSWORD_LENGTH = 9;
// Replacement for print_r.
public static function print_r($var, $return = FALSE)
{
$return_value = '<pre style="font-size: 13px; font-family: Consolas, Courier New, Courier, monospace; color: #000; background: #EFEFEF; border: 1px solid #CCC; padding: 5px;">';
$return_value .= print_r($var, TRUE);
$return_value .= '</pre>';
if ($return)
{
return $return_value;
}
else
{
echo $return_value;
}
}
/**
* Number handling
*/
public static function ceiling($value, $precision = 0) {
return ceil($value * pow(10, $precision)) / pow(10, $precision);
}
public static function floor($value, $precision = 0) {
return floor($value * pow(10, $precision)) / pow(10, $precision);
}
public static function money_format($number)
{
if ($number < 0)
return '-$'.number_format(abs($number), 2);
else
return '$'.number_format($number, 2);
}
public static function getFiscalYear($timestamp = NULL)
{
if ($timestamp === NULL)
$timestamp = time();
$fiscal_year = intval(date('Y', $timestamp));
$fiscal_month = intval(date('m', $timestamp));
if ($fiscal_month >= 9)
$fiscal_year++;
return $fiscal_year;
}
/**
* Security
*/
public static function generatePassword($char_length = self::PASSWORD_LENGTH)
{
// String of all possible characters. Avoids using certain letters and numbers that closely resemble others.
$numeric_chars = str_split('234679');
$uppercase_chars = str_split('ACDEFGHJKLMNPQRTWXYZ');
$lowercase_chars = str_split('acdefghjkmnpqrtwxyz');
$chars = array($numeric_chars, $uppercase_chars, $lowercase_chars);
$password = '';
for($i = 1; $i <= $char_length; $i++)
{
$char_array = $chars[$i % 3];
$password .= $char_array[mt_rand(0, count($char_array)-1)];
}
return str_shuffle($password);
}
// Get the plain-english value of a given timestamp.
public static function timeToText($timestamp)
{
return self::timeDifferenceText(0, $timestamp);
}
// Get the plain-english difference between two timestamps.
public static function timeDifferenceText($timestamp1, $timestamp2, $precision = 1)
{
$time_diff = abs($timestamp1 - $timestamp2);
$diff_text = "";
if ($time_diff < 60)
{
$time_num = intval($time_diff);
$time_unit = 'second';
}
else if ($time_diff >= 60 && $time_diff < 3600)
{
$time_num = round($time_diff / 60, $precision);
$time_unit = 'minute';
}
else if ($time_diff >= 3600 && $time_diff < 216000)
{
$time_num = round($time_diff / 3600, $precision);
$time_unit = 'hour';
}
else if ($time_diff >= 216000 && $time_diff < 10368000)
{
$time_num = round($time_diff / 86400);
$time_unit = 'day';
}
else
{
$time_num = round($time_diff / 2592000);
$time_unit = 'month';
}
$diff_text = $time_num.' '.$time_unit.(($time_num != 1)?'s':'');
return $diff_text;
}
/**
* Truncate text (adding "..." if needed)
*/
public static function truncateText($text, $limit = 80, $pad = '...')
{
if (strlen($text) <= $limit)
{
return $text;
}
else
{
$wrapped_text = wordwrap($text, $limit, "{N}", TRUE);
$shortened_text = substr($wrapped_text, 0, strpos($wrapped_text, "{N}"));
// Prevent the padding string from bumping up against punctuation.
$punctuation = array('.',',',';','?','!');
if (in_array(substr($shortened_text, -1), $punctuation))
{
$shortened_text = substr($shortened_text, 0, -1);
}
return $shortened_text.$pad;
}
}
public static function truncateUrl($url, $length=40)
{
$url = str_replace(array('http://', 'https://', 'www.'), array('', '', ''), $url);
return self::truncateText(rtrim($url, '/'), $length);
}
/**
* Array Combiner (useful for configuration files)
*/
public static function pairs($array)
{
return array_combine($array, $array);
}
public static function columns($array, $num_cols = 2, $preserve_keys = true)
{
$items_total = (int)count($array);
$items_per_col = ceil($items_total / $num_cols);
return array_chunk($array, $items_per_col, $preserve_keys);
}
public static function rows($array, $num_per_row = 3, $preserve_keys = true)
{
return array_chunk($array, $num_per_row, $preserve_keys);
}
}

Some files were not shown because too many files have changed in this diff Show More