Initial commit.

This commit is contained in:
Buster Neece 2014-02-21 03:25:10 -06:00
commit ce7216ea0b
8857 changed files with 1512491 additions and 0 deletions

12
.hgignore Normal file
View File

@ -0,0 +1,12 @@
syntax: glob
*Thumbs.db
tmp/cache/*---*
app/models/Proxy/*.php
web/static/api/*
*.DS_Store
*.apdisk
*.zip
<<<<<<< local
*.mp3
=======
>>>>>>> other

25
.htaccess Normal file
View File

@ -0,0 +1,25 @@
RewriteEngine on
Options -Indexes
Options +FollowSymLinks
DirectoryIndex index.php
# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
php_value magic_quotes_gpc 0
php_value register_globals 0
php_value session.auto_start 0
php_value short_open_tag 1
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
# Forward all requests that are not existing files to index.php
RewriteCond %{REQUEST_FILENAME} !-f
# RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php [L,QSA]
</IfModule>

1
app/.env Executable file
View File

@ -0,0 +1 @@
production

1
app/.updated Executable file
View File

@ -0,0 +1 @@
1356653191

106
app/bootstrap.php Normal file
View File

@ -0,0 +1,106 @@
<?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_BASE.'/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_BASE.'/library');
define("DF_INCLUDE_LIB_LOCAL", DF_INCLUDE_BASE.'/library_local');
define("DF_UPLOAD_FOLDER", DF_INCLUDE_STATIC);
define("DF_URL_STATIC", (DF_IS_SECURE ? 'https:' : 'http:').'//static.ponyvillelive.com');
// Self-reference to current script.
if (isset($_SERVER['REQUEST_URI']))
define("DF_THIS_PAGE", reset(explode("?", $_SERVER['REQUEST_URI'])));
else
define("DF_THIS_PAGE", '');
define("DF_TIME", time());
// 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.
error_reporting(E_ALL & ~E_NOTICE);
// Set include path (as needed by CLI access.)
$include_path = array(DF_INCLUDE_LIB, get_include_path());
// 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 != '..')
{
$config_directory = DF_INCLUDE_MODULES.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.'config';
if (file_exists($config_directory))
{
$module_config_dirs[$module] = $config_directory;
}
$library_directory = DF_INCLUDE_MODULES.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.'library';
if (file_exists($library_directory))
{
$include_path[] = $library_directory;
}
}
}
// Set include paths.
set_include_path(implode(PATH_SEPARATOR, $include_path));
// Save configuration object.
require('DF/Config.php');
$config = new DF\Config(DF_INCLUDE_APP.'/config');
$config->preload(array('application','general'));
$module_config = array();
if ($module_config_dirs)
{
foreach($module_config_dirs as $module_name => $config_dir)
{
$module_config[$module_name] = new \DF\Config($config_dir);
}
}
require('DF/Loader.php');
DF\Loader::register($config->application->autoload);
// Initialize the ZendFramework Application Bootstrapper.
require('Zend/Application.php');
$application = new Zend_Application('application', $config->application);
$application->getBootstrap();
$application->bootstrap('doctrine');
// Save the configuration object to the global registry.
Zend_Registry::set('application', $application);
Zend_Registry::set('config', $config);
Zend_Registry::set('module_config', $module_config);
Zend_Registry::set('cache', new DF\Cache);
Zend_Registry::set('auth', new DF\Auth\Model);
Zend_Registry::set('acl', new DF\Acl\Instance);
// PVL-specific customization.
$system_tz = \PVL\Customization::get('timezone');
@date_default_timezone_set($system_tz);

165
app/common/footer.phtml Normal file
View File

@ -0,0 +1,165 @@
<?
$affiliates = array(
array(
'name' => 'Ponyhoof',
'url' => 'http://ponyhoof.little.my',
'description' => 'Ponify Facebook and make it 20% cooler!',
'image' => \DF\Url::content('affiliates/ponyhoof.png'),
),
array(
'name' => 'Journey of the Spark',
'url' => 'http://fimsparkmovie.tumblr.com/',
'description' => 'A Full Length Fan-Created Movie',
'image' => \DF\Url::content('affiliates/jots.png'),
),
array(
'name' => 'PonyMC',
'description' => 'A Ponyville Live! Minecraft Partner',
'url' => 'http://ponymc.com/',
'image' => \DF\Url::content('affiliates/ponymc.png'),
),
array(
'name' => 'Legends of Equestria',
'url' => 'http://legendsofequestria.com/',
'description' => 'A Pony-Themed MMORPG',
'image' => \DF\Url::content('affiliates/loe.png'),
),
array(
'name' => 'PonySquare/BronySquare',
'url' => 'http://www.ponysquare.com/',
'custom' => '<a href="http://www.ponysquare.com/" target="_blank">PonySquare</a> &amp; <a href="http://www.bronysquare.com/" target="_blank">BronySquare</a>',
'description' => 'Pony-Driven Social Networks',
'image' => \DF\Url::content('affiliates/squared.png'),
),
array(
'name' => 'Brony Aerospace',
'url' => 'http://bronyaerospace.net/',
'description' => 'Launching Rockets Pony-Style!',
'image' => \DF\Url::content('affiliates/aerospace.png'),
),
array(
'name' => 'Brony@Home',
'url' => 'http://bronyathome.org/',
'description' => 'Distributed Computing for the Greater Good',
'image' => \DF\Url::content('affiliates/bronyathome.png'),
),
array(
'name' => 'Derpy Hooves News',
'url' => 'http://www.derpyhoovesnews.com/',
'description' => 'Aderpable Pony News Site',
'image' => \DF\Url::content('affiliates/dhn.png'),
),
array(
'name' => 'Bronies For Good',
'url' => 'http://broniesforgood.org/',
'description' => 'Promoting Brony Kindness and Philanthropy',
'image' => \DF\Url::content('affiliates/bfg.png'),
),
array(
'name' => 'Brony Musician Directory',
'url' => 'http://bronymusic.com/',
'description' => 'Profiles and Biographies of Pony Musicians',
'image' => \DF\Url::content('affiliates/bmd.png'),
),
/*
array(
'name' => 'MTMS Gaming',
'url' => 'http://steamcommunity.com/groups/MaximumServers',
'description' => 'Home of TF2 Servers and L4D Servers',
'image' => \DF\Url::content('affiliates/mtms.png'),
),
*/
array(
'name' => 'Las Pegasus Gaming',
'url' => 'http://laspegasus.net/',
'description' => 'A Community Brony Gaming Site',
'image' => \DF\Url::content('affiliates/lpp.png'),
),
);
shuffle($affiliates);
$num_affiliates = count($affiliates);
$col1_length = ceil($num_affiliates / 2);
$col1 = array_splice($affiliates, 0, $col1_length);
$cols = array($col1, $affiliates);
?>
<div class="footer-inner">
<div class="row-fluid">
<div class="span8">
<div class="headline"><h3>Friends &amp; Affiliates</h3></div>
<div class="row-fluid">
<? foreach($cols as $column): ?>
<div class="span6">
<ul class="media-list">
<? foreach($column as $affiliate): ?>
<li class="media">
<div class="media-object pull-left">
<a href="<?=$affiliate['url'] ?>" target="_blank">
<img src="<?=$affiliate['image'] ?>" style="width: 40px;">
</a>
</div>
<div class="media-body">
<h4>
<? if ($affiliate['custom']): ?>
<?=$affiliate['custom'] ?><br>
<? else: ?>
<a href="<?=$affiliate['url'] ?>" target="_blank"><?=$affiliate['name'] ?></a><br>
<? endif; ?>
<small><?=$affiliate['description'] ?></small>
</h4>
</div>
</li>
<? endforeach; ?>
</ul>
</div>
<? endforeach; ?>
</div>
</div>
<div class="span4">
<div class="headline"><h3>Support PVL</h3></div>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="ATKJ53AWWRQP4">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
<br>
<ul class="unstyled">
<li><a href="http://www.zazzle.com/ponyvillelive" target="_blank"><i class="icon-money"></i> Swag Store</a></li>
</ul>
<div class="headline"><h3>Contact Us</h3></div>
<ul class="unstyled">
<li>Public Relations:<br><?=$this->mailto('pr@ponyvillelive.com') ?></li>
<li>Director:<br><?=$this->mailto('silvereagle@ponyvillelive.com') ?></li>
<li>Associate Director:<br><?=$this->mailto('weareborg@ponyvillelive.com') ?></li>
</ul>
<div class="headline"><h3>Stay Connected</h3></div>
<ul class="unstyled">
<li><a href="http://news.ponyvillelive.com/" target="_blank"><img src="<?=\DF\Url::content('social/tumblr_16.png') ?>" alt="Tumblr"> Tumblr</a></li>
<li><a href="http://steamcommunity.com/groups/ponyvillelive" target="_blank"><img src="<?=\DF\Url::content('social/steam_16.png') ?>" alt="Steam"> Steam</a></li>
<li><a href="https://www.facebook.com/pages/Ponyville-LIVE/517435684948331" target="_blank"><img src="<?=\DF\Url::content('social/facebook_16.png') ?>" alt="Facebook"> Facebook</a></li>
<li><a href="https://twitter.com/PonyvilleLive" target="_blank"><img src="<?=\DF\Url::content('social/twitter_16.png') ?>" alt="Twitter"> Twitter</a></li>
</ul>
</div>
</div>
</div>

45
app/common/nav.phtml Normal file
View File

