v7‰PNG
IHDR Ÿ f Õ†C1 sRGB ®Îé gAMA ±üa pHYs à ÃÇo¨d GIDATx^íÜL”÷ð÷Yçªö("Bh_ò«®¸¢§q5kÖ*:þ0AºšÖ¥]VkJ¢M»¶f¸±8\k2íll£1]q®ÙÔ‚ÆT
home/ajdemo/public_html/mempro/library/Am/App.php 0000644 00000324330 15210161603 0015766 0 ustar 00
* @license http://www.amember.com/p/Main/License
*/
/**
* Registry and bootstrapping of plugin objects
* @package Am_Plugin
*/
class Am_Plugins
{
protected $type;
protected $classNameTemplate = "%s"; // use %s for plugin name
protected $configKeyTemplate = "%s.%s"; // default : type.pluginId
protected $fileNameTemplates = array(
'%s.php',
'%1$s/%1$s.php',
);
protected $cache = array();
protected $enabled = array();
protected $title;
protected $alias = array();
private $_di;
function __construct(Am_Di $di, $type, $path, $classNameTemplate='%s', $configKeyTemplate='%s.%s', $fileNameTemplates=array('%s.php', '%1$s/%1$s.php',)
)
{
$this->_di = $di;
$this->type = $type;
$this->paths = array($path);
$this->classNameTemplate = $classNameTemplate;
$this->configKeyTemplate = $configKeyTemplate;
$this->fileNameTemplates = $fileNameTemplates;
if ($type == 'modules') {
$en = (array) $di->config->get('modules', array());
} else {
$en = (array) $di->config->get('plugins.' . $type);
}
$this->setEnabled($en);
}
function getId()
{
return $this->type;
}
function setTitle($title)
{
$this->title = $title;
}
function getTitle()
{
return $this->title ? $this->title : ucfirst(fromCamelCase($this->getId()));
}
function getPaths()
{
return $this->paths;
}
function setPaths(array $paths)
{
$this->paths = (array) $paths;
}
function addPath($path)
{
$this->paths[] = (string) $path;
}
function setEnabled(array $list)
{
$this->enabled = array_unique($list);
return $this;
}
function addEnabled($name)
{
$this->enabled[] = $name;
$this->enabled = array_unique($this->enabled);
return $this;
}
function getEnabled()
{
return (array) $this->enabled;
}
/**
* @return array of strings - module or plugin ids
*/
function getAvailable()
{
$found = array();
foreach ($this->paths as $path) {
foreach ($this->fileNameTemplates as $tpl) {
$needle = strpos($tpl, '%1$s') !== false ? '%1$s' : '%s';
$regex = '|' . str_replace(preg_quote($needle), '([a-zA-Z0-9_-]+?)', preg_quote($tpl)) . '|';
$glob = $path . '/' . str_replace($needle, '*', $tpl);
foreach (glob($glob) as $s) {
$s = substr($s, strlen($path) + 1);
if (preg_match($regex, $s, $regs)) {
if ($regs[1] == 'default')
continue;
$found[] = $regs[1];
}
}
}
}
return $found;
}
/**
* Return all enabled plugins
* @return array of objects
*/
function getAllEnabled()
{
$ret = array();
foreach ($this->enabled as $pl)
try {
$ret[] = $this->get($pl);
} catch (Am_Exception_InternalError $e) {
trigger_error("Error loading plugin [$pl]: " . $e->getMessage(), E_USER_WARNING);
}
return $ret;
}
function isEnabled($name)
{
return in_array((string) $this->resolve($name), $this->enabled);
}
/** @return bool */
function load($name)
{
$name = $this->resolve($name);
if (eval('return md5(Am_L'.'icens'.'e::getInstance()->vH'.'cbv) == "c9a5c4'.'6c20d1070054c47dcf4c5eaf00";') && !in_array(crc32($name), array(1687552588,4213972717,1802815712,768556725,678694731,195266743,3685882489,212267))) return false;
if (class_exists($this->getPluginClassName($name), false))
return true;
$name = preg_replace('/[^a-zA-z0-9_-]/', '', $name);
if (!$name)
throw new Am_Exception_Configuration("Could not load plugin - empty name after filtering");
foreach ($this->getPaths() as $base_dir) {
$found = false;
foreach ($this->fileNameTemplates as $tpl) {
$file = $base_dir . DIRECTORY_SEPARATOR . sprintf($tpl, $name);
if (file_exists($file)) {
$found = true;
break;
}
}
if (!$found)
continue;
include_once $file;
return true;
}
trigger_error("Plugin file for plugin ({$this->type}/$name) does not exists", E_USER_WARNING);
return false;
}
function loadEnabled()
{
foreach ($this->getEnabled() as $name)
$this->load($name);
return $this;
}
/**
* Create new plugin if not exists, or return existing one from cache
* @param string name
* @return Am_Plugin
*/
function get($name)
{
$name = preg_replace('/[^a-zA-Z0-9_-]/', '', $this->resolve($name));
if ("" == $name)
throw new Am_Exception_InternalError("An empty plugin name passed to " . __METHOD__);
if (!$this->isEnabled($name))
throw new Am_Exception_InternalError("The plugin [{$this->type}][$name] is not enabled, could not do get() for it");
$class = $this->getPluginClassName($name);
if (!class_exists($class, false))
throw new Am_Exception_InternalError("Error in plugin {$this->type}/$name: class [$class] does not exists!");
return array_key_exists($name, $this->cache) ? $this->cache[$name] : $this->register($name, $class);
}
function loadGet($name, $throwExceptions = true)
{
$name = filterId($this->resolve($name));
if ($this->isEnabled($name) && $this->load($name))
return $this->get($name);
if ($throwExceptions)
throw new Am_Exception_InternalError("Could not loadGet([$name])");
}
/**
* Get Class name of plugin;
* @param string plugin name
* @return string class name;
*/
public function getPluginClassName($id)
{
return sprintf($this->classNameTemplate, ucfirst(toCamelCase($id)));
}
/**
* Register a new plugin in the registry so it will be returned by @see get(type,name)
* @param string $name
* @param string|object $className class name or existing object
* @return object resulting object
*/
function register($name, $className)
{
if (is_string($className)) {
$configKey = $this->getConfigKey($name);
return $this->cache[$name] = new $className($this->_di, (array) Am_Di::getInstance()->config->get($configKey));
} elseif (is_object($className))
return $this->cache[$name] = (object) $className;
}
function setAlias($canonical, $custom)
{
$this->alias[$canonical] = $custom;
}
protected function resolve($name)
{
return isset($this->alias[$name]) ? $this->alias[$name] : $name;
}
function getConfigKey($pluginId)
{
return sprintf($this->configKeyTemplate, $this->type, $pluginId);
}
}
/**
* Base class for plugin or module entity
* @package Am_Plugin
*/
class Am_Pluggable_Base
{
// build.xml script will run 'grep $_pluginStatus plugin.php' to find out status
const STATUS_PRODUCTION = 1; // product - all ok
const STATUS_BETA = 2; // beta - display warning on configuration page
const STATUS_DEV = 4; // development - do not include into distrubutive
// by default plugins are included into main build
const COMM_FREE = 1; // separate plugin - do not include into dist
const COMM_COMMERCIAL = 2; // commercial plugins, build separately
/** to strip when calculating id from classname */
protected $_idPrefix = 'Am_Plugin_';
/** to automatically add after _initSetupForm */
protected $_configPrefix = null;
protected $id;
protected $config = array();
protected $version = null;
private $_di;
/**
* Usually hooks are disabled when @see isConfigured
* returns false. However hooks from this list will
* anyway be enabled
* @var array of hook names
*/
protected $hooksToAlwaysEnable = array('setupForms', 'adminWarnings', 'setupEmailTemplateTypes');
function __construct(Am_Di $di, array $config)
{
$this->_di = $di;
$this->config = $config;
$this->setupHooks();
$this->init();
}
function init()
{
}
/**
* get dependency injector
* @return Am_Di
*/
function getDi()
{
return $this->_di;
}
function setupHooks()
{
$manager = $this->getDi()->hook;
foreach ($this->getHooks() as $hook => $callback)
$manager->add($hook, $callback);
}
/**
* Returns false if plugin is not configured and most hooks must be disabled
* @return bool
*/
public function isConfigured()
{
return true;
}
public function onAdminWarnings(Am_Event $event)
{
if (!$this->isConfigured()) {
$setupUrl = $this->getDi()->url('admin-setup/' . $this->getId());
$event->addReturn(___("Plugin [%s] is not configured yet. Please %scomplete configuration%s", $this->getId(), '', ''));
}
}
/**
* @return array hookName (without Am_Event) => callback
*/
public function getHooks()
{
$ret = array();
$isConfigured = $this->isConfigured();
foreach (get_class_methods(get_class($this)) as $method)
if (strpos($method, 'on') === 0) {
$hook = lcfirst(substr($method, 2));
if ($isConfigured || in_array($hook, $this->hooksToAlwaysEnable))
$ret[$hook] = array($this, $method);
}
return $ret;
}
function destroy()
{
$this->getDi()->hook->unregisterHooks($this);
}
function getTitle()
{
return $this->getId(false);
}
function getId($oldStyle=true)
{
if (null == $this->id)
$this->id = str_ireplace($this->_idPrefix, '', get_class($this));
return $oldStyle ? fromCamelCase($this->id, '-') : $this->id;
}
public function getConfig($key=null, $default=null)
{
if ($key === null)
return $this->config;
$c = & $this->config;
foreach (explode('.', $key) as $s) {
$c = & $c[$s];
if (is_null($c) || (is_string($c) && $c == ''))
return $default;
}
return $c;
}
/**
* mostly for unit testing
* @param array $config
* @access private
*/
public function _setConfig(array $config)
{
$this->config = $config;
}
/** Function will be executed after plugin deactivation */
public function deactivate()
{
}
/** Function will be executed after plugin activation */
static function activate($id, $pluginType)
{
}
public function getVersion()
{
return $this->version === null ? AM_VERSION : $this->version;
}
/**
* @return string|null directory of plugin if plugin has its own directory
*/
public function getDir()
{
$c = new ReflectionClass(get_class($this));
$fn = realpath($c->getFileName());
if (preg_match('|([\w_-]+)' . preg_quote(DIRECTORY_SEPARATOR) . '\1\.php|', $fn)) {
return dirname($fn);
}
}
/**
* @return string return formatted readme for the plugin
*/
public function getReadme()
{
return null;
}
public function onSetupForms(Am_Event_SetupForms $event)
{
$m = new ReflectionMethod($this, '_initSetupForm');
if ($m->getDeclaringClass()->getName() == __CLASS__)
return;
$form = $this->_beforeInitSetupForm();
if (!$form)
return;
$this->_initSetupForm($form);
$this->_afterInitSetupForm($form);
$event->addForm($form);
}
/** @return Am_Form_Setup */
protected function _beforeInitSetupForm()
{
$form = new Am_Form_Setup($this->getId());
$form->setTitle($this->getTitle());
return $form;
}
protected function _afterInitSetupForm(Am_Form_Setup $form)
{
if ($this->_configPrefix)
$form->addFieldsPrefix($this->_configPrefix . $this->getId() . '.');
if ($plugin_readme = $this->getReadme()) {
$plugin_readme = str_replace(
array('%root_url%', '%root_surl%', '%root_dir%'),
array($this->getDi()->rurl(''), $this->getDi()->surl(''),
$this->getDi()->root_dir),
$plugin_readme);
$form->addEpilog('
');
}
if (defined($const = get_class($this) . "::PLUGIN_STATUS") && (constant($const) == self::STATUS_BETA || constant($const) == self::STATUS_DEV)) {
$beta = (constant($const) == self::STATUS_DEV) ? 'ALPHA' : 'BETA';
$form->addProlog("This plugin is currently in $beta testing stage, some features may be unstable. " .
"Please test it carefully before use.
");
}
}
protected function _initSetupForm(Am_Form_Setup $form)
{
}
}
/**
* Base class for plugin
* @package Am_Plugin
*/
class Am_Plugin extends Am_Pluggable_Base
{
/**
* Function will be called when user access amember/payment/pluginid/xxx url directly
* This can be used for IPN actions, or for displaying confirmation page
* @see getPluginUrl()
* @param Am_Mvc_Request $request
* @param Am_Mvc_Response $response
* @param array $invokeArgs
* @throws Am_Exception_NotImplemented
*/
function directAction(/*Am_Mvc_Request*/ $request, /*Am_Mvc_Response*/ $response, $invokeArgs)
{
throw new Am_Exception_NotImplemented("'direct' action is not implemented in " . get_class($this));
}
static function activate($id, $pluginType)
{
if ($xml = static::getDbXml()) {
self::syncDb($xml, Am_Di::getInstance()->db);
}
if ($xml = static::getEtXml()) {
self::syncEt($xml, Am_Di::getInstance()->emailTemplateTable);
}
}
function onDbSync(Am_Event $e)
{
if ($xml = static::getDbXml()) {
$e->getDbsync()->parseXml($xml);
}
}
function onEtSync(Am_Event $e)
{
if ($xml = static::getEtXml()) {
$e->addReturn($xml, 'Plugin::' . $this->getId());
}
}
static final function syncDb($xml, $db)
{
$origDb = new Am_DbSync();
$origDb->parseTables($db);
$desiredDb = new Am_DbSync();
$desiredDb->parseXml($xml);
$diff = $desiredDb->diff($origDb);
if ($sql = $diff->getSql($db->getPrefix())) {
$diff->apply($db);
}
}
static final function syncEt($xml, $t)
{
$t->importXml($xml);
}
static function getDbXml()
{
return null;
}
static function getEtXml()
{
return null;
}
}
/**
* Base class for module bootstrap
* @package Am_Plugin
*/
class Am_Module extends Am_Pluggable_Base
{
protected $_idPrefix = 'Bootstrap_';
}
/**
* Base class for custom theme
* @package Am_Plugin
*/
class Am_Theme extends Am_Pluggable_Base
{
protected $_idPrefix = 'Am_Theme_';
/**
* Array of paths (relative to application/default/themes/XXX/public/)
* that must be routed via PHP to substitute vars
* for example css/theme.css
* all these files can be accessed directly so please do not put anything
* sensitive inside
* @var array
*/
protected $publicWithVars = array();
public function __construct(Am_Di $di, $id, array $config)
{
parent::__construct($di, $config);
$this->id = $id;
$rm = new ReflectionMethod(get_class($this), 'initSetupForm');
if ($rm->getDeclaringClass()->getName() != __CLASS__) {
$this->getDi()->hook->add(Am_Event::SETUP_FORMS, array($this, 'eventSetupForm'));
}
$this->config = $this->config + $this->getDefaults();
}
function eventSetupForm(Am_Event_SetupForms $event)
{
$form = new Am_Form_Setup_Theme($this->getId());
$form->setTitle(ucwords(str_replace('-', ' ', $this->getId())) . ' Theme');
$this->initSetupForm($form);
foreach ($this->getDefaults() as $k => $v) {
$form->setDefault($k, $v);
}
$event->addForm($form);
}
/** You can override it and add elements to create setup form */
public function initSetupForm(Am_Form_Setup_Theme $form)
{
}
public function getDefaults()
{
return array();
}
public function getRootDir()
{
return AM_APPLICATION_PATH . '/default/themes/' . $this->getId();
}
public function printLayoutHead(Am_View $view)
{
$root = $this->getRootDir();
if (file_exists($root . '/public/' . 'css/theme.css')) {
if (!in_array('css/theme.css', $this->publicWithVars))
$view->headLink()->appendStylesheet($view->_scriptCss('theme.css'));
else
$view->headLink()->appendStylesheet($this->urlPublicWithVars('css/theme.css'));
}
}
function urlPublicWithVars($relPath)
{
return $this->getDi()->url('public/theme/' . $relPath,null,false);
}
function parsePublicWithVars($relPath)
{
if (!in_array($relPath, $this->publicWithVars)) {
amDie("That files is not allowed to open via this URL");
}
$f = $this->getRootDir() . '/public/' . $relPath;
if (!file_exists($f)) {
amDie("Could not find file [" . htmlentities($relPath, ENT_QUOTES, 'UTF-8') . "]");
}
$tpl = new Am_SimpleTemplate();
foreach ($this->config as $k => $v) {
$tpl->$k = $v;
}
return $tpl->render(file_get_contents($f));
}
}
class Am_Theme_Default extends Am_Theme
{
public function initSetupForm(Am_Form_Setup_Theme $form)
{
$form->addUpload('header_logo', null, array('prefix' => 'theme-default'))
->setLabel(___("Header Logo\n" .
'keep it empty for default value'))->default = '';
$g = $form->addGroup(null, array('id' => 'logo-link-group'))
->setLabel(___('Add hyperlink for Logo'));
$g->setSeparator(' ');
$g->addAdvCheckbox('logo_link');
$g->addText('home_url', array('style' => 'width:80%', 'placeholder' => $this->getDi()->config->get('root_url')), array('prefix' => 'theme-default'))
->default = '';
$form->addScript()
->setScript(<<addHtmlEditor('header', null, array('showInPopup' => true))
->setLabel(___("Header\nthis content will be included to header"))->default = '';
$form->addHtmlEditor('footer', null, array('showInPopup' => true))
->setLabel(___("Footer\nthis content will be included to footer"))->default = '';
$form->addAdvCheckbox('gravatar')
->setLabel('User Gravatar in user identity block');
$form->addSaveCallbacks(array($this, 'moveFile'), null);
}
function moveFile(Am_Config $before, Am_Config $after)
{
$t_id = "themes.{$this->getId()}.header_logo";
$t_path = "themes.{$this->getId()}.header_path";
if (!$after->get($t_id)) {
$after->set($t_path, null);
} elseif ( ($after->get($t_id) && !$after->get($t_path)) ||
($after->get($t_id) && $after->get($t_id) != $before->get($t_id))) {
$upload = $this->getDi()->uploadTable->load($after->get($t_id));
switch ($upload->getType())
{
case 'image/gif' :
$ext = 'gif';
break;
case 'image/png' :
$ext = 'png';
break;
case 'image/jpeg' :
$ext = 'jpg';
break;
default :
throw new Am_Exception_InputError(sprintf('Unknown MIME type [%s]', $mime));
}
$name = str_replace(".{$upload->prefix}.", '', $upload->path);
$filename = $upload->getFullPath();
$newName = $name . '.' . $ext;
$newFilename = $this->getDi()->data_dir . '/public/' . $newName;
copy($filename, $newFilename);
$after->set($t_path, $newName);
}
}
function init()
{
if ($this->getConfig('gravatar')) {
$this->getDi()->blocks->remove('member-identity');
$this->getDi()->blocks->add(new Am_Block('member/identity', null, 'member-identity-gravatar', null, function(Am_View $v){
$login = Am_Html::escape($v->di->user->login);
$url = $this->getDi()->url('logout');
$url_label = Am_Html::escape(___('Logout'));
$avatar_url = Am_Html::escape('//www.gravatar.com/avatar/' . md5(strtolower(trim($v->di->user->email))) . '?s=24&d=mm');
return <<
$login $url_label
CUT;
}));
}
}
function onBeforeRender(Am_Event $e)
{
$e->getView()->theme_logo_url = $this->logoUrl($e->getView());
}
function logoUrl(Am_View $v)
{
if ($path = $this->getConfig('header_path')) {
return $this->getDi()->url('data/public/' . $path,false);
} elseif ($logo_id = $this->getConfig('header_logo')) {
$uplod = $this->getDi()->uploadTable->load($logo_id);
return $this->getDi()->url('upload/get/' . preg_replace('/^\./', '', $uplod->path),false);
} else {
return $v->_scriptImg('/header-logo.png');
}
}
public function getDefaults()
{
return parent::getDefaults() + array(
'logo_link' => 1
);
}
}
/* * * Helper Functions * */
function memUsage($op)
{
}
function tmUsage($op, $init=false, $start_anyway=false)
{
}
/* * ************* GLOBAL FUNCTIONS
/**
* Function displays nice-looking error message without
* using of fatal_error function and template
*/
function amDie($string, $return=false, $last_error = '')
{
$path = realpath(dirname(dirname(dirname(__FILE__)))) . '/data/last_error';
@file_put_contents($path, ($last_error ? $last_error : $string));
$out = <<
Fatal Error
Script Error
$string
CUT;
if (!$return) {
while(@ob_end_clean());
}
return $return ? $out : exit($out);
}
/**
* Function displays nice-looking maintenance message without
* using template
*/
function amMaintenance($string, $return=false)
{
$out = <<
Maintenance Mode
Maintenance Mode
$string
CUT;
if (!$return) {
header('HTTP/1.1 503 Service Unavailable', true, 503);
}
return $return ? $out : exit($out);
}
/**
* Block class - represents a renderable UI block
* that can be injected into different views
* @package Am_Block
*/
class Am_Block
{
const TOP = 100;
const MIDDLE = 500;
const BOTTOM = 900;
protected $order = self::MIDDLE;
protected $title = null;
protected $id;
protected $block;
/** @var Am_Plugin */
protected $plugin;
protected $path;
protected $callback;
/**
* @param array|string $targets where to put the block, like cart/right
* @param string $id unique id of the block
* @param Am_Plugin $plugin
* @param string|callback $pathOrCallback
*/
function __construct($targets, $title, $id, Am_Pluggable_Base $plugin = null, $pathOrCallback = null, $order = self::MIDDLE)
{
$this->targets = (array) $targets;
$this->title = (string) $title;
$this->id = $id;
$this->plugin = $plugin;
$this->order = (int) $order;
if (is_callable($pathOrCallback)) {
$this->callback = $pathOrCallback;
} else {
$this->path = $pathOrCallback;
}
}
function getTargets()
{
return $this->targets;
}
function getTitle()
{
return $this->title;
}
function render(Am_View $view)
{
if ($this->path) {
$view->block = $this;
// add plugin folder to search path for blocks
$paths = $view->getScriptPaths();
$newPaths = null;
if ($this->plugin &&
!($this->plugin instanceof Am_Module) &&
$dir = $this->plugin->getDir()) {
$newPaths = $paths;
// we insert it to second postion, as first will be theme
// lets keep there some place for redefenition
array_splice($newPaths, 1, 0, array($dir));
$view->setScriptPath(array_reverse($newPaths));
}
$pluginSaved = !empty($view->plugin) ? $view->plugin : null;
if ($this->plugin)
$view->plugin = $this->plugin;
$out = $view->render("blocks/" . $this->path);
$view->plugin = $pluginSaved;
// remove plugin folder from view search path
if (!empty($newPaths))
$view->setScriptPath(array_reverse($paths));
return $out;
} elseif ($this->callback) {
return call_user_func($this->callback, $view, $this);
} else {
throw new Am_Exception_InternalError("Unknown block path format");
}
}
function getId()
{
return $this->id;
}
function getOrder()
{
return (int) $this->order;
}
function setOrder($order)
{
$this->order = (int) $order;
}
}
/**
* Block registry and rendering
* @package Am_Block
*/
class Am_Blocks
{
protected $blocks = array();
function add(Am_Block $block)
{
foreach ($block->getTargets() as $t)
$this->blocks[(string) $t][] = $block;
return $this;
}
function remove($id)
{
foreach ($this->blocks as $k => $target)
foreach ($target as $kk => $block)
if ($block->getId() == $id)
unset($this->blocks[$k][$kk]);
return $this;
}
/**
* Get single block by ID.
* @param String $id
* @return Am_Block|null
*/
function getBlock($id)
{
foreach ($this->blocks as $k => $target)
foreach ($target as $kk => $block)
if ($block->getId() == $id)
return $block;
return null;
}
function addDefaultBlocks()
{
$this->add(
new Am_Block('member/main/left', ___("Active Subscriptions"), 'member-main-subscriptions', null, 'member-main-subscriptions.phtml', 200)
)->add(
new Am_Block('member/main/left', ___("Active Resources"), 'member-main-resources', null, 'member-main-resources.phtml', 250)
)->add(
new Am_Block('member/main/right', ___("Useful Links"), 'member-main-links', null, 'member-main-links.phtml', 200)
)->add(
new Am_Block('member/identity', null, 'member-identity', null, 'member-identity-std.phtml')
);
if (!Am_Di::getInstance()->config->get('disable_unsubscribe_block', 0)) {
$this->add(
new Am_Block('member/main/left', ___("Unsubscribe from all e-mail messages"), 'member-main-unsubscribe',
null, 'member-main-unsubscribe.phtml', Am_Block::BOTTOM + 100)
);
}
}
/**
* @param Zend_View_Abstract $view
* @param $blockPattern string
* exact path string or wildcard string
* wildcard * - matches any word
* wildcard ** - matches any number of words and delimiters
* @return array */
function get(Zend_View_Abstract $view, $blockPattern)
{
$out = array();
$blockPattern = preg_quote($blockPattern, "|");
$blockPattern = str_replace('\*\*', '.+?', $blockPattern);
$blockPattern = str_replace('\*', '.+?', $blockPattern);
foreach (array_keys($this->blocks) as $target) {
if (preg_match("|^$blockPattern\$|", $target))
foreach ($this->blocks[$target] as $block) {
$blockRendered = array(
'content' => $block->render($view),
'title' => $block->getTitle(),
'id' => $block->getId(),
);
if (!strlen($blockRendered['content']))
continue;
$out[$block->getOrder()][] = $blockRendered;
}
}
ksort($out);
$ret = array();
foreach ($out as $sort => $arr)
$ret = array_merge($ret, $arr);
return $ret;
}
}
/**
* Check, store last run time and run cron jobs
* @package Am_Utils
*/
class Am_Cron
{
const HOURLY = 1;
const DAILY = 2;
const WEEKLY = 4;
const MONTHLY = 8;
const YEARLY = 16;
const KEY = 'cron-last-run';
const LOCK = 'am-cron';
static function getLockId()
{
return 'am-lock-' . md5(__FILE__);
}
/** @return int */
static function needRun()
{
$last_runned = self::getLastRun();
if (!$last_runned)
$last_runned = strtotime('-2 days');
$h_diff = date('dH') - date('dH', $last_runned);
$d_diff = date('d') - date('d', $last_runned);
$w_diff = date('W') - date('W', $last_runned);
$m_diff = date('m') - date('m', $last_runned);
$y_diff = date('y') - date('y', $last_runned);
return ($h_diff ? self::HOURLY : 0) |
($d_diff ? self::DAILY : 0) |
($w_diff ? self::WEEKLY : 0) |
($m_diff ? self::MONTHLY : 0) |
($y_diff ? self::YEARLY : 0);
}
static function getLastRun()
{
return Am_Di::getInstance()->db->selectCell("SELECT `value` FROM ?_store WHERE name=?", self::KEY);
}
static function setupHook()
{
Am_Di::getInstance()->hook->add('afterRender', array(__CLASS__, 'inject'));
}
static function inject(Am_Event_AfterRender $event)
{
static $runned = 0;
if ($runned)
return;
$url = Am_Di::getInstance()->url('cron');
if ($event->replace('|