integrating google minify with zend framework - php

so I tried to integrate minify and zend framework
http://code.google.com/p/minify/
what I basically did was copy the contents of minify's index.php file to a zend action:
and changed the third line from
define('MINIFY_MIN_DIR', dirname(__FILE__));
to
define('MINIFY_MIN_DIR', 'Z:\wamp2\www\min');
which is where the minify folder is located
here's the full action:
public function test2Action()
{
define('MINIFY_MIN_DIR', 'Z:\wamp2\www\min');
// load config
require MINIFY_MIN_DIR . '/config.php';
// setup include path
set_include_path($min_libPath . PATH_SEPARATOR . get_include_path());
require 'Minify.php';
Minify::$uploaderHoursBehind = $min_uploaderHoursBehind;
Minify::setCache(
isset($min_cachePath) ? $min_cachePath : ''
,$min_cacheFileLocking
);
if ($min_documentRoot) {
$_SERVER['DOCUMENT_ROOT'] = $min_documentRoot;
} elseif (0 === stripos(PHP_OS, 'win')) {
Minify::setDocRoot(); // IIS may need help
}
$min_serveOptions['minifierOptions']['text/css']['symlinks'] = $min_symlinks;
if ($min_allowDebugFlag && isset($_GET['debug'])) {
$min_serveOptions['debug'] = true;
}
if ($min_errorLogger) {
require_once 'Minify/Logger.php';
if (true === $min_errorLogger) {
require_once 'FirePHP.php';
Minify_Logger::setLogger(FirePHP::getInstance(true));
} else {
Minify_Logger::setLogger($min_errorLogger);
}
}
// check for URI versioning
if (preg_match('/&\\d/', $_SERVER['QUERY_STRING'])) {
$min_serveOptions['maxAge'] = 31536000;
}
if (isset($_GET['g'])) {
// well need groups config
$min_serveOptions['minApp']['groups'] = (require MINIFY_MIN_DIR . '/groupsConfig.php');
}
if (isset($_GET['f']) || isset($_GET['g'])) {
// serve!
Minify::serve('MinApp', $min_serveOptions);
//echo Minify::combine(array('//css/DisplayHelpers/DisplayObject.css'),$min_serveOptions);
} else{
echo 'fail';
}
// action body
}
notice these lines...I added the combine line which is commented out
Minify::serve('MinApp', $min_serveOptions);
//echo Minify::combine(array('//css/DisplayHelpers/DisplayObject.css'),$min_serveOptions);
the
Minify::serve('MinApp', $min_serveOptions); line is in the original index.php....if I keep it there, it will not return the correct minifed files properly and instead return some crazy gibberish when I go to http://localhost/tester/test2?f=/css/DisplayHelpers/DisplayObject.css...
on the other hand, when I go to http://localhost/min?f=/css/DisplayHelpers/DisplayObject.css which uses minify's index.php it would work properly
on the other hand if I uncomment the combine line and comment the serve line it would also work properly but it won't do caching, etc
any ideas on how to resolve in using the normal serve method within the zend action so that I can use the cache?

Why an action plus there's already a Zend helper in that project.

Related

Integrate Composer with existing project autoloader