@ -0,0 +1,45 @@
<?
$categories = \Entity\Station::getStationsInCategories();
$podcasts = \Entity\Podcast::fetchArray('name');
?>
<ul class="nav primary_menu">
<!-- About PVL -->
<li class="dropdown">
<a href="<?=$this->route(array('controller' => 'about')) ?>"><i class="icon-info-sign"></i> About</a>
<ul class="dropdown-menu">
<li><a href="<?=$this->route(array('controller' => 'about')) ?>"><i class="icon-info-sign"></i> About Ponyville Live!</a></li>
<li><a href="<?=$this->route(array('controller' => 'events')) ?>"><i class="icon-group"></i> Conventions</a></li>
<li><a href="<?=$this->route(array('controller' => 'events', 'action' => 'schedule')) ?>"><i class="icon-calendar"></i> Station Schedules</a></li>
</ul>
</li>
<!-- Stations -->
<li class="dropdown">
<a href="#" data-toggle="dropdown"><i class="icon-music"></i> Radio</a>
<ul class="dropdown-menu">
<? foreach($categories['audio']['stations'] as $station): ?>
<li><a href="<?=$station['web_url'] ?>" title="<?=$station['genre'] ?>" target="_blank"><?=$station['name'] ?></a></li>
<? endforeach; ?>
</ul>
</li>
<li class="dropdown">
<a href="#" data-toggle="dropdown"><i class="icon-facetime-video"></i> Video</a>
<ul class="dropdown-menu">
<? foreach($categories['video']['stations'] as $station): ?>
<li><a href="<?=$station['web_url'] ?>" title="<?=$station['genre'] ?>" target="_blank"><?=$station['name'] ?></a></li>
<? endforeach; ?>
</ul>
</li>
<li class="dropdown">
<a href="#" data-toggle="dropdown"><i class="icon-rss"></i> Shows</a>
<ul class="dropdown-menu">
<? foreach($podcasts as $podcast): ?>
<li><a href="<?=$podcast['web_url'] ?>" title="<?=$podcast['description'] ?>" target="_blank"><?=$podcast['name'] ?></a></li>
<? endforeach; ?>
</ul>
</li>
<li><a href="<?=$this->route(array('action' => 'index', 'mode' => 'chat')) ?>"><i class="icon-comment"></i> Chat</a></li>
</ul>

31
app/common/podcast.phtml Normal file
View File

@ -0,0 +1,31 @@
<ul class="media-list">
<? foreach($this->podcasts as $podcast_info): ?>
<?
$podcast = $podcast_info['record'];
$episodes = $podcast_info['episodes'];
$ep = $episodes[0];
?>
<li class="media podcast">
<div class="media-object pull-left">
<a href="<?=$this->routeFromHere(array('action' => 'podcast', 'id' => $podcast->id)) ?>" class="fancybox fancybox.ajax">
<img class="station-image" src="<?=\DF\Url::content($podcast->image_url) ?>" style="width: 40px;">
<div class="station-play-button">
<i class="icon-rss"></i>
</div>
</a>
</div>
<div class="media-body">
<div class="station-info">
<h4><?=$podcast->name ?><br>
<span class="genre-info"><small>
<?=$podcast->description ?>
</small></span>
</h4>
<small>Newest Episode (<?=date('F j, Y', $ep['timestamp']) ?>):</small><br>
<a href="<?=$ep['web_url'] ?>" target="_blank"><b><?=$ep['title'] ?></b></a>
</div>
</div>
</li>
<? endforeach; ?>
</ul>

237
app/common/radio.phtml Normal file
View File

@ -0,0 +1,237 @@
<?php
$stations = \Entity\Station::fetchArray();
?>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="brand" style="padding: 5px 5px 5px 25px" href="<?=\DF\Url::route() ?>"><img src="<?=\DF\Url::content('pvl_dark.png') ?>" alt="Ponyville Live!"></a>
<ul class="nav">
<? foreach($stations as $station): ?>
<li class="header_station"><a href="#" id="header_station_<?=\Entity\Station::getStationShortName($station['name']) ?>" data-id="<?=$station['id'] ?>" data-type="<?=$station['type'] ?>" data-stream="<?=$station['stream_url'] ?>">
<img src="<?=\DF\Url::content($station['image_url']) ?>" style="width: 35px; height: 35px; border: 1px solid #163D63;">
<span class="max-width-only" style="margin-left: 5px;">
<?=str_replace(' Radio', '', $station['name']) ?>
</span>
</a></li>
<? endforeach; ?>
</ul>
<ul class="nav pull-right">
<li id="nowplaying-area">
<a href="#" id="btn_radio" class="clearfix">
<img id="nowplaying-image" src="<?=\DF\Url::content('stations/generic.png') ?>" style="width: 35px; height: 35px; border: 1px solid #163D63; float: left;">
<div id="nowplaying-icon">
<i class="current-status icon-music"></i>
</div>
<div id="nowplaying-wrapper">
<div id="nowplaying-artist">Select a Station</div>
<div id="nowplaying-title">to Tune In Live</div>
</div>
</a>
</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript">
var soundObject;
var volume = 50;
var nowplaying_id;
var generic_image = '<?=\DF\Url::content('stations/generic.png') ?>';
$(function() {
soundManager.setup({
url: '<?=\DF\Url::content('soundmanager/swf/') ?>',
onready: function() {
// Check for previously playing song and play it.
var nowplaying_cookie = getCookie('nowplaying_id');
if (nowplaying_cookie)
playStation(nowplaying_cookie);
}
});
$('#btn-tunein').click(function(e) {
var href = $(this).attr('href');
window.open(href, "pvlplayer", "width=300,height=600,menubar=0,toolbar=0,location=0,status=1");
e.preventDefault();
return false;
});
$('.nowplaying-status').hide();
$('.header_station a').click(function(e) {
e.preventDefault();
playStation($(this).attr('id'));
});
$('.station').click(function(e) {
e.preventDefault();
playStation('header_'+$(this).attr('id'));
});
$('#btn_radio').click(function(e) {
e.preventDefault();
stopAllPlayers();
});
checkNowPlaying();
});
$(window).bind("unload", function(){
document.cookie = "nowplaying_id="+nowplaying_id+"; expires=cookie_date.getTime+300; path=/";
});
function playStation(id)
{
var station = $('#'+id);
var stream_type = station.data('type');
var stream_url = station.data('stream');
var stream_id = station.data('id');
var currently_playing = (id == nowplaying_id);
if (currently_playing)
{
stopAllPlayers();
}
else
{
if (stream_url && stream_type)
{
stopAllPlayers();
if (stream_type == "shoutcast2" || stream_type == "shoutcast1")
{
soundObject = soundManager.createSound({
id:'pvlradio',
url: stream_url
});
soundObject.play({'volume': volume});
/*
var image = station.find('img').attr('src');
$('#jwplayer_outer').show();
jwplayer('jwplayer').setup({
'image': station.find('img').attr('src'),
'file': stream_url,
'type': 'mp3',
'source': 'sound',
'primary': 'flash',
'autostart': 'true',
'width': '100%',
'height': '150'
}).setVolume(volume).onError(function() {
setTimeout(function() {
stopAllPlayers();
playStation(id);
}, 5000);
});
*/
}
else if (stream_type == "video")
{
}
$('#nowplaying-area').addClass('active');
$('#nowplaying-icon i').removeClass('icon-music icon-pause').addClass('icon-pause');
$('#nowplaying-title').text('Now Playing...');
$('#nowplaying-artist').text(station.find('span').text());
station.closest('li').addClass('active');
var station_image = station.find('img').attr('src');
$('#nowplaying-image').attr('src', station_image);
nowplaying_id = id;
}
else
{
$('#player').text('Error: This stream is not currently active. Please select another stream to continue.');
}
}
}
function checkNowPlaying()
{
jQuery.ajax({
url: '<?=\DF\Url::route(array('module' => 'default', 'controller' => 'index', 'action' => 'nowplaying', 'v' => '2')) ?>',
dataType: 'json'
}).done(function(data) {
for (var station_id in data)
{
var station_info = data[station_id];
var header_station = 'header_station_'+station_id;
var is_playing = (header_station == nowplaying_id);
var station = $('#station_'+station_id);
if (!station_info.title)
{
var nowplaying_artist = station_info.text;
var nowplaying_title = '';
}
else
{
var nowplaying_artist = station_info.title;
var nowplaying_title = station_info.artist;
}
station.find('.nowplaying-artist').text(nowplaying_artist);
station.find('.nowplaying-title').text(nowplaying_title);
if (is_playing)
{
$('#nowplaying-artist').text(nowplaying_artist);
$('#nowplaying-title').text(nowplaying_title);
}
if (station_info.listeners)
station.find('.nowplaying-listeners').text(station_info.listeners+' Tuned In');
else
station.find('.nowplaying-listeners').hide();
}
setTimeout('checkNowPlaying()', 10000);
});
}
function stopAllPlayers()
{
$('#nowplaying-area').removeClass('active');
$('#nowplaying-icon i').removeClass('icon-music icon-pause').addClass('icon-music');
$('#nowplaying-image').attr('src', generic_image);
$('#nowplaying-artist').text('Select a Station');
$('#nowplaying-title').text('to Tune In Live');
$('.header_station').removeClass('active');
nowplaying_id = null;
soundManager.destroySound('pvlradio');
/*
jwplayer('jwplayer').stop();
$('#jwplayer_outer').hide();
$('i.current-status').removeClass('icon-stop icon-play').addClass('icon-play');
$('.nowplaying-status').hide();
$('.station').removeClass('playing');
*/
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
</script>

148
app/common/station.phtml Normal file
View File

@ -0,0 +1,148 @@
<ul class="media-list" style="padding-bottom: 0; margin-bottom: 0;">
<? foreach((array)$this->stations as $station): ?>
<li class="media station" id="station_<?=\Entity\Station::getStationShortName($station['name']) ?>"
data-id="<?=$station['id'] ?>"
data-name="<?=$station['name'] ?>"
data-type="<?=$station['type'] ?>"
data-stream="<?=$station['stream_url'] ?>"
data-image="<?=\DF\Url::content($station['image_url']) ?>"
data-chat="<?=$station['irc'] ?>"
data-inactive="<? if ($station['hide_if_inactive']): ?>hide<? else: ?>show<? endif; ?>"
style="margin-top: 0;">
<div class="media-object pull-left center">
<img class="station-image" src="<?=\DF\Url::content($station['image_url']) ?>">
<div class="station-play-button">
<i class="icon-play"></i>
</div>
</div>
<div class="media-body">
<div class="station-info">
<? if ($this->render_mode != 'embed'): ?>
<!-- Station Like/Share Buttons -->
<div class="station-link buttons btn-toolbar pull-right" style="display: none;">
<div class="btn-group">
<? if ($this->auth->isLoggedIn()): ?>
<?=$this->button(array(
'type' => 'small',
'icon' => 'icon-thumbs-up',
'text' => 'Like',
'href' => $this->route(array('action' => 'like', 'origin' => 'pvl')),
'class' => 'btn-success btn-like',
)) ?>
<? else: ?>
<?=$this->button(array(
'type' => 'small',
'icon' => 'icon-thumbs-up',
'text' => 'Like',
'href' => '#',
'class' => 'btn-success btn-like-login-required',
)) ?>
<? endif; ?>
<?=$this->button(array(
'type' => 'small',
'icon' => 'icon-facebook',
'title' => 'Share on Facebook',
'href' => '#',
'class' => 'btn-icon-only btn-primary btn-share-station btn-share-facebook',
)) ?>
<?=$this->button(array(
'type' => 'small',
'icon' => 'icon-twitter',
'title' => 'Share on Twitter',
'href' => '#',
'class' => 'btn-icon-only btn-primary btn-share-station btn-share-twitter',
)) ?>
</div>
</div>
<? endif; ?>
<!-- Station Header -->
<h4>
<? if ($station['nickname']): ?>
<?=$station['nickname'] ?>
<? else: ?>
<?=$station['name'] ?>
<? endif; ?>
<span class="nowplaying-info">
<small>
<span class="nowplaying-live">Live! &bull; </span>
<span class="nowplaying-listeners"></span>
<span class="nowplaying-status"> &bull; Now Playing</span>
</small>
</span>
<? if ($station['genre']): ?>
<span class="genre-info">
<small>
<?=$station['genre'] ?>
</small>
</span>
<? endif; ?>
</h4>
<? if ($station['now']): ?>
<div class="nowplaying-onair">
<i class="icon-star"></i> On Air: <?=$station['now']['title'] ?>
</div>
<? else: ?>
<div class="nowplaying-onair" style="display: none;"></div>
<? endif; ?>
<!-- Now Playing Information -->
<div><big><span class="nowplaying-artist">Loading...</span></big></div>
<div><span class="nowplaying-title">Loading...</span></div>
</div>
<div class="station-player" style="display: none;">
<div class="station-player-container"></div>
<!-- Station Links -->
<div class="station-link buttons btn-toolbar">
<? if ($station['requests_enabled']): ?>
<div class="btn-group">
<?=$this->button(array(
'type' => 'small',
'icon' => 'icon-music',
'text' => 'Request',
'title' => 'Request a song to play on this station!',
'href' => $this->route(array('controller' => 'station', 'action' => 'request', 'id' => $station['id'])),
'class' => 'btn-inverse',
'target' => '_blank',
)) ?>
</div>
<? endif; ?>
<div class="btn-group">
<? if ($this->render_mode != 'embed'): ?>
<?=$this->button(array(
'type' => 'small',
'icon' => 'icon-time',
'text' => 'Recent',
'title' => 'Show recently played songs.',
'href' => '#',
'class' => 'btn-show-history',
)) ?>
<?=$this->button(array(
'type' => 'small',
'icon' => 'icon-globe',
'text' => 'Site',
'title' => 'View the station\'s web site.',
'href' => $station['web_url'],
'target' => '_blank',
)) ?>
<? endif; ?>
<?=$this->button(array(
'type' => 'small',
'icon' => 'icon-download',
'text' => 'PLS',
'title' => 'Download a PLS playlist to play this station in a media player.',
'href' => $this->route(array('controller' => 'station', 'action' => 'playlist', 'format' => 'pls', 'id' => $station['id'])),
)) ?>
</div>
</div>
<div class="station-history"></div>
</div>
</div>
</li>
<? endforeach; ?>
</ul>

View File

@ -0,0 +1,147 @@
<?php
/**
* Application Settings
*/
$session_lifetime = 86400*0.5;
$config = array(
// Application name
'name' => 'Ponyville Live!',
'analytics_code' => 'UA-37359273-1',
// Primary application web address
'base_url' => (DF_IS_SECURE ? 'https' : 'http').'://'.($_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!',
// 'bounce_addr' => 'noreply@ponyvillelive.com',
// 'error_addr' => 'noreply@ponyvillelive.com',
'use_smtp' => true,
'smtp' => array(
'server' => 'smtp.mandrillapp.com',
'port' => '587',
'auth' => 'login',
'username' => 'loobalightdark@gmail.com',
'password' => 'd05MxdhMxGxq7i8HRh8_mg',
),
),
'phpSettings' => array(
'display_startup_errors' => 0,
'display_errors' => 0,
'error_reporting' => E_ALL & ~E_NOTICE & ~E_WARNING,
'session' => array(
'save_path' => DF_INCLUDE_TEMP.DIRECTORY_SEPARATOR.'sessions',
'gc_maxlifetime' => $session_lifetime,
'cookie_lifetime' => $session_lifetime,
),
),
'bootstrap' => array(
'path' => 'DF/Application/Bootstrap.php',
'class' => '\DF\Application\Bootstrap',
),
'includePaths' => array(
DF_INCLUDE_LIB,
DF_INCLUDE_LIB.'/Doctrine',
),
'pluginpaths' => array(
'DF\Application\Resource\\' => 'DF/Application/Resource',
),
'autoload' => array(
'Zend_' => DF_INCLUDE_LIB,
'Hybrid_' => DF_INCLUDE_LIB.'/ThirdParty',
'DF' => DF_INCLUDE_LIB,
'Doctrine' => DF_INCLUDE_LIB,
'Symfony' => DF_INCLUDE_LIB.'/Doctrine',
'PVL' => DF_INCLUDE_LIB_LOCAL,
),
'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_MODELS.'/Proxy',
'modelPath' => DF_INCLUDE_MODELS,
'conn' => array(
'driver' => 'pdo_mysql',
'host' => 'localhost',
'dbname' => 'pvladmin_app',
'user' => 'pvladmin_app',
'password' => 'PvlWebDatabase2013!',
),
),
/* RESOURCES: Menu */
'menu' => array(
'enabled' => true,
),
/* RESOURCES: Layout */
'layout' => array(
'layout' => 'default',
'layoutPath' => DF_INCLUDE_APP.'/layouts',
'commonTemplates' => DF_INCLUDE_BASE.'/common',
),
/* RESOURCES: Session */
'session' => array(
'use_only_cookies' => true,
'remember_me_seconds' => $session_lifetime,
),
),
);
/**
* Doctrine autoloading.
*/
$config['autoload']['Entity'] = $config['resources']['doctrine']['modelPath'];
$config['autoload']['Proxy'] = $config['resources']['doctrine']['modelPath'];
/**
* Development mode changes.
*/
if (DF_APPLICATION_ENV != 'production')
{
$config['phpSettings']['display_startup_errors'] = 1;
$config['phpSettings']['display_errors'] = 1;
$config['phpSettings']['error_reporting'] = E_ALL & ~E_STRICT & ~E_NOTICE;
unset($config['base_url']);
$config['resources']['doctrine']['conn'] = array(
'driver' => 'pdo_mysql',
'host' => 'localhost',
'dbname' => 'pvl',
'user' => 'pvl',
'password' => '7AchaZAz',
);
}
return $config;

100
app/config/general.conf.php Executable file
View File

@ -0,0 +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',
),
);

10
app/config/pvl.conf.php Normal file
View File

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

View File

@ -0,0 +1,15 @@
<?php
/**
* CentovaCast Service Configuration
*/
return array(
// IP or hostname of the CentovaCast server.
'host' => '198.27.112.218',
'db_user' => 'centova',
'db_pass' => 'PVLRadio2013!',
'db_name' => 'centova',
);

View File

@ -0,0 +1,92 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
// ----------------------------------------------------------------------------------------
// HybridAuth Config file: http://hybridauth.sourceforge.net/userguide/Configuration.html
// ----------------------------------------------------------------------------------------
return array(
"base_url" => \DF\Url::baseUrl(TRUE),
"providers" => array (
// openid providers
"OpenID" => array (
"enabled" => true
),
/*
"Yahoo" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" ),
),
"AOL" => 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"
),
),
/*
// windows live
"Live" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" )
),
"MySpace" => array (
"enabled" => true,
"keys" => array ( "key" => "", "secret" => "" )
),
"LinkedIn" => array (
"enabled" => true,
"keys" => array ( "key" => "", "secret" => "" )
),
"Foursquare" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" )
),
*/
),
// if you want to enable logging, set 'debug_mode' to true then provide a writable file by the web server on "debug_file"
"debug_mode" => false,
"debug_file" => "",
);

View File

@ -0,0 +1,9 @@
<?php
/**
* ReCAPTCHA Configuration
*/
return array(
'public_key' => '6LfE7eASAAAAADg6R11mHJaFdiGKj_KNB55kB-A4',
'private_key' => '6LfE7eASAAAAAIH3Wn8LUhEUihib4uO2qDxg64n7',
);

View File

@ -0,0 +1,10 @@
<?php
return array(
'consumer_key' => 'dekLAskiLF8nrTZI3zmmg',
'consumer_secret' => 'J6OaNpKHlDmrQLEmvxfdlRWO4E7WbyNnBTdpz1njLcw',
'user_token' => '974916638-1jK4vgMYvv9pAc2gQfAYGcnDY58xTij5M42P93VU',
'user_secret' => 'TTDLFrhcULlU3a9uYxIbdW5DZxx4TsCfOlf9sWuVlY4',
'curl_ssl_verifyhost' => 0,
'curl_ssl_verifypeer' => false,
);

237
app/layouts/default.phtml Normal file
View File