I'm updating a project and I've decided to update my Twig version. I deliberately haven't updated it in the past because of the fact you now need to use Composer, but I've eventually given in to this and decided to install a newer version.
However, it's messing around with my Autoload functions and not loading Twig properly, and I really don't want to have to use it. In a blank file with only the code to autoload Composer it works, so I know my autoloader is clashing. I can see that I'm going to have to use it to some degree, because Twig now requires it. I'm only interested in using it for third-party code, and I don't want to use it for anything else. So what I'm looking for is my own autoloader to try first, and then if I can't load a class by my own means, to try using the Composer autoloader. Third-party code exists in a subdirectory of "Lib". So With Twig, it sits in Lib/vendor/twig/twig/src.
At the moment, I'm checking the first part of the namespace and if it isn't matching my own, I'm trying to load the Composer autoload.php file in Lib/vendor/autoload.php, and then returning back out of my autoload function. But this doesn't seem to be finding the class.
Is what I'm trying to do actually possible? How would I approach something like this?
** Edit - Current Autoloader **
public static function autoloader($classname)
{
/* Separate by namespace */
$bits = explode('\\', ltrim($classname, '\\'));
$vendor = array_shift($bits);
/* If this doesn't belong to us, ignore it */
if ($vendor !== 'Site')
{
// We don't want to interfere here
if ($vendor == 'Forum')
return;
// Try to see if we can autoload with Composer, if not abort
include_once(SITE_ROOT.'include/Lib/vendor/autoload.php');
print_r(spl_autoload_functions ( ));
return;
}
$class = array_pop($bits);
$namespace = empty($bits) ? 'Site' : ('Site\\'.implode('\\', $bits));
$sources_dir = false;
$path = SITE_ROOT.'include/';
foreach (array_merge($bits, array($class)) as $i => $bit)
{
if ($i === 0 && $bit == 'Lib')
{
$bit = mb_strtolower($bit);
$sources_dir = true;
}
else if (preg_match("/^[a-z0-9]/", $bit)) // Applications only contain lowercase letters
{
if ($i === 0)
$path .= 'apps/';
else
$sources_dir = true;
}
else if ($i === 1 && ($bit == 'Api' || $bit == 'Cli' || $bit == 'Ajax')) // The API/CLI/AJAX interfaces have slightly different rules ....
{
$bit = mb_strtolower($bit);
$sources_dir = true;
}
else if ($sources_dir === false)
{
if ($i === 0)
{
$path .= 'components/';
}
else if ($i === 1 && $bit === 'Application')
{
// Do nothing
}
else
{
$path .= 'sources/';
}
$sources_dir = true;
}
$path .= $bit.'/';
}
/* Load it */
$path = \substr($path, 0, -1).'.php';
if (!file_exists($path))
{
$path = \substr($path, 0, -4).\substr($path, \strrpos($path, '/'));
if (!file_exists($path))
{
return false;
}
}
require_once($path);
if (interface_exists("{$namespace}\\{$class}", FALSE))
{
return;
}
/* Doesn't exist? */
if (!class_exists("{$namespace}\\{$class}", FALSE))
{
trigger_error("Class {$classname} could not be loaded. Ensure it has been properly prefixed and is in the correct namespace.", E_USER_ERROR);
}
}
It might be too late to load Composer's autoload.php within the custom autoload.
You should not worry too much about performance issues and just load both your custom autoloader and Composer's autoload one after to other. You can optimize a little by prioritizing these autoloaders based on which classes will you load more often (your own or those installed via Composer).
Also, your own/custom autoloader should only care about successful loading and not throw errors if something is not found. Leave that to PHP, this could help with compatibility with other autoloaders.

Slim Page loading Issues