@ -0,0 +1,237 @@
<?php
header("Content-type: text/html; charset=utf-8");
echo $this->doctype();
$skin = \PVL\Customization::get('theme');
?>
<html class="full_layout theme_<?=$skin ?>">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,requiresActiveX=true">
<meta name="viewport" content="initial-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
<meta name="keywords" content="Pony, Brony, Radio, Video, Podcast, Multimedia, Convention, Ponyville, Live, MLP, MLP:FiM" />
<meta name="description" content="Equestria's newest Brony multimedia network, featuring 24/7 pony radio, videos, podcasts, convention coverage, and more." />
<link rel="canonical" href="http://www.ponyvillelive.com" />
<!-- iPhone/iPhone Retina -->
<link rel="apple-touch-icon-precomposed" sizes="57x57" href="<?=\DF\Url::content('ios/touch_icon_iphone.png') ?>" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="<?=\DF\Url::content('ios/touch_icon_iphone.png') ?>" />
<!-- iPad/iPad Retina -->
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="<?=\DF\Url::content('ios/touch_icon_ipad.png') ?>" />
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="<?=\DF\Url::content('ios/touch_icon_ipad.png') ?>" />
<!-- Facebook and Other Social Sites -->
<link rel="image_src" href="<?=\DF\Url::content('pvl_square.png') ?>" />
<?php
$title_items = $this->headTitle()->getIterator();
$title = current($title_items);
if (!$this->layout()->subtitle && $this->layout()->show_subtitle)
$this->layout()->subtitle = next($title_items);
$this->headTitle($this->config->application->name);
if (count($title_items) == 1)
{
$this->headTitle()->append('Bringing Pony People Together');
$this->headTitle()->append('24/7 Pony Radio, Video, Podcasts, Convention Coverage & More');
}
if (DF_APPLICATION_ENV != "production")
$this->headTitle()->prepend('('.ucfirst(DF_APPLICATION_ENV).')');
echo $this->headTitle()->setSeparator(" - ")->toString();
$this->headLink()
->appendStylesheet('//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css', 'all')
->appendStylesheet('//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css', 'all')
->appendStylesheet(\DF\Url::content('common/jquery/fancybox/jquery.fancybox.css'), 'all')
->appendStylesheet(\DF\Url::content('common/bootstrap2_r2/df-ui-printable.css'), 'print')
->appendStylesheet('//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700', 'screen')
->appendStylesheet(\DF\Url::content('mid2013/style.css'), 'all')
->appendStylesheet(\DF\Url::content('mid2013/skin_'.$skin.'.css'));
$this->headScript()
->prependFile(\DF\Url::cdn('jquery', '1.8.3'))
->appendFile(\DF\Url::content('common/jquery/fancybox/jquery.fancybox.pack.js'))
->appendFile(\DF\Url::content('common/bootstrap2_r2/bootstrap/js/bootstrap.min.js'))
->appendFile(\DF\Url::content('common/bootstrap2_r2/layout.js'))
->appendFile(\DF\Url::content('swfobject.js'))
->appendFile(\DF\Url::content('global.js'));
echo $this->headMeta()."\n";
echo $this->headLink()."\n";
echo $this->headScript()."\n";
if ($this->config->application->analytics_code)
echo $this->analytics($this->config->application->analytics_code);
?>
<? /*
<script type="text/javascript">
var uvOptions = {};
(function() {
var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/RFLIXt2xqcpK7mNFeTJzjA.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
})();
</script>
*/ ?>
<script>
var DF_ContentPath = '<?php echo \DF\Url::content(); ?>';
</script>
</head>
<body>
<!-- Start Alexa Certify Javascript -->
<script type="text/javascript">
_atrk_opts = { atrk_acct:"Y1t+i1a8Dy00a/", domain:"ponyvillelive.com",dynamic: true};
(function() { var as = document.createElement('script'); as.type = 'text/javascript'; as.async = true; as.src = "https://d31qbv1cthcecs.cloudfront.net/atrk.js"; var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(as, s); })();
</script>
<noscript><img src="https://d5nxst8fruw4z.cloudfront.net/atrk.gif?account=Y1t+i1a8Dy00a/" style="display:none" height="1" width="1" alt="" /></noscript>
<!-- End Alexa Certify Javascript -->
<div class="top">
<div class="container">
<ul class="loginbar pull-right">
<?
$tz_info = \PVL\Timezone::getInfo();
$tz_text = $tz_info['now']->format('g:ia').' '.$tz_info['abbr'];
?>
<li><a href="<?=$this->route(array('controller' => 'account', 'action' => 'timezone')) ?>" class="fancybox fancybox.ajax"><i class="icon-time"></i> <?=$tz_text ?></a></li>
<li class="divider">&nbsp;</li>
<li><a href="<?=$this->route(array('controller' => 'account', 'action' => 'theme', 'skin' => 'toggle')) ?>"><i class="icon-adjust"></i> <? if ($skin == 'light'): ?>Dark Theme<? else: ?>Light Theme<? endif; ?></a></li>
<li class="divider">&nbsp;</li>
<li><a href="<?=$this->route(array('module' => 'default', 'controller' => 'index', 'action' => 'tunein', 'origin' => 'home')) ?>" id="btn-tune-in"><i class="icon-youtube-play"></i> Player</a></li>
<li class="divider">&nbsp;</li>
<li><a href="<?=$this->route(array('module' => 'default', 'controller' => 'index', 'action' => 'app')) ?>"><i class="icon-cloud-download"></i> Plugins &amp; Apps</a></li>
<li class="divider">&nbsp;</li>
<? if ($this->auth->isLoggedIn()): ?>
<?
$user = $this->auth->getLoggedInUser();
?>
<? if ($this->acl->isAllowed('view administration')): ?>
<li><a href="<?=$this->route(array('module' => 'admin')) ?>"><i class="icon-cog"></i> Admin</a></li>
<li class="divider">&nbsp;</li>
<? endif; ?>
<? if (\Entity\Station::canSeeStationCenter($user)): ?>
<li><a href="<?=$this->route(array('module' => 'stations')) ?>"><i class="icon-group"></i> Station Center</a></li>
<li class="divider">&nbsp;</li>
<? endif; ?>
<li><b><?=$user->name ?></b></li>
<? if ($this->auth->isMasqueraded()): ?>
<li><a href="<?=$this->route(array('module' => 'account', 'controller' => 'logout', 'action' => 'endimpersonate')) ?>"><i class="icon-signout"></i> Switch User</a></li>
<? else: ?>
<li><a href="<?=$this->route(array('module' => 'account', 'controller' => 'logout')) ?>"><i class="icon-signout"></i> Sign Out</a></li>
<? endif; ?>
<? else: ?>
<li><a href="<?=$this->route(array('module' => 'default', 'controller' => 'account', 'action' => 'login')) ?>"><i class="icon-signin"></i> Sign In</a></li>
<? endif; ?>
</ul>
</div>
</div>
<div class="header">
<div class="container">
<div class="logo">
<a href="<?=$this->route() ?>"><img id="logo-header" src="<?=\DF\Url::content('mid2013/logo_'.$skin.'.png') ?>" alt="Logo"></a>
</div>
<div class="navbar">
<div class="navbar-inner">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<div class="nav-collapse collapse">
<?=$this->renderCommon('nav') ?>
</div>
</div>
</div>
</div>
</div>
<? if ($this->placeholder('content_top')->toString()): ?>
<?=$this->placeholder('content_top')->toString() ?>
<? else: ?>
<div id="secondary_header_stripe">&nbsp;</div>
<? endif; ?>
<div id="body-wrapper">
<div id="body" class="container">
<div id="page_wrapper"><div id="page">
<div>
<?
if (\DF\Flash::hasMessages()):
$messages = \DF\Flash::getMessages();
foreach($messages as $message):
?>
<div class="content-top-alert alert alert-<?=$message['color'] ?>" data-alert="alert">
<a class="close" data-dismiss="alert" href="#">×</a>
<?=$message['message'] ?>
</div>
<?
endforeach;
endif;
?>
<div id="content_wrapper">
<div id="content">
<?
$breadcrumb = $this->breadcrumb()->render();
if ($breadcrumb):
?>
<div id="breadcrumb">
<a href="<?=\DF\Url::baseUrl() ?>/"><?=$this->config->application->name ?></a> &raquo; <?=$breadcrumb ?>
</div>
<? endif; ?>
<? if (!$this->layout()->hide_title): ?>
<h1 class="title"><?=$title ?></h1>
<? endif; ?>
<? if ($this->layout()->tabs): ?>
<div id="content_tabs">
<?=$this->layout()->tabs ?>
</div>
<? endif; ?>
<? if ($this->layout()->subtitle): ?>
<h2 class="title"><?=$this->layout()->subtitle ?></h2>
<? endif; ?>
<? if ($this->layout()->manual): ?>
<?php echo $this->layout()->content; ?>
<? else: ?>
<div class="row-fluid">
<div class="span12">
<div class="content_inner">
<?php echo $this->layout()->content; ?>
</div>
</div>
</div>
<? endif; ?>
</div>
</div>
</div>
</div></div>
</div>
</div>
<div class="footer">
<div class="container">
<?=$this->renderCommon('footer') ?>
</div>
</div>
<div class="copyright">
<div class="container">
<p>MLP is copyright &copy; Hasbro. All creations are &copy; to their respective artists. All songs are property of their respective artists.<br>
Copyright &copy; <?=date('Y') ?> Ponyville Live! All rights reserved.</p>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,86 @@
<?php
/*
$theme_session = \DF\Session::getNamespace('theme');
$default_theme = $this->config->pvl->default_theme;
$skin = ($theme_session->skin) ? $theme_session->skin : $default_theme;
*/
$skin = ($this->skin) ? $this->skin : 'dark';
$embed = ($this->embed_mode) ? 'embedded' : 'non-embedded';
?>
<?php echo $this->doctype(); ?>
<html class="compact_layout theme_<?=$skin ?> <?=$embed ?>">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
$title = current($this->headTitle()->getIterator());
$this->headTitle($this->config->application->name);
if (DF_APPLICATION_ENV != "production")
$this->headTitle()->prepend('('.ucfirst(DF_APPLICATION_ENV).')');
echo $this->headTitle()->setSeparator(" | ")->toString();
$this->headLink()
->appendStylesheet(\DF\Url::content('common/bootstrap2_r2/df-ui.css'), 'all')
->appendStylesheet(\DF\Url::content('common/bootstrap2_r2/df-ui-responsive.css'), 'all')
->appendStylesheet(\DF\Url::content('global.css'), 'all')
->appendStylesheet(\DF\Url::content('common/jquery/fancybox/jquery.fancybox.css'), 'all')
->appendStylesheet(\DF\Url::content('common/bootstrap2_r2/df-ui-printable.css'), 'print')
->appendStylesheet('http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700', 'screen')
->appendStylesheet(\DF\Url::content('global_'.$skin.'.css'));
$this->headScript()
->prependFile(\DF\Url::cdn('jquery', '1.8'))
->appendFile(\DF\Url::content('common/jquery/fancybox/jquery.fancybox.pack.js'))
->appendFile(\DF\Url::content('common/bootstrap2_r2/bootstrap/js/bootstrap.min.js'))
->appendFile(\DF\Url::content('common/bootstrap2_r2/layout.js'))
->appendFile(\DF\Url::content('global.js'))
->appendFile(\DF\Url::content('swfobject.js'));
echo $this->headMeta();
echo $this->headLink();
echo $this->headScript();
if ($this->config->application->analytics_code)
echo $this->analytics($this->config->application->analytics_code);
?>
<script>
var DF_ContentPath = '<?php echo \DF\Url::content(); ?>';
</script>
</head>
<body>
<!-- Start Alexa Certify Javascript -->
<script type="text/javascript">
_atrk_opts = { atrk_acct:"Y1t+i1a8Dy00a/", domain:"ponyvillelive.com",dynamic: true};
(function() { var as = document.createElement('script'); as.type = 'text/javascript'; as.async = true; as.src = "https://d31qbv1cthcecs.cloudfront.net/atrk.js"; var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(as, s); })();
</script>
<noscript><img src="https://d5nxst8fruw4z.cloudfront.net/atrk.gif?account=Y1t+i1a8Dy00a/" style="display:none" height="1" width="1" alt="" /></noscript>
<!-- End Alexa Certify Javascript -->
<div id="body-wrapper">
<div id="body" class="container">
<div id="maintenance_header">
<a href="<?=$this->route(array('module' => 'default')) ?>" title="Home" target="_blank"><img src="<?=\DF\Url::content('pvl_'.$skin.'.png') ?>" alt="Home" /></a>
</div>
<? if ($title): ?>
<h1 class="title"><?=$title ?></h1>
<? endif; ?>
<? if ($this->layout()->manual): ?>
<?php echo $this->layout()->content; ?>
<? else: ?>
<div class="row">
<div class="span12">
<div class="floating">
<div class="content_inner">
<?php echo $this->layout()->content; ?>
</div>
</div>
</div>
</div>
<? endif; ?>
</div>
</div>
</body>
</html>

102
app/layouts/message.phtml Executable file
View File

@ -0,0 +1,102 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
{literal}
<!--
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
background-color: #FFFFFF;
}
body, td, th, div {
font-family: "Tahoma", Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
color: #000;
}
h1 {
font-size: 20px;
font-weight: normal;
}
h2 {
font-size: 17px;
font-weight: bold;
}
h3 {
font-size: 14px;
font-weight: bold;
}
small {
font-size: 11px;
color: #999999;
}
dt {
font-weight: bold;
}
#content-wrapper {
padding: 5px;
background-color: #FFFFFF;
}
#content {
border-top: 1px solid #CCC;
border-bottom: 1px solid #CCC;
padding-top: 20px;
padding-bottom: 20px;
}
#footer {
font-size: 11px;
color: #999999;
}
table.datatable {
border: 1px solid #CCC;
border-collapse: collapse;
}
table.datatable th {
background: #EEE;
border: 1px solid #CCC;
padding: 6px 4px;
}
table.datatable tfoot tr td {
background: #EEE;
border-left: 1px solid #CCC;
border-top: 1px solid #CCC;
padding: 6px 4px;
}
table.datatable tr td {
background: #EEE;
border-left: 1px solid #CCC;
border-bottom: 1px solid #EEE;
padding: 4px;
vertical-align: top;
}
table.datatable tr.even td {
background: #EDF5FF;
}
table.datatable tr.odd td {
background: #FFF;
}
table tr td.left_padded,
table tr th.left_padded {
padding-left: 10px;
}
-->
{/literal}
</style>
</head>
<body>
<div style="padding: 5px;">
<h1><?=$this->config->application->name ?></h1>
<?=$this->layout()->content ?>
</div>
</body>
</html>

22
app/library/DF/Acl.php Executable file
View File

@ -0,0 +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);
}
}

149
app/library/DF/Acl/Instance.php Executable file
View File

@ -0,0 +1,149 @@
<?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();
}
}
}

View File

@ -0,0 +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;
}
}

View File

@ -0,0 +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;
}
}

View File

@ -0,0 +1,146 @@
<?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;
// 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;
if ($options['conn']['platform'])
{
$class_obj = new \ReflectionClass($options['conn']['platform']);
$options['conn']['platform'] = $class_obj->newInstance();
}
$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);
if ($options['conn']['driver'] != "pdo_sqlsrv")
$em->getConnection()->setCharset('utf8');
$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

@ -0,0 +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;
}
}

19
app/library/DF/Auth.php Executable file
View File

@ -0,0 +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);
}
}

View File

@ -0,0 +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);
}
}

View File

@ -0,0 +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']);
}
}

View File

@ -0,0 +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('Could not determine credentials to be authentic.')
);
}
}
public function modelAuth($username, $password)
{
return \Entity\User::authenticate($username, $password);
}
}

40
app/library/DF/Auth/Cas.php Executable file
View File

@ -0,0 +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;
}
}
}

View File

@ -0,0 +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);
}
}

206
app/library/DF/Auth/Instance.php Executable file
View File

@ -0,0 +1,206 @@
<?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);
$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;
}
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;
}
}

65
app/library/DF/Auth/Ldap.php Executable file
View File

@ -0,0 +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;
}
}
}

39
app/library/DF/Auth/Model.php Executable file
View File

@ -0,0 +1,39 @@
<?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->_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

@ -0,0 +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);
}
}

200
app/library/DF/Cache.php Normal file
View File

@ -0,0 +1,200 @@
<?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_umask' => 0777,
'cache_file_perm' => 0777,
);
}
return array($backend_name, $backend_options);
}
}

227
app/library/DF/Calendar.php Normal file
View File

@ -0,0 +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));
}
}

94
app/library/DF/Config.php Executable file
View File

@ -0,0 +1,94 @@
<?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;
}
}

View File

@ -0,0 +1,326 @@
<?php
namespace DF\Controller;
use \DF\Url;
use \DF\Flash;
class Action extends \Zend_Controller_Action
{
public $config;
public $module_config;
public $auth;
public $acl;
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];
$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 \DF\Exception\NotLoggedIn();
else
throw new \DF\Exception\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();
}
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)
{
return $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);
}
protected 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 = new \Zend_Session_Namespace('df_referrer_'.strtolower($namespace));
if( !isset($session->url) || ($loose && isset($session->url) && Url::current() != Url::referrer()) )
$session->url = Url::referrer();
}
protected function getStoredReferrer($namespace = 'default')
{
$session = new \Zend_Session_Namespace('df_referrer_' . strtolower($namespace));
return $session->url;
}
protected function clearStoredReferrer($namespace = 'default')
{
$session = new \Zend_Session_Namespace('df_referrer_' . strtolower($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;
}
}
/**
* 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);
}
}

29
app/library/DF/Csrf.php Executable file
View File

@ -0,0 +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());
}
}

View File

@ -0,0 +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);
}
}

View File

@ -0,0 +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);
$value = \DateTime::createFromFormat(\DateTime::ISO8601, date(\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

@ -0,0 +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';
}
}

View File

@ -0,0 +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()';
}
}

View File

@ -0,0 +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()
{}
}

View File

@ -0,0 +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;
}
}

View File

@ -0,0 +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';
}
}

View File

@ -0,0 +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;
}
}

View File

@ -0,0 +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;
}
}

View File

@ -0,0 +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;
}
}

View File

@ -0,0 +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;
}
}

46
app/library/DF/Encryption.php Executable file
View File

@ -0,0 +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);
}
}

3
app/library/DF/Exception.php Executable file
View File

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

View File

@ -0,0 +1,7 @@
<?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

@ -0,0 +1,7 @@
<?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 {}

280
app/library/DF/Export.php Executable file
View File

@ -0,0 +1,280 @@
<?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;
}
/**
* 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));
}
}

192
app/library/DF/File.php Executable file
View File

@ -0,0 +1,192 @@
<?php
/**
* Static class that facilitates the uploading, reading and deletion of files in a controlled directory.
*/
namespace DF;
class File
{
public static function getFileExtension($file_name)
{
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));
}
}

20
app/library/DF/Filter/Float.php Executable file
View File

@ -0,0 +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;
}
}

159
app/library/DF/Filter/Phone.php Executable file
View File