So after fixing mustache and Apache perms I now have ran into an issue where the site will load the index page, but any page after that located in (the same place a index.html) /pages as it fails to load.
What you can see below is the index.php for Slim to do it's stuff. I can't really understand why the index page will load just fine but no other page will load. If you can point me in the right direction then it would be greatly appreciated.
Examples:
End User > myexample.com/
Location > myexample.com/pages/index.html
The above works just fine but if you look below, you should be able to understand my issue.
End User > myexample.com/info
Location > myexample.com/pages/info.html
The End User is what you see on the site, but the location is where the files belong.
Thanks in advance, Luke.
<?php
// Load up composer autoload, and instantiate the application.
require 'vendor/autoload.php';
$app = new \Slim\Slim;
// Register a singleton of the Mustache engine, and tell it to cache
$app->container->singleton('mustache', function () {
return new Mustache_Engine(array(
'cache' => 'storage',
'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__) . '/pages', array('extension' => '.html'))
));
});
// Helper function to render templates
function renderTemplate($name, $data = array()) {
global $app;
if (file_exists('config.php')) {
$data = (require 'config.php');
}
$data += array(
'resourceUri' => $app->request->getResourceUri() ?: 'index',
'request' => $app->request
);
return $app->mustache->loadTemplate($name)->render($data);
}
// Loads a page by the given name/path
function loadPage($path) {
global $app;
// Set up the base path
$f = 'pages/' . $path;
if (file_exists($f . '.html')) {
// If there's an HTML file, render the mustache template
return renderTemplate($path . '.html');
} elseif (file_exists($f . '.php')) {
// If there's a PHP file, return it
return (require $f . '.php');
} elseif ($path != '404') {
// Otherwise, go get the 404 page
return loadPage('404');
} else {
// But if the user doesn't have a 404 page made, return a plain 404
$app->halt(404);
}
}
// Index page
$app->get('/', function () use ($app) {
echo loadPage('index');
});
// Route to everything else
$app->get('/.*?', function () use ($app) {
// Get the current request path
$path = $app->request->getResourceUri();
// Make sure the user isn't trying to escape and do nasty things
if (!preg_match('/^[A-z\/\-\_]+$/', $path)) {
echo loadPage('404');
}
// Send the page off to get loaded
echo loadPage($path);
});
$app->run();
I think you'll find your problem isn't with Slim but rather with the custom functions you wrote to allow Slim to load Mustache templates.
I would highly recommend removing those functions and using the custom Slim Mustache view provided in the views directory of Slim-Extras repo. At that point, any issues with Slim can be more easily diagnosed as there won't be custom functions to debug.
NOTE: While the Slim-Extras repo is deprecated in favor of the Slim-Views repo, the custom Mustache view (which hasn't made it to the Slim-Views repo) should work fine.
For reference please see the Custom Views section of the Slim documentation.
UPDATE: I've been using Dearon's Slim Mustache library for integration with Slim View in a new app of mine and Justin Hileman's PHP implementation of Mustache. Both are highly recommended and simple to install and configure. Good luck!

CodeIgniter Checking Files

I'm writing a template_loader for my CodeIgniter project. As usual, I need several security layers for my templates. One of them, which is the very first one, is checking if the files exists or not.
Now, My Problem is: I can't configure what address to give to the template loader. When I use simple php function called 'include()', it works, but with my template_loader function, it fails to work.
Here is my actual page (index.php):
<?php
/**
Add the page-suitable template from in folder.
**/
$this->template_loader->load_template('inc/temp_one_col.php');
// include('inc/temp_one_col.php');
?>
And here is my class and template_loader:
class Template_loader
{
function load_template ($arg)
{
$base_name = basename($arg);
$CI =& get_instance();
if(file_exists($arg) === true)
{
echo 'it is also good.';
if (pathinfo($base_name, PATHINFO_EXTENSION) == 'php' ||
pathinfo($base_name, PATHINFO_EXTENSION) == 'html'
)
{
$file_name_check = substr($base_name, 0, 4);
if($file_name_check === TEMP_FILE_INDICATOR)
{
include($arg);
}
else
{
redirect($CI->base_url . '/error/show_problem');
}
}
else
{
redirect($CI->base_url . '/error/show_problem');
}
}
else
{
redirect($CI->base_url . '/error/show_problem');
}
}
}
Out of interest, what are you passing to the function as the $arg parameter?
Sounds like you just need to use the correct path to the file, which should be the absolute path to the file in the filesystem.
To get the absolute path you could create a new global variable in your sites index.php to point to your views folder.
webroot/index.php:
if (realpath('../application/views') !== FALSE)
{
$views_path =realpath('../application/views').'/';
define('VIEWSPATH', $views_path);
}
Now you can use this as the base for your $arg parameter VIEWSPATH.$path_to_file

Zend Framework Cron for FIFO Queue

I am trying to run a cron job in my application my set up is like this:
My zend application Version 1.12
inside my public/index.php
function Mylib_init_settings($settings, $environment)
{
if (getenv('LOCAL_ENV') && file_exists($serverConfigFile = __DIR__ . '/../application/configs/' . getenv('LOCAL_ENV') . '.ini')) {
$settings->addOverrideFile($serverConfigFile);
}
}
define('MYLIB_APPLICATION_ENV', 'production');
require __DIR__ . '/../library/Mylib/Application/start.php';
Inside Start.php
<?php
use Mylib\Config;
use Mylib\Config\Loader\SecondGeneration;
function mylib_trigger_hook($hook, $params = array())
{
$func = 'mylib_init_' . strtolower(trim($hook));
if (function_exists($func)) {
call_user_func_array($func, $params);
}
}
// ---------------------------------------------------------------------------------------------------------------------
// setup application constants
if (getenv('SELENIUM')) {
defined('MYLIB_APPLICATION_ENV')
?: define('MYLIB_APPLICATION_ENV', 'testing');
}
// should the application be bootstrapped?
defined('MYLIB_APPLICATION_BOOTSTRAP')
?: define('MYLIB_APPLICATION_BOOTSTRAP', true);
// should the application run?
defined('MYLIB_APPLICATION_CREATE')
?: define('MYLIB_APPLICATION_CREATE', true);
// should the application run?
defined('MYLIB_APPLICATION_RUN')
?: define('MYLIB_APPLICATION_RUN', true);
// maximum execution time
defined('MYLIB_APPLICATION_TIME_LIMIT')
?: define('MYLIB_APPLICATION_TIME_LIMIT', 0);
// path to application rooth
defined('MYLIB_APPLICATION_PATH_ROOT')
?: define('MYLIB_APPLICATION_PATH_ROOT', realpath(__DIR__ . '/../../../'));
// path to library
defined('MYLIB_APPLICATION_PATH_LIBRARY')
?: define('MYLIB_APPLICATION_PATH_LIBRARY', realpath(__DIR__ . '/../../'));
mylib_trigger_hook('constants');
// ---------------------------------------------------------------------------------------------------------------------
// limits the maximum execution time
set_time_limit(MYLIB_APPLICATION_TIME_LIMIT);
// ---------------------------------------------------------------------------------------------------------------------
// determine which configuration section, and overrides to load
$configSection = defined('MYLIB_APPLICATION_ENV') ?MYLIB_APPLICATION_ENV : null;
$configOverride = null;
$environmentFilename = MYLIB_APPLICATION_PATH_ROOT . '/environment';
if (file_exists($environmentFilename)) {
$ini = parse_ini_file($environmentFilename);
if ($ini === false) {
throw new \RuntimeException('Failed to parse enviroment file: ' . $environmentFilename);
}
if (!defined('MYLIB_APPLICATION_ENV')) {
// should have at least a config.section variable
if (!isset($ini['config.section'])) {
throw new \RuntimeException('\'config.section\' setting is missing in environment file');
}
$configSection = $ini['config.section'];
}
if (isset($ini['config.override'])) {
$configOverrideFilename = MYLIB_APPLICATION_PATH_ROOT . '/application/configs/' . $ini['config.override'] . '.ini';
if (!is_readable($configOverrideFilename)) {
throw new \RuntimeException(
sprintf('You have provided a config override file (%s), but it is not readable', $configOverrideFilename)
);
} else {
$configOverride = $configOverrideFilename;
}
}
}
defined('MYLIB_APPLICATION_ENV')
?: define('MYLIB_APPLICATION_ENV', $configSection);
static $allowedEnvironmnets = array(
'production',
'staging',
'testing',
'development',
);
if (!in_array(MYLIB_APPLICATION_ENV, $allowedEnvironmnets)) {
throw new \RuntimeException(
sprintf('Invalid environment %s provided. Must be either of: %s', MYLIB_APPLICATION_ENV, implode(', ', $allowedEnvironmnets))
);
}
macq_trigger_hook('environment', array(MYLIB_APPLICATION_ENV));
// ---------------------------------------------------------------------------------------------------------------------
// set the include path
set_include_path(MYLIB_APPLICATION_PATH_LIBRARY . PATH_SEPARATOR . get_include_path());
mylib_trigger_hook('includepath', array(get_include_path()));
// ---------------------------------------------------------------------------------------------------------------------
// enable PSR-0 autoloading
require_once MYLIB_APPLICATION_PATH_LIBRARY . '/Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance()
->setFallbackAutoloader(true);
// ---------------------------------------------------------------------------------------------------------------------
// load configuration settings, and if an override is specified, merge it
$settings = new SecondGeneration(
MYLIB_APPLICATION_PATH_ROOT,
MYLIB_APPLICATION_ENV,
MYLIB_APPLICATION_PATH_LIBRARY . '/MyLib/Application/configuration.ini'
);
if ($configOverride) {
$settings->addOverrideFile($configOverride);
}
// set up config file caching, this is a seperate cache then any application caches created!
if (isset($ini['config.cache.enabled']) && $ini['config.cache.enabled']) {
if (isset($ini['config.cache.dir']) && is_writable($ini['config.cache.dir'])) {
$configCache = new Zend_Cache_Core(array('automatic_serialization'=>true));
$backend = new Zend_Cache_Backend_File(array(
'cache_dir' => $ini['config.cache.dir'],
));
$configCache->setBackend($backend);
$settings->setCache($configCache);
unset($configCache, $backend);
} else {
throw new \RuntimeException(
sprintf('Configuration cache is enabled, but no correct cache dir is specified, or the specified directory is not writable')
);
}
}
// load configuration settings
Config::load($settings);
mylib_trigger_hook('settings', array($settings, MYLIB_APPLICATION_ENV));
// ---------------------------------------------------------------------------------------------------------------------
// create application and bootstrap
if (MYLIB_APPLICATION_CREATE) {
$application = new Zend_Application(Config::environment(), Config::config());
macq_trigger_hook('application', array($application));
if (MYLIB_APPLICATION_BOOTSTRAP) {
$application->bootstrap();
macq_trigger_hook('bootstrap', array($application));
}
// ---------------------------------------------------------------------------------------------------------------------
// run application?
if (MYLIB_APPLICATION_RUN) {
$application->run();
macq_trigger_hook('run', array($application));
}
}
What I did is :
I followed the following link:
http://www.magentozend.com/blog/2012/02/03/setting-up-cronjobs-for-zend-framework-envoirment/
what I did is create a "cron" folder at the level in which my application folders are present.
inside the folder created init.php file inside that I added my index.php code and start.php code.
and my controller file is as like this:
application/modules/myproject/controller/cronjop.php
inside the cron job file I just called init.php
by
require_once('/../../../../cron/init.php');
but the cron is not working can some one help me..
thanks in advance..
I see you miss the point of using Cron and Zend as well. Zend site is just normal site so you can use for example lynx browser to run the site.
*/10 * * * * lynx -dump http://www.myzendsite.com/mycontroller/mycronaction
just create My Controller add mycron Action and put in this method what you want cron to do. Lynx will open it as normal user would do. Cron will run lynx after some time.
The line */10 means every 10 minutes. You can fit it to your needs.
There are other ways to run php script for example via php parser or curl.
Check this tutorial

Website Structure for Small Site without DB

I'm trying to setup a system to minimize complexity for people updating the site as I will not be the main person updating daily content AND also provide clean URLs.
Since I am unable to use a DB, all of the content resides in one of two base folders (/private/content OR /private/utilities). For normal daily updates, the utilities (contains the page wrapper - header, nav, footer, etc.) folder wouldn't need to be accessed. This minimizes the amount of visible code to the daily editor.
I've created an array ($allowedContent) that has the list of valid sections that are accessible. The code tests against that array to verify that the user is not attempting to access inappropriate content. With the code below, these requests would be successful. Everything else would fail.
www.example.com/
www.example.com/popup/*
www.example.com/test
www.example.com/hello
www.example.com/foobar
My question is:
Is there anything that sticks out as a problem with this approach?
.htaccess
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
PHP
// parse the URL
$requestURI = explode('/', $_SERVER['REQUEST_URI']);
//print_r ($requestURI);
// a list of non-restricted dynamic content
$allowedContent = array("test", "hello", "foobar");
$allowAccess = false; // assume hackers :o
// determine the section
if (!$requestURI[1]) { // none defined - use root/home
$section = 'home';
$skin = true;
$allowAccess = true;
} elseif ($requestURI[1] == 'popup') { // popup - no skin
$section = $requestURI[2];
$skin = false;
$allowAccess = true;
} else {
if (in_array($requestURI[1], $allowedContent)) { // verify that the requested content is allowed / prevent someone from trying to hack the site
$section = $requestURI[1];
$skin = true;
$allowAccess = true;
} else { // this would be either a 404 or a user trying to access a restricted directory
echo "evil laugh"; // obviously, this would change to a 404 redirect
}
}
Added code where content is called
// call the relevant content pieces
if ($allowAccess == true) {
if ($skin == true ) {
// call wrapper part 1
include $_SERVER['DOCUMENT_ROOT'] . '/private/utilities/wrapperOpen.php';
// call aside
include $_SERVER['DOCUMENT_ROOT'] . '/private/utilities/header.php';
// call aside
include $_SERVER['DOCUMENT_ROOT'] . '/private/utilities/aside.php';
}
// call CONTENT (based on section)
include $_SERVER['DOCUMENT_ROOT'] . '/private/content/' . $section . '/index.php';
if ($skin == true ) {
// call branding
include $_SERVER['DOCUMENT_ROOT'] . '/private/utilities/branding.php';
// call footer
include $_SERVER['DOCUMENT_ROOT'] . '/private/utilities/footer.php';
// call wrapper part 2
include $_SERVER['DOCUMENT_ROOT'] . '/private/utilities/wrapperClose.php';
}
}
this would work.
you coyuld also look into using xml to store data, but you need to keep watch over system memory usage and loading time if the files get too large. sosplit them up where possible.
can’t you talk them into using a database? webhosting with database is cheap.

Categories