@ -0,0 +1,159 @@
<?php
namespace DF\Filter;
class Phone implements \Zend_Filter_Interface
{
/**
* Output format string
*
* @var string
*/
protected $_format = '%countrycode% %areacode% %centralofficecode%-%linenumber% %extension%';
/**
* Formatting options to apply to a token before placing in the format string
*
* @var array
*/
protected $_subFormats = array(
'%areacode%' => '(%areacode%)',
'%extension%' => 'ext. %extension%',
);
/**
* Values to be replaced if one of the following tokens is empty
*
* @var array
*/
protected $_ifEmpty = array(
'%areacode%' => '',
'%extension%' => '',
'%countrycode%' => '',
);
/**
* Common delimiter between groupings of numerals in a phone number
*
* @var string
*/
protected static $_phoneRegex_delim = "[\W]*";
/**
* Portions of the phone regular expression. Expressed as an array for ease
* of maintenence. Not intended to be altered.
*
* @var array
*/
protected static $_phoneRegex_pieces = array(
'%countrycode% + %areacode%' => '(([\s\+\-\d]+|)[\W]*(\d{3})|)', //country code requires an area code
'%centralofficecode%' => '(\d{3})',
'%linenumber%' => '(\d{4})',
'%extension%' => '((ext[\.\s]*)(\d+)|)'
);
/**
* List the numerical indicies for the particular groups in the $matches array
* returned by preg_match().
*
* @var array
*/
protected $_groups = array(
'%countrycode%' => 2,
'%areacode%' => 3,
'%centralofficecode%' => 4,
'%linenumber%' => 5,
'%extension%' => 8,
);
/**
* Valid replaceable tokens are:
*
* - %countrycode%
* - %areacode%
* - %centralofficecode%
* - %linenumber%
* - %extension%
*
*
* @param string $phoneFormat
* @param array $subFormats
* @param array $ifEmpty
*/
public function __construct($phoneFormat = null, array $subFormats = null, array $ifEmpty = null)
{
if( $phoneFormat !== null )
$this->_format = $phoneFormat;
if( $subFormats !== null )
$this->_subFormats = $subFormats;
if( $ifEmpty !== null )
$this->_ifEmpty = $ifEmpty;
}
/**
* Returns the compiled phone regular expression
*
* @staticvar string $regex Cached regex string
* @return string
*
*/
public static function getPhoneRegex()
{
static $regex;
if( !$regex )
$regex = '#^' . implode(self::$_phoneRegex_delim, self::$_phoneRegex_pieces) . '$#i';
return $regex;
}
/**
* Formats a given phone number according to the rules given in the constructor
*
* @param string $value
* @return string
*/
public function filter($value)
{
$value = trim($value);
$matches = array();
if( preg_match(self::getPhoneRegex(), $value, $matches) != 1 )
{
return $value;
}
$search = array();
$replace = array();
foreach( $this->_groups as $key => $value )
{
$search[$key] = $key;
if( isset($matches[$value]) )
$replace[$key] = trim($matches[$value]);
else
$replace[$key] = '';
}
foreach( $this->_subFormats as $key => $format )
{
$match = isset($matches[$this->_groups[$key]]) ? $matches[$this->_groups[$key]] : '';
if( trim($match) != '' )
{
$replace[$key] = str_replace($key, $match, $format);
}
else
{
$replace[$key] = '';
}
}
foreach( $this->_ifEmpty as $key => $value )
{
if( !isset($replace[$key]) || $replace[$key] == '' )
$replace[$key] = $value;
}
return trim(str_replace($search, $replace, $this->_format));
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace DF\Filter;
class WebAddress implements \Zend_Filter_Interface
{
public function filter($value)
{
$value = trim($value);
if ($value && substr($value, 0, 4) != "http")
$value = 'http://'.str_replace('http://', '', $value);
return $value;
}
}

53
app/library/DF/Flash.php Executable file
View File

@ -0,0 +1,53 @@
<?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 = new \Zend_Session_Namespace('DF_Flash');
$color_chart = array(
'green' => 'success',
'success' => 'success',
'yellow' => 'warning',
'warning' => 'warning',
'red' => 'error',
'error' => 'error',
'info' => 'info',
'blue' => 'info',
'default' => 'info',
);
$session->messages[] = array(
'message' => $message,
'color' => (isset($color_chart[$level])) ? $color_chart[$level] : $color_chart['default'],
);
}
public static function hasMessages()
{
$session = new \Zend_Session_Namespace('DF_Flash');
$messages = (array)$session->messages;
return count($messages) > 0;
}
public static function getMessages()
{
$session = new \Zend_Session_Namespace('DF_Flash');
$messages = (array)$session->messages;
unset($session->messages);
return (count($messages) > 0) ? $messages : false;
}
}

330
app/library/DF/Form.php Normal file
View File

@ -0,0 +1,330 @@
<?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.'/'.$new_file_name;
$new_file_path_full = DF_UPLOAD_FOLDER.DIRECTORY_SEPARATOR.$new_file_path_short;
@rename($file_path_original, $new_file_path_full);
$return_fields[$element_name][$i] = $new_file_path_short;
$i++;
}
}
}
}
return $return_fields;
}
}

39
app/library/DF/Form/Custom.php Executable file
View File

@ -0,0 +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.");
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace DF\Form\Decorator;
class DtDdWrapper extends \Zend_Form_Decorator_Abstract
{
public function render($content)
{
$elementName = $this->getElement()->getName();
$dtLabel = $this->getOption('dtLabel');
$dt = '<dt id="' . $elementName . '-label">' . $dtLabel . '</dt>';
$dd = '<dd id="' . $elementName . '-element">' . $content . '</dd>';
if( null !== $dtLabel )
return $dt.$dd;
else
return $dd;
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace DF\Form\Decorator;
class FormErrors extends \Zend_Form_Decorator_FormErrors
{
public function render($content)
{
$errors = parent::render('');
if (empty($errors))
return $content;
$markup = '<div class="alert block-message alert-error"><p>The form could not be submitted because the following errors occurred:</p>'.$errors.'</div>';
switch ($this->getPlacement()) {
case self::APPEND:
return $content . $this->getSeparator() . $markup;
case self::PREPEND:
return $markup . $this->getSeparator() . $content;
}
}
}

View File

@ -0,0 +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;
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace DF\Form\Decorator;
class FormFileView extends \Zend_Form_Decorator_Abstract implements \Zend_Form_Decorator_Marker_File_Interface
{
public function render($content)
{
return $content;
}
}

View File

@ -0,0 +1,134 @@
<?php
namespace DF\Form\Decorator;
class FormView extends \Zend_Form_Decorator_Form
{
public function render($content)
{
$view_mode = $GLOBALS['df_form_mode'];
$element = $this->getElement();
// Special handling for subforms and forms themselves.
if ($element instanceof \Zend_Form)
{
$elements = $element->getElements();
$groups = $element->getDisplayGroups();
$attribs = $element->getAttribs();
$content = trim($content);
// Wrap content in DL tag if not otherwise done.
if (count($groups) == 0 && $content)
$content = '<dl>'.$content.'</dl>';
if ($view_mode == "message")
return $content;
else
return '<div class="form-view">'.$content.'</div>';
}
// Special handling for formsets.
if ($element instanceof \Zend_Form_DisplayGroup)
{
if (trim($content))
{
$attribs = $element->getAttribs();
$return = '';
if ($attribs['legend'])
$return .= '<h3>'.$attribs['legend'].'</h3>';
$return .= '<dl>'.trim($content).'</dl>';
return $return;
}
return NULL;
}
if ($element->getIgnore() == TRUE)
return NULL;
$element_attribs = $element->getAttribs();
$element_options = (isset($element_attribs['options'])) ? $element_attribs['options'] : array();
$element_value = $element_attribs['df_raw_value'];
if ($element_value === NULL)
return NULL;
$return_content = '';
if ($element instanceof \Zend_Form_Element_File)
{
if (defined('DF_UPLOAD_URL') && DF_UPLOAD_URL)
$url_base = DF_UPLOAD_URL;
else
$url_base = \DF\Url::content();
$files = (array)$element_value;
$i = 1;
foreach($files as $file)
{
$file_url = $url_base.'/'.$file;
$return_content .= '<div>#'.$i.': <a href="'.$file_url.'" target="_blank">Download File</a>';
$i++;
}
}
else if ($element instanceof \DF\Form\Element\UnixDate)
{
$return_content .= ($element_value != 0) ? date('F j, Y', $element_value) : '';
}
else if ($element instanceof \DF\Form\Element\UnixDateTime)
{
$return_content .= ($element_value != 0) ? date('F j, Y g:ia', $element_value) : '';
}
else if (is_array($element_value))
{
$return_content .= '<ul>';
foreach($element_value as $element_value_item)
{
if (isset($element_options[$element_value_item]))
$element_value_item = $element_options[$element_value_item];
$return_content .= '<li>'.$element_value_item.'</li>';
}
$return_content .= '</ul>';
}
else
{
$validators = (array)$element->getValidators();
$validator_classes = array_keys($validators);
$filters = (array)$element->getFilters();
$filter_classes = array_keys($filters);
if ($element_value && in_array('Zend_Validate_EmailAddress', $validator_classes))
{
$element_value = '<a href="mailto:'.$element_value.'">'.$element_value.'</a>';
}
elseif ($element_value && in_array('DF\Filter\WebAddress', $filter_classes))
{
$element_value = '<a href="'.$element_value.'" target="_blank">'.$element_value.'</a>';
}
if ($element_options)
$return_content .= nl2br($element_options[$element_value]);
else
$return_content .= nl2br($element_value);
}
if (trim($return_content))
{
$label_raw = $element->getLabel();
if ($label_raw)
$label = '<dt>'.$label_raw.':</dt>';
else
$label = '';
return $label.'<dd>'.$return_content.'</dd>';
}
}
}

View File

@ -0,0 +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;
}
}
}

View File

@ -0,0 +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;
}
}

View File

@ -0,0 +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;
}
}

View File

@ -0,0 +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);
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) : '';
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'] : date('m', $default_timestamp);
$day = (!empty($value['day'])) ? (int)$value['day'] : date('d', $default_timestamp);
$year = (!empty($value['year'])) ? (int)$value['year'] : date('Y', $default_timestamp);
return strtotime($month.'/'.$day.'/'.$year.' 00:00:00');
}
}
}

View File

@ -0,0 +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);
}
}

View File

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

86
app/library/DF/Image.php Normal file
View File

@ -0,0 +1,86 @@
<?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;
}
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, 0);
break;
}
}
}

83
app/library/DF/Loader.php Executable file
View File

@ -0,0 +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();
}
}

58
app/library/DF/Menu.php Executable file
View File

@ -0,0 +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;
}
}

View File

@ -0,0 +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 = $mail_config['smtp'];
$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;
}
}

53
app/library/DF/Mobile.php Executable file
View File

@ -0,0 +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);
}
}

222
app/library/DF/Navigation.php Executable file
View File

@ -0,0 +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);
}
}

18
app/library/DF/Paginator.php Executable file
View File

@ -0,0 +1,18 @@
<?php
namespace DF;
class Paginator extends \Zend_Paginator
{
public function __construct($paged_object, $page = 1, $limit = 10)
{
if ($paged_object instanceof \Doctrine\ORM\Query || $paged_object instanceof \Doctrine\ORM\QueryBuilder)
parent::__construct(new Paginator\Adapter\DoctrineQuery($paged_object));
elseif (is_array($paged_object))
parent::__construct(new \Zend_Paginator_Adapter_Array($paged_object));
else
parent::__construct(new \Zend_Paginator_Adapter_Null($paged_object));
$this->setItemCountPerPage($limit);
$this->setCurrentPageNumber($page);
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace DF\Paginator\Adapter;
use \Doctrine\ORM\Query;
use \Doctrine\ORM\QueryBuilder;
class DoctrineQuery implements \Zend_Paginator_Adapter_Interface
{
protected $_query;
protected $_rowCount;
public function __construct($query)
{
if ($query instanceof QueryBuilder)
$query = $query->getQuery();
$this->_query = $query;
}
public function cloneQuery(Query $query)
{
$countQuery = clone $query;
$params = $query->getParameters();
foreach ($params as $key => $param) {
$countQuery->setParameter($key, $param);
}
return $countQuery;
}
public function getItems($offset, $itemsPerPage)
{
$qb = $this->cloneQuery($this->_query);
$qb->setFirstResult($offset);
$qb->setMaxResults($itemsPerPage);
return $qb->execute();
}
public function count()
{
if ($this->_rowCount === null)
{
$query = $this->cloneQuery($this->_query);
$query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('DF\Doctrine\Paginate\CountWalker'));
$query->setFirstResult(null)->setMaxResults(null);
$this->_rowCount = $query->getSingleScalarResult();
}
return $this->_rowCount;
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace DF\Paginator;
class Doctrine extends \Zend_Paginator
{
public function __construct($query, $page = 1, $limit = 10)
{
parent::__construct(new Adapter\DoctrineQuery($query));
$this->setItemCountPerPage($limit);
$this->setCurrentPageNumber($page);
}
}

118
app/library/DF/Search.php Executable file
View File

@ -0,0 +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(),
);
}
}
}

View File

@ -0,0 +1,9 @@
<?php
/**
* Compass API interface class.
*/
namespace DF\Service;
class Compass extends DoitApi
{}

View File

@ -0,0 +1,163 @@
<?php
/**
* DoIT API (CompassAPI) interface class.
*/
namespace DF\Service;
class DoitApi
{
const TIMEOUT = 300;
protected $_settings;
protected $_http_client;
public function __construct()
{
$config = \Zend_Registry::get('config');
$this->_settings = $config->services->doitapi->toArray();
}
public function __call($method, $params = array())
{
return $this->request($method, $params);
}
/**
* Custom Wrapper Functions
*/
public function checkAvailability()
{
try
{
$response = $this->request('isServerAlive');
return ($response);
}
catch (Exception $e)
{
return false;
}
}
public function logException($exception, $user = NULL)
{
try
{
$config = \Zend_Registry::get('config');
return $this->request('logException', array($config->application->shortcode, array(
'environment' => DF_APPLICATION_ENV,
'user' => $user,
'message' => $exception->getMessage(),
'exception' => get_class($exception),
'file' => $exception->getFile(),
'stack_trace' => $exception->getTraceAsString(),
'ip' => $_SERVER['REMOTE_ADDR'],
'user_agent' => $_SERVER['HTTP_USER_AGENT'],
'request_uri' => $_SERVER['REQUEST_URI'],
'referrer' => $_SERVER['HTTP_REFERRER'],
'request_params' => $_REQUEST,
)));
}
catch (\Exception $e)
{
return $e->getMessage();
}
}
/**
* Standard API Calls
*/
protected function request($method, $params = array(), $id = NULL)
{
set_time_limit(self::TIMEOUT+30);
$client = $this->getHttpClient();
$client->setUri($this->_settings['service_uri']);
$request_string = array(
'jsonrpc' => '2.0',
'method' => $method,
'params' => $params,
'id' => $id,
);
$request_string = json_encode($request_string);
$client->setRawData($request_string, 'application/json');
$client->setHeaders('X-Compass-Api-Request-Signature: '.$this->getRequestSignature($request_string));
$response = $client->request('POST');
if ($response->isSuccessful() && $this->validateResponse($response))
{
$response_text = $response->getBody();
$response_json = json_decode($response_text, TRUE);
if (isset($response_json['result']))
{
return $response_json['result'];
}
}
else
{
throw new \Exception('Invalid Response (HTTP '.$response->getStatus().'): '.$response->getBody());
}
}
protected function getHttpClient()
{
if (!is_object($this->_http_client))
{
if (DF_APPLICATION_ENV == "standalone")
{
$this->_http_client = new \Zend_Http_Client(NULL, array(
'adapter' => new \Zend_Http_Client_Adapter_Test,
));
}
else
{
$this->_http_client = new \Zend_Http_Client();
$this->_http_client->setConfig(array(
'timeout' => self::TIMEOUT,
'keepalive' => true,
));
}
}
$this->_http_client->resetParameters();
return $this->_http_client;
}
protected function validateResponse($response)
{
$signature = $response->getHeader('X-Compass-Api-Response-Signature', 'unsigned');
if(strtolower($signature) == 'unsigned')
{
if($response->hasData('error'))
return true;
else
return false;
}
$hash = $this->getDataHash($response->getBody());
return ($hash == $signature);
}
protected function getDataHash($data)
{
$hash = hash_hmac("sha256", $data, $this->_settings['private_key']);
return $hash;
}
protected function getRequestSignature($data)
{
$hash = $this->getDataHash($data);
return $this->_settings['api_key'].':'.$hash;
}
}

File diff suppressed because it is too large Load Diff

View File

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

183
app/library/DF/Service/Ldap.php Executable file
View File

@ -0,0 +1,183 @@
<?php
/**
* LDAP Authentication Adapter
*/
namespace DF\Service;
define(LDAP_OPT_DIAGNOSTIC_MESSAGE, 0x0032);
use \Entity\Role;
class Ldap
{
public static function authenticate($username, $password)
{
$ldapconn = self::init();
$user_entry = self::findByUsername($username);
if ($user_entry)
{
$user_dn = $user_entry['ldap_dn'];
$login = @ldap_bind($ldapconn, $user_dn, $password);
if ($user_dn && $login)
{
return new \Zend_Auth_Result(
\Zend_Auth_Result::SUCCESS,
$user_entry,
array()
);
}
else
{
return new \Zend_Auth_Result(
\Zend_Auth_Result::FAILURE,
null,
(array)'Login failed.'
);
}
}
else
{
return new \Zend_Auth_Result(
\Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,
null,
array(
'Username not found.'
)
);
}
}
public static function search($query)
{
$fields_to_search = array(
'sAMAccountName',
'cn',
);
foreach($fields_to_search as $search_field)
{
$result = self::findByField($search_field, $query);
if ($result)
return $result;
}
return NULL;
}
public static function findById($id)
{ return self::findByField('sID', $id); }
public static function findByUsername($username)
{ return self::findByField('sAMAccountName', $username); }
public static function findByName()
{ return self::findByField('cn', $username); }
public static function findByField($field_name, $field_val)
{
$settings = self::getSettings();
$ldapconn = self::init();
$search_dn = $field_name.'='.$field_val;
$results = ldap_search($ldapconn, $settings['basedn'], $search_dn);
$entries = ldap_get_entries($ldapconn, $results);
if ($entries['count'] > 0)
{
$entry = $entries[0];
return self::processEntry($entry);
}
return NULL;
}
public static function processEntry($entry)
{
$settings = self::getSettings();
// Parse user roles.
$user_roles = array();
foreach((array)$entry['memberof'] as $group_item)
{
$addr_parts = ldap_explode_dn($group_item, 1);
$group_name = ($addr_parts) ? trim($addr_parts[0]) : NULL;
if (isset($settings['role_mapping'][$group_name]))
{
$role_name = $settings['role_mapping'][$group_name];
if ($role_name instanceof Role)
{
$user_roles[] = $role->id;
}
else
{
$role = Role::getRepository()->findOneByName($role_name);
if ($role instanceof Role)
$user_roles[] = $role->id;
}
}
}
// Parse department name.
$addr_parts = ldap_explode_dn($entry['dn'], 1);
$addr_parts = ($addr_parts) ? array_reverse($addr_parts) : array();
$dept_name = $addr_parts[6];
return array(
'ldap_guid' => base64_encode($entry['objectguid'][0]),
'ldap_dn' => $entry['dn'],
'username' => $entry['samaccountname'][0],
'firstname' => $entry['givenname'][0],
'lastname' => $entry['sn'][0],
'title' => $entry['title'][0],
'dept' => $dept_name,
'email' => $entry['mail'][0],
'phone' => $entry['telephonenumber'][0],
'roles' => $user_roles,
);
}
public static function init()
{
static $ldapconn;
if (!$ldapconn)
{
if (DF_APPLICATION_ENV == "standalone")
throw new \DF\Exception('LDAP authentication called in a standalone environment.');
$settings = self::getSettings();
ldap_set_option($ldapconn, LDAP_OPT_DEBUG_LEVEL, 7);
$ldapconn = ldap_connect($settings['server']);
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
if ($settings['tls'])
{
putenv('LDAPTLS_REQCERT=never') or die('Failed to setup the env');
ldap_start_tls($ldapconn);
}
@ldap_bind($ldapconn, $settings['binddn'], $settings['bindpw']);
}
return $ldapconn;
}
public static function getSettings()
{
static $settings;
if (!$settings)
{
$config = \Zend_Registry::get('config');
$settings = $config->services->ldap->toArray();
}
return $settings;
}
}

108
app/library/DF/Service/PubNub.php Executable file
View File

@ -0,0 +1,108 @@
<?php
namespace DF\Service;
class PubNub {
private $ORIGIN = 'pubsub.pubnub.com';
private $LIMIT = 1800;
private $PUBLISH_KEY = 'demo';
private $SUBSCRIBE_KEY = 'demo';
private $SECRET_KEY = false;
private $SSL = false;
public function __construct()
{
$config = \Zend_Registry::get('config');
$settings = $config->services->pubnub->toArray();
$this->PUBLISH_KEY = $settings['pub_key'];
$this->SUBSCRIBE_KEY = $settings['sub_key'];
$this->SECRET_KEY = $settings['secret_key'];
$this->SSL = $settings['ssl'];
$this->ORIGIN = (($this->SSL) ? 'https://' : 'http://').$this->ORIGIN;
}
public function publish($channel, $message)
{
$message = json_encode($message);
## Generate String to Sign
$string_to_sign = implode( '/', array(
$this->PUBLISH_KEY,
$this->SUBSCRIBE_KEY,
$this->SECRET_KEY,
$channel,
$message
) );
## Sign Message
$signature = $this->SECRET_KEY ? md5($string_to_sign) : '0';
## Fail if message too long.
if (strlen($message) > $this->LIMIT) {
echo('Message TOO LONG (' . $this->LIMIT . ' LIMIT)');
return array( 0, 'Message Too Long.' );
}
## Send Message
return $this->_request(array(
'publish',
$this->PUBLISH_KEY,
$this->SUBSCRIBE_KEY,
$signature,
$channel,
'0',
$message
));
}
public function history($channel, $limit = 10)
{
## Get History
return $this->_request(array(
'history',
$this->SUBSCRIBE_KEY,
$channel,
'0',
$limit
));
}
public function time() {
## Get History
$response = $this->_request(array(
'time',
'0'
));
return $response[0];
}
private function _request($request)
{
$request = array_map(array(__CLASS__, '_encode'), $request);
array_unshift( $request, $this->ORIGIN );
$ctx = stream_context_create(array(
'http' => array( 'timeout' => 200 )
));
return json_decode( @file_get_contents(
implode( '/', $request ), 0, $ctx
), true );
}
protected static function _encode($part)
{
return implode('', array_map(
array(__CLASS__, '_encode_char'), str_split($part)
));
}
protected static function _encode_char($char)
{
if (strpos( ' ~`!@#$%^&*()+=[]\\{}|;\':",./<>?', $char ) === false)
return $char;
return rawurlencode($char);
}
}

View File

@ -0,0 +1,81 @@
<?php
/**
* TAMU REST Web Services Connector
*/
namespace DF\Service;
class TamuRest
{
public static function getByUin($uin)
{
return self::request('uin', $uin);
}
public function getByNetid($netid)
{
return self::request('netid', $netid);
}
public function getByUid($uid)
{
return self::request('uid', $uid);
}
protected static function request($criteria, $value)
{
if (DF_APPLICATION_ENV == "standalone")
return NULL;
$settings = self::getSettings();
$replacement_pattern = array(
'{CRITERIA}' => urlencode($criteria),
'{VALUE}' => urlencode($value),
'{FORMAT}' => 'json',
);
$uri_base = $settings['uri_base'];
$uri_page = str_replace(array_keys($replacement_pattern), array_values($replacement_pattern), $settings['uri_style']);
$http_client = new \Zend_Http_Client();
$http_client->setUri($uri_base.$uri_page);
$date_header = gmdate('D, d M Y H:i:s \G\M\T'); // Valid HTTP header date format.
$authentication_string = $uri_page."\n".$date_header."\n".$settings['identifier'];
$signature = base64_encode(hash_hmac('sha256', $authentication_string, $settings['shared_secret'], TRUE));
$http_client->setHeaders(array(
'Date' => $date_header,
'Authorization' => 'TAM '.$settings['identifier'].':'.$signature
));
try
{
$response = $http_client->request('GET');
}
catch(\Exception $e)
{
return NULL;
}
if ($response->isSuccessful())
{
$body = $response->getBody();
return \Zend_Json::decode($body);
}
else
{
return NULL;
}
}
protected static function getSettings()
{
static $settings;
if (!$settings)
{
$config = \Zend_Registry::get('config');
$settings = $config->services->tamurest->toArray();
}
return $settings;
}
}

View File

@ -0,0 +1,131 @@
<?php
/**
* TouchNet uPay Connector Class
*/
namespace DF\Service;
class TouchNet
{
// Creates a new transaction in the local database and returns the data necessary to create the form post.
public static function createTransaction($amount, $user, $site_id = null)
{
$record = new \Entity\Touchnet();
$record->user = $user;
$record->time_created = time();
$record->time_updated = time();
$record->payment_status = 'pending';
$record->save();
$record_id = $record->id;
$trans_id = self::getTransactionId($record_id);
$record->transaction_id = $trans_id;
$record->save();
$settings = self::getSettings();
// Compose the transaction information array and return it.
$transaction_data = array(
'record' => $record,
'url' => $settings->form_url,
'fields' => array(
'UPAY_SITE_ID' => (!is_null($site_id)) ? $site_id : $settings->site_id,
'EXT_TRANS_ID' => $trans_id,
'EXT_TRANS_ID_LABEL' => $settings->trans_id_label,
'AMT' => number_format($amount, 2, '.', ''),
'VALIDATION_KEY' => self::getValidationKey($amount, $trans_id),
),
);
return $transaction_data;
}
// Get the validation key for a transaction.
public static function getValidationKey($amount, $trans_id)
{
$settings = self::getSettings();
$encode_string = $settings->posting_key . $trans_id . number_format($amount, 2, '.', '');
return base64_encode(md5($encode_string, true));
}
// Generate a new transaction ID.
public static function getTransactionId($record_id)
{
$settings = self::getSettings();
$record_hash = strtoupper(md5($settings->posting_key.$record_id));
$record_id_string = str_pad($record_id, 6, '0', STR_PAD_LEFT);
return substr($record_hash, 0, 5).$record_id_string;
}
// Handle the submission of posting URL data from the payment system. Returns the UserID to mark as paid if applicable.
public static function processPostData()
{
$settings = self::getSettings();
// Check for valid posting key.
if (strcmp($_REQUEST['posting_key'], $settings->posting_key) == 0)
{
// Check for existing transaction ID.
$trans_id = $_REQUEST['EXT_TRANS_ID'];
$record = \Entity\Touchnet::getRepository()->findOneBy(array('transaction_id' => $trans_id));
if ($record instanceof \Entity\Touchnet)
{
if ($_REQUEST['pmt_status'] == "success")
{
$record->payment_status = 'success';
$record->payment_amount = floatval($_REQUEST['pmt_amt']);
$record->payment_card_type = (string)$_REQUEST['card_type'];
$record->payment_name = (string)$_REQUEST['name_on_acct'];
$record->payment_order_id = intval($_REQUEST['sys_tracking_id']);
$record->payment_internal_trans_id = $_REQUEST['tpg_trans_id'];
$record->time_updated = time();
$record->save();
return $record;
}
else if ($_REQUEST['pmt_status'] == "cancelled")
{
$record->payment_status = 'cancelled';
$record->time_updated = time();
$record->save();
return NULL;
}
else
{
self::error('Invalid status code provided.');
}
}
else
{
self::error('Transaction not found!');
}
}
else
{
self::error('Invalid posting key specified!');
}
}
public static function error($text)
{
file_put_contents(DF_INCLUDE_WEsB.'/touchnet.txt', $text, FILE_APPEND);
throw new \DF\Exception($text);
}
public static function getSettings()
{
static $settings;
if (!$settings)
{
$config = \Zend_Registry::get('config');
$settings = $config->services->touchnet;
}
return $settings;
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace DF\Service;
class Twilio
{
public static function getInstance()
{
static $twilio;
if (!$twilio)
{
$settings = self::loadSettings();
$http = new \Services_Twilio_TinyHttp('https://api.twilio.com', array('curlopts' => array(
CURLOPT_SSL_VERIFYPEER => false
)));
$twilio = new \Services_Twilio($settings['account_id'], $settings['auth_token'], '2010-04-01', $http);
}
return $twilio;
}
public static function loadSettings()
{
static $settings;
if (!$settings)
{
$config = \Zend_Registry::get('config');
$settings = $config->services->twilio->toArray();
}
return $settings;
}
public static function sms($number, $message)
{
$client = self::getInstance();
$settings = self::loadSettings();
$number = preg_replace("/[^0-9]/", "", $number);
if (strlen($number) > 10)
$number = substr($number, -10);
if ($number)
{
return $client->account->sms_messages->create(
$settings['from_number'],
$number,
$message
);
}
}
}

44
app/library/DF/Session.php Executable file
View File

@ -0,0 +1,44 @@
<?php
/**
* DF_Session:
* Extender for session management
*/
namespace DF;
class Session
{
public static function get($namespace = 'default')
{
return self::getNamespace($namespace);
}
public static function getNamespace($namespace = 'default')
{
static $sessions;
if ($sessions === NULL)
$sessions = array();
$session_name = self::getNamespaceName($namespace);
if (!isset($sessions[$session_name]))
$sessions[$session_name] = new \Zend_Session_Namespace($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

@ -0,0 +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();
}
}

215
app/library/DF/Url.php Normal file
View File

@ -0,0 +1,215 @@
<?php
namespace DF;
class Url
{
/**
* Returns the baseUrl
*
* @return string
*/
public static function baseUrl($include_domain = TRUE)
{
$config = \Zend_Registry::get('config');
if ($config->application->base_url && $include_domain === TRUE)
{
$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();
if ($include_domain)
return self::domain(TRUE).$base_url;
else
return $base_url;
}
}
public static function content($file_name = NULL)
{
if (defined('DF_URL_STATIC'))
$static_url_base = DF_URL_STATIC;
else
$static_url_base = self::baseUrl(FALSE).'/static';
if ($file_name !== NULL)
return $static_url_base.'/'.$file_name;
else
return $static_url_base;
}
public static function file($file_name = NULL)
{
if (defined('DF_UPLOAD_URL'))
{
$upload_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)
{
$domain = $_SERVER['HTTP_HOST'];
if($includeScheme)
$domain = 'http'.((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 's' : '').'://'.$domain;
return $domain;
}
/**
* 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;
}
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;
}
}

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