Пример #1
0
/**
 * Zikula_View function to display a preview image from a theme
 *
 * Available parameters:
 *  - name       name of the theme to display the preview image for
 *  - name       if set, the id assigned to the image
 *  - size         if set, the size of the image to use from small, medium, large (optional: default 'medium')
 *  - assign     if set, the title will be assigned to this variable
 *
 * Example
 * {previewimage name=andreas08 size=large}
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @see    function.title.php::smarty_function_previewimage()
 *
 * @return string The markup to display the theme image.
 */
function smarty_function_previewimage($params, Zikula_View $view)
{
    if (!isset($params['name'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('previewimage', 'name')));
        return false;
    }
    if (!isset($params['size']) || !in_array($params['size'], array('large', 'medium', 'small'))) {
        $params['size'] = 'medium';
    }
    $idstring = '';
    if (isset($params['id'])) {
        $idstring = " id=\"{$params['id']}\"";
    }
    $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($params['name']));
    $theme = ThemeUtil::getTheme($themeinfo['name']);
    $themePath = null === $theme ? "themes/{$themeinfo['directory']}/images" : $theme->getRelativePath() . '/Resources/public/images';
    if (file_exists("{$themePath}/preview_{$params['size']}.png")) {
        $filesrc = "{$themePath}/preview_{$params['size']}.png";
    } else {
        $filesrc = "system/ThemeModule/Resources/public/images/preview_{$params['size']}.png";
    }
    $markup = "<img{$idstring} src=\"{$filesrc}\" alt=\"\" />";
    if (isset($params['assign'])) {
        $view->assign($params['assign'], $markup);
    } else {
        return $markup;
    }
}
Пример #2
0
    /**
     * display theme changing user interface
     */
    public function main()
    {
        // check if theme switching is allowed
        if (!System::getVar('theme_change')) {
            LogUtil::registerError($this->__('Notice: Theme switching is currently disabled.'));
            $this->redirect(ModUtil::url('Users', 'user', 'main'));
        }

        if (!SecurityUtil::checkPermission('Theme::', '::', ACCESS_COMMENT)) {
            return LogUtil::registerPermissionError();
        }

        // get our input
        $startnum = FormUtil::getPassedValue('startnum', isset($args['startnum']) ? $args['startnum'] : 1, 'GET');

        // we need this value multiple times, so we keep it
        $itemsperpage = $this->getVar('itemsperpage');

        // get some use information about our environment
        $currenttheme = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));

        // get all themes in our environment
        $allthemes = ThemeUtil::getAllThemes(ThemeUtil::FILTER_USER);

        $previewthemes = array();
        $currentthemepic = null;
        foreach ($allthemes as $key => $themeinfo) {
            $themename = $themeinfo['name'];
            if (file_exists($themepic = 'themes/'.DataUtil::formatForOS($themeinfo['directory']).'/images/preview_medium.png')) {
                $themeinfo['previewImage'] = $themepic;
                $themeinfo['largeImage'] = 'themes/'.DataUtil::formatForOS($themeinfo['directory']).'/images/preview_large.png';
            } else {
                $themeinfo['previewImage'] = 'system/Theme/images/preview_medium.png';
                $themeinfo['largeImage'] = 'system/Theme/images/preview_large.png';
            }
            if ($themename == $currenttheme['name']) {
                $currentthemepic = $themepic;
                unset($allthemes[$key]);
            } else {
                $previewthemes[$themename] = $themeinfo;
            }
        }

        $previewthemes = array_slice($previewthemes, $startnum-1, $itemsperpage);

        $this->view->setCaching(Zikula_View::CACHE_DISABLED);

        $this->view->assign('currentthemepic', $currentthemepic)
                   ->assign('currenttheme', $currenttheme)
                   ->assign('themes', $previewthemes)
                   ->assign('defaulttheme', ThemeUtil::getInfo(ThemeUtil::getIDFromName(System::getVar('Default_Theme'))));

        // assign the values for the pager plugin
        $this->view->assign('pager', array('numitems' => sizeof($allthemes),
                                           'itemsperpage' => $itemsperpage));

        // Return the output that has been generated by this function
        return $this->view->fetch('theme_user_main.tpl');
    }
Пример #3
0
    /**
     * Retrieves default configuration array for HTML Purifier.
     *
     * @return array HTML Purifier default configuration settings.
     */
    private static function _getpurifierdefaultconfig()
    {
        $purifierDefaultConfig = HTMLPurifier_Config::createDefault();
        $purifierDefaultConfigValues = $purifierDefaultConfig->def->defaults;

        $config = array();

        foreach ($purifierDefaultConfigValues as $key => $val) {
            $keys = explode(".", $key, 2);

            $config[$keys[0]][$keys[1]] = $val;
        }

        $charset = ZLanguage::getEncoding();
        if (strtolower($charset) != 'utf-8') {
            // set a different character encoding with iconv
            $config['Core']['Encoding'] = $charset;
            // Note that HTML Purifier's support for non-Unicode encodings is crippled by the
            // fact that any character not supported by that encoding will be silently
            // dropped, EVEN if it is ampersand escaped.  If you want to work around
            // this, you are welcome to read docs/enduser-utf8.html in the full package for a fix,
            // but please be cognizant of the issues the "solution" creates (for this
            // reason, I do not include the solution in this document).
        }

        // determine doctype of current theme
        // supported doctypes include:
        //
        // HTML 4.01 Strict
        // HTML 4.01 Transitional
        // XHTML 1.0 Strict
        // XHTML 1.0 Transitional (default)
        // XHTML 1.1
        //
        // TODO - we need a new theme field for doctype declaration
        // for now we will use non-strict modes
        $currentThemeID = ThemeUtil::getIDFromName(UserUtil::getTheme());
        $themeInfo = ThemeUtil::getInfo($currentThemeID);
        $useXHTML = (isset($themeInfo['xhtml']) && $themeInfo['xhtml']) ? true : false;

        // as XHTML 1.0 Transitional is the default, we only set HTML (for now)
        if (!$useXHTML) {
            $config['HTML']['Doctype'] = 'HTML 4.01 Transitional';
        }

        // allow nofollow and imageviewer to be used as document relationships in the rel attribute
        // see http://htmlpurifier.org/live/configdoc/plain.html#Attr.AllowedRel
        $config['Attr']['AllowedRel'] = array('nofollow' => true, 'imageviewer' => true, 'lightbox' => true);

        // allow Youtube by default
        $config['Filter']['YouTube'] = false; // technically deprecated in favour of HTML.SafeEmbed and HTML.Object

        // general enable for embeds and objects
        $config['HTML']['SafeObject'] = true;
        $config['Output']['FlashCompat'] = true;
        $config['HTML']['SafeEmbed'] = true;

        return $config;
    }
Пример #4
0
/**
 * Smarty function to display the theme info
 *
 * Example
 * {themeinfo}
 *
 * @see          function.themeinfo.php::smarty_function_themeinfo()
 * @param        array       $params      All attributes passed to this function from the template
 * @param        object      $smarty     Reference to the Smarty object
 * @return       string      the themeinfo
 */
function smarty_function_themeinfo($params, $smarty)
{
    LogUtil::log(__f('Warning! Template plugin {%1$s} is deprecated, please use {%2$s} instead.', array('themeinfo', '$themeinfo')), E_USER_DEPRECATED);
    $thistheme = UserUtil::getTheme();
    $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($thistheme));
    $themecredits = '<!-- ' . __f('Theme: %1$s by %2$s - %3$s', array(DataUtil::formatForDisplay($themeinfo['display']), DataUtil::formatForDisplay($themeinfo['author']), DataUtil::formatForDisplay($themeinfo['contact']))) . ' -->';
    return $themecredits;
}
Пример #5
0
 /**
  * Constructor.
  *
  * @param Zikula_ServiceManager $serviceManager ServiceManager.
  * @param string                $themeName      Theme name.
  */
 public function __construct(Zikula_ServiceManager $serviceManager, $themeName)
 {
     // store our theme information
     $this->themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($themeName));
     // prevents any case mismatch
     $themeName = $this->themeinfo['name'];
     foreach (array('name', 'directory', 'version', 'state', 'xhtml') as $key) {
         $this->{$key} = $this->themeinfo[$key];
     }
     parent::__construct($serviceManager);
     if ($this->themeinfo['i18n']) {
         ZLanguage::bindThemeDomain($this->name);
         // property for {gt} template plugin to detect language domain
         $this->domain = ZLanguage::getThemeDomain($this->name);
     } else {
         $this->domain = null;
     }
     EventUtil::attachCustomHandlers("themes/{$themeName}/EventHandlers");
     EventUtil::attachCustomHandlers("themes/{$themeName}/lib/{$themeName}/EventHandlers");
     $event = new \Zikula\Core\Event\GenericEvent($this);
     $this->eventManager->dispatch('theme.preinit', $event);
     // change some base settings from our parent class
     // template compilation
     $this->compile_dir = CacheUtil::getLocalDir('Theme_compiled');
     $this->compile_check = ModUtil::getVar('ZikulaThemeModule', 'compile_check');
     $this->force_compile = ModUtil::getVar('ZikulaThemeModule', 'force_compile');
     // template caching
     $this->cache_dir = CacheUtil::getLocalDir('Theme_cache');
     $this->caching = (int) ModUtil::getVar('ZikulaThemeModule', 'enablecache');
     //if ($this->caching) {
     //    $this->cache_modified_check = true;
     //}
     // if caching and is not an admin controller
     if ($this->caching && strpos($this->type, 'admin') !== 0) {
         $modulesnocache = array_filter(explode(',', ModUtil::getVar('ZikulaThemeModule', 'modulesnocache')));
         if (in_array($this->toplevelmodule, $modulesnocache)) {
             $this->caching = Zikula_View::CACHE_DISABLED;
         }
     } else {
         $this->caching = Zikula_View::CACHE_DISABLED;
     }
     // halt caching for write operations to prevent strange things happening
     if (isset($_POST) && count($_POST) != 0) {
         $this->caching = Zikula_View::CACHE_DISABLED;
     }
     // and also for GET operations with csrftoken/authkey
     if (isset($_GET['csrftoken']) || isset($_GET['authkey'])) {
         $this->caching = Zikula_View::CACHE_DISABLED;
     }
     $this->cache_lifetime = ModUtil::getVar('ZikulaThemeModule', 'cache_lifetime');
     if (!$this->homepage) {
         $this->cache_lifetime = ModUtil::getVar('ZikulaThemeModule', 'cache_lifetime_mods');
     }
     // assign all our base template variables
     $this->_base_vars();
     // define the plugin directories
     $this->_plugin_dirs();
     // load the theme configuration
     $this->load_config();
     // check for cached output
     // turn on caching, check for cached output and then disable caching
     // to prevent blocks from being cached
     if ($this->caching && $this->is_cached($this->themeconfig['page'], $this->cache_id)) {
         $this->display($this->themeconfig['page'], $this->cache_id);
         System::shutdown();
     }
     // register page vars output filter
     $this->load_filter('output', 'pagevars');
     // register short urls output filter
     if (System::getVar('shorturls')) {
         $this->load_filter('output', 'shorturls');
     }
     // register trim whitespace output filter if requried
     if (ModUtil::getVar('ZikulaThemeModule', 'trimwhitespace')) {
         $this->load_filter('output', 'trimwhitespace');
     }
     $this->load_filter('output', 'asseturls');
     $event = new \Zikula\Core\Event\GenericEvent($this);
     $this->eventManager->dispatch('theme.init', $event);
     $this->startOutputBuffering();
 }
Пример #6
0
 /**
  * Constructor.
  *
  * @param Zikula_ServiceManager $serviceManager ServiceManager.
  * @param string                $moduleName     Module name ("zikula" for system plugins).
  * @param integer|null          $caching        Whether or not to cache (Zikula_View::CACHE_*) or use config variable (null).
  */
 public function __construct(Zikula_ServiceManager $serviceManager, $moduleName = '', $caching = null)
 {
     $this->serviceManager = $serviceManager;
     $this->eventManager = $this->serviceManager->get('event_dispatcher');
     $this->request = \ServiceUtil::get('request');
     // set the error reporting level
     $this->error_reporting = isset($GLOBALS['ZConfig']['Debug']['error_reporting']) ? $GLOBALS['ZConfig']['Debug']['error_reporting'] : E_ALL;
     $this->error_reporting &= ~E_USER_DEPRECATED;
     $this->allow_php_tag = true;
     // get variables from input
     $module = FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $type = FormUtil::getPassedValue('type', 'user', 'GETPOST', FILTER_SANITIZE_STRING);
     $func = FormUtil::getPassedValue('func', 'main', 'GETPOST', FILTER_SANITIZE_STRING);
     // set vars based on the module structures
     $this->homepage = PageUtil::isHomepage();
     $this->type = strtolower(!$this->homepage ? $type : System::getVar('starttype'));
     $this->func = strtolower(!$this->homepage ? $func : System::getVar('startfunc'));
     // Initialize the module property with the name of
     // the topmost module. For Hooks, Blocks, API Functions and others
     // you need to set this property to the name of the respective module!
     $this->toplevelmodule = ModUtil::getName();
     if (!$moduleName) {
         $moduleName = $this->toplevelmodule;
     }
     $this->modinfo = ModUtil::getInfoFromName($moduleName);
     $this->module = array($moduleName => $this->modinfo);
     // initialise environment vars
     $this->language = ZLanguage::getLanguageCode();
     $this->baseurl = System::getBaseUrl();
     $this->baseuri = System::getBaseUri();
     // system info
     $this->themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));
     $this->theme = $theme = $this->themeinfo['directory'];
     $themeBundle = ThemeUtil::getTheme($this->themeinfo['name']);
     //---- Plugins handling -----------------------------------------------
     // add plugin paths
     switch ($this->modinfo['type']) {
         case ModUtil::TYPE_MODULE:
             $mpluginPathNew = "modules/" . $this->modinfo['directory'] . "/Resources/views/plugins";
             $mpluginPath = "modules/" . $this->modinfo['directory'] . "/templates/plugins";
             break;
         case ModUtil::TYPE_SYSTEM:
             $mpluginPathNew = "system/" . $this->modinfo['directory'] . "/Resources/views/plugins";
             $mpluginPath = "system/" . $this->modinfo['directory'] . "/templates/plugins";
             break;
         default:
             $mpluginPathNew = "system/" . $this->modinfo['directory'] . "/Resources/views/plugins";
             $mpluginPath = "system/" . $this->modinfo['directory'] . "/templates/plugins";
     }
     // add standard plugin search path
     $this->plugins_dir = array();
     $this->addPluginDir('config/plugins');
     // Official override
     $this->addPluginDir('lib/legacy/viewplugins');
     // Core plugins
     $this->addPluginDir(isset($themeBundle) ? $themeBundle->getRelativePath() . '/plugins' : "themes/{$theme}/plugins");
     // Theme plugins
     $this->addPluginDir('plugins');
     // Smarty core plugins
     $this->addPluginDir($mpluginPathNew);
     // Plugins for current module
     $this->addPluginDir($mpluginPath);
     // Plugins for current module
     // check if the 'type' parameter in the URL is admin or adminplugin
     $legacyControllerType = FormUtil::getPassedValue('lct', 'user', 'GETPOST', FILTER_SANITIZE_STRING);
     if ($type === 'admin' || $type === 'adminplugin' || $legacyControllerType === 'admin') {
         // include plugins of the Admin module to the plugins_dir array
         if (!$this instanceof Zikula_View_Theme) {
             $this->addPluginDir('system/AdminModule/Resources/views/plugins');
         } else {
             $this->load_filter('output', 'admintitle');
         }
     }
     // theme plugins module overrides
     $themePluginsPath = isset($themeBundle) ? $themeBundle->getRelativePath() . '/modules/$moduleName/plugins' : "themes/{$theme}/templates/modules/{$moduleName}/plugins";
     $this->addPluginDir($themePluginsPath);
     //---- Cache handling -------------------------------------------------
     if ($caching && in_array((int) $caching, array(0, 1, 2))) {
         $this->caching = (int) $caching;
     } else {
         $this->caching = (int) ModUtil::getVar('ZikulaThemeModule', 'render_cache');
     }
     $this->compile_id = '';
     $this->cache_id = '';
     // template compilation
     $this->compile_dir = CacheUtil::getLocalDir('view_compiled');
     $this->compile_check = ModUtil::getVar('ZikulaThemeModule', 'render_compile_check');
     $this->force_compile = ModUtil::getVar('ZikulaThemeModule', 'render_force_compile');
     // template caching
     $this->cache_dir = CacheUtil::getLocalDir('view_cache');
     $this->cache_lifetime = ModUtil::getVar('ZikulaThemeModule', 'render_lifetime');
     $this->expose_template = ModUtil::getVar('ZikulaThemeModule', 'render_expose_template') == true ? true : false;
     // register resource type 'z' this defines the way templates are searched
     // during {include file='my_template.tpl'} this enables us to store selected module
     // templates in the theme while others can be kept in the module itself.
     $this->register_resource('z', array('Zikula_View_Resource', 'z_get_template', 'z_get_timestamp', 'z_get_secure', 'z_get_trusted'));
     // set 'z' as default resource type
     $this->default_resource_type = 'z';
     // process some plugins specially when Render cache is enabled
     if (!$this instanceof Zikula_View_Theme && $this->caching) {
         $this->register_nocache_plugins();
     }
     // register the 'nocache' block to allow dynamic zones caching templates
     $this->register_block('nocache', array('Zikula_View_Resource', 'block_nocache'), false);
     // For ajax requests we use the short urls filter to 'fix' relative paths
     if ($this->serviceManager->get('zikula')->getStage() & Zikula_Core::STAGE_AJAX && System::getVar('shorturls')) {
         $this->load_filter('output', 'shorturls');
     }
     // register prefilters
     $this->register_prefilter('z_prefilter_add_literal');
     $this->register_prefilter('z_prefilter_gettext_params');
     //$this->register_prefilter('z_prefilter_notifyfilters');
     // assign some useful settings
     $this->assign('homepage', $this->homepage)->assign('modinfo', $this->modinfo)->assign('module', $moduleName)->assign('toplevelmodule', $this->toplevelmodule)->assign('type', $this->type)->assign('func', $this->func)->assign('lang', $this->language)->assign('themeinfo', $this->themeinfo)->assign('themepath', isset($themeBundle) ? $themeBundle->getRelativePath() : $this->baseurl . 'themes/' . $theme)->assign('baseurl', $this->baseurl)->assign('baseuri', $this->baseuri)->assign('moduleBundle', ModUtil::getModule($moduleName))->assign('themeBundle', $themeBundle);
     if (isset($themeBundle)) {
         $stylePath = $themeBundle->getRelativePath() . "/Resources/public/css";
         $javascriptPath = $themeBundle->getRelativePath() . "/Resources/public/js";
         $imagePath = $themeBundle->getRelativePath() . "/Resources/public/images";
         $imageLangPath = $themeBundle->getRelativePath() . "/Resources/public/images/" . $this->language;
     } else {
         $stylePath = $this->baseurl . "themes/{$theme}/style";
         $javascriptPath = $this->baseurl . "themes/{$theme}/javascript";
         $imagePath = $this->baseurl . "themes/{$theme}/images";
         $imageLangPath = $this->baseurl . "themes/{$theme}/images/" . $this->language;
     }
     $this->assign('stylepath', $stylePath)->assign('scriptpath', $javascriptPath)->assign('imagepath', $imagePath)->assign('imagelangpath', $imageLangPath);
     // for {gt} template plugin to detect gettext domain
     if ($this->modinfo['type'] == ModUtil::TYPE_MODULE) {
         $this->domain = ZLanguage::getModuleDomain($this->modinfo['name']);
     }
     // make render object available to modifiers
     parent::assign('zikula_view', $this);
     // add ServiceManager, EventManager and others to all templates
     parent::assign('serviceManager', $this->serviceManager);
     parent::assign('eventManager', $this->eventManager);
     parent::assign('zikula_core', $this->serviceManager->get('zikula'));
     parent::assign('request', $this->request);
     $modvars = ModUtil::getModvars();
     // Get all modvars from any modules that have accessed their modvars at least once.
     // provide compatibility 'alias' array keys
     // @todo remove after v1.4.0
     if (isset($modvars['ZikulaAdminModule'])) {
         $modvars['Admin'] = $modvars['ZikulaAdminModule'];
     }
     if (isset($modvars['ZikulaBlocksModule'])) {
         $modvars['Blocks'] = $modvars['ZikulaBlocksModule'];
     }
     if (isset($modvars['ZikulaCategoriesModule'])) {
         $modvars['Categories'] = $modvars['ZikulaCategoriesModule'];
     }
     if (isset($modvars['ZikulaExtensionsModule'])) {
         $modvars['Extensions'] = $modvars['ZikulaExtensionsModule'];
     }
     if (isset($modvars['ZikulaGroupsModule'])) {
         $modvars['Groups'] = $modvars['ZikulaGroupsModule'];
     }
     if (isset($modvars['ZikulaMailerModule'])) {
         $modvars['Mailer'] = $modvars['ZikulaMailerModule'];
     }
     if (isset($modvars['ZikulaPageLockModule'])) {
         $modvars['PageLock'] = $modvars['ZikulaPageLockModule'];
     }
     if (isset($modvars['ZikulaPermissionsModule'])) {
         $modvars['Permissions'] = $modvars['ZikulaPermissionsModule'];
     }
     if (isset($modvars['ZikulaSearchModule'])) {
         $modvars['Search'] = $modvars['ZikulaSearchModule'];
     }
     if (isset($modvars['ZikulaSecurityCenterModule'])) {
         $modvars['SecurityCenter'] = $modvars['ZikulaSecurityCenterModule'];
     }
     if (isset($modvars['ZikulaSettingsModule'])) {
         $modvars['Settings'] = $modvars['ZikulaSettingsModule'];
     }
     if (isset($modvars['ZikulaThemeModule'])) {
         $modvars['Theme'] = $modvars['ZikulaThemeModule'];
     }
     if (isset($modvars['ZikulaUsersModule'])) {
         $modvars['Users'] = $modvars['ZikulaUsersModule'];
     }
     // end compatibility aliases
     parent::assign('modvars', $modvars);
     $this->add_core_data();
     // metadata for SEO
     if (!$this->serviceManager->hasParameter('zikula_view.metatags')) {
         $this->serviceManager->setParameter('zikula_view.metatags', new ArrayObject(array()));
     }
     parent::assign('metatags', $this->serviceManager->getParameter('zikula_view.metatags'));
     if (isset($themeBundle) && $themeBundle->isTwigBased()) {
         // correct asset urls when smarty output is wrapped by twig theme
         $this->load_filter('output', 'asseturls');
     }
     $event = new \Zikula\Core\Event\GenericEvent($this);
     $this->eventManager->dispatch('view.init', $event);
 }
Пример #7
0
 /**
  * Decode the path string into a set of variable/value pairs.
  *
  * This API works in conjunction with the new short urls
  * system to extract a path based variable set into the Get, Post
  * and request superglobals.
  * A sample path is /modname/function/var1:value1.
  *
  * @return void
  */
 public static function queryStringDecode(Request $request)
 {
     if (self::isInstalling()) {
         return;
     }
     // Try to match a route first.
     // Make sure we have the correct request context.
     $requestContext = ServiceUtil::get('router.request_context');
     $requestContext->fromRequest($request);
     /** @var \Symfony\Component\Routing\Matcher\RequestMatcherInterface $router */
     $router = ServiceUtil::get('router');
     try {
         $parameters = $router->matchRequest($request);
         if (!isset($parameters['_zkModule']) || !isset($parameters['_zkType']) || !isset($parameters['_zkFunc'])) {
             // This might be the web profiler or another native bundle.
             return;
         }
         // The following block is needed as long as not every url is a route. To be removed when all legacy routing
         // is removed.
         if ($parameters['_route'] == 'zikularoutesmodule_redirectingcontroller_removetrailingslash') {
             $pathInfo = $request->getPathInfo();
             $requestUri = $request->getRequestUri();
             // Check if url without slash exists. If it doesn't exist, it will throw an exception which is caught
             // by the try->catch below.
             $url = str_replace($pathInfo, rtrim($pathInfo, ' /'), $requestUri);
             $router->match($url);
         }
         $modname = strtolower($parameters['_zkModule']);
         $type = strtolower($parameters['_zkType']);
         $func = strtolower($parameters['_zkFunc']);
         if (isset($parameters['_locale'])) {
             $lang = strtolower($parameters['_locale']);
             $request->query->set('lang', $lang);
             self::queryStringSetVar('lang', $lang);
         }
         $request->attributes->set('_zkModule', $modname);
         $request->attributes->set('_zkType', $type);
         $request->attributes->set('_zkFunc', $func);
         $request->query->set('module', $modname);
         $request->query->set('type', $type);
         $request->query->set('func', $func);
         self::queryStringSetVar('module', $modname);
         self::queryStringSetVar('type', $type);
         self::queryStringSetVar('func', $func);
         return;
     } catch (ResourceNotFoundException $e) {
         // This is an old style url.
     } catch (RouteNotFoundException $e) {
         // This is an old style url.
     } catch (MethodNotAllowedException $e) {
         // this is an old style url.
     }
     // get our base parameters to work out if we need to decode the url
     $module = FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $func = FormUtil::getPassedValue('func', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $type = FormUtil::getPassedValue('type', null, 'GETPOST', FILTER_SANITIZE_STRING);
     // check if we need to decode the url
     $shorturls = self::getVar('shorturls');
     if ($shorturls && empty($module) && empty($type) && empty($func)) {
         // user language is not set at this stage
         $lang = self::getVar('language_i18n', '');
         $customentrypoint = self::getVar('entrypoint');
         $expectEntrypoint = !self::getVar('shorturlsstripentrypoint');
         $root = empty($customentrypoint) ? 'index.php' : $customentrypoint;
         // check if we hit baseurl, e.g. domain.com/ and if we require the language URL
         // then we should redirect to the language URL.
         if (ZLanguage::isRequiredLangParam() && self::getCurrentUrl() == self::getBaseUrl()) {
             $uri = $expectEntrypoint ? "{$root}/{$lang}" : $lang;
             self::redirect(self::getBaseUrl() . $uri);
             self::shutDown();
         }
         // check if entry point is part of the URL expectation.  If so throw error if it's not present
         // since this URL is technically invalid.
         if ($expectEntrypoint && self::getCurrentUrl() != self::getBaseUrl() && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) !== 0) {
             $protocol = self::serverGetVar('SERVER_PROTOCOL');
             header("{$protocol} 404 Not Found");
             echo __('The requested URL cannot be found');
             self::shutDown();
         }
         if (!$expectEntrypoint && self::getCurrentUrl() == self::getBaseUrl() . $root) {
             self::redirect(self::getHomepageUrl(), array(), 302, true);
             self::shutDown();
         }
         if (!$expectEntrypoint && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) === 0) {
             $protocol = self::serverGetVar('SERVER_PROTOCOL');
             header("{$protocol} 404 Not Found");
             echo __('The requested URL cannot be found');
             self::shutDown();
         }
         // get base path to work out our current url
         $parsedURL = parse_url(self::getCurrentUri());
         // strip any unwanted content from the provided URL
         $tobestripped = array(self::getBaseUri(), "{$root}");
         $path = str_replace($tobestripped, '', $parsedURL['path']);
         $path = trim($path, '/');
         // split the path into a set of argument strings
         $args = explode('/', rtrim($path, '/'));
         // ensure that each argument is properly decoded
         foreach ($args as $k => $v) {
             $args[$k] = urldecode($v);
         }
         $modinfo = null;
         $frontController = $expectEntrypoint ? "{$root}/" : '';
         // if no arguments present
         if (!$args[0] && !isset($_GET['lang']) && !isset($_GET['theme'])) {
             // we are in the homepage, checks if language code is forced
             if (ZLanguage::getLangUrlRule() && $lang) {
                 // and redirect then
                 self::redirect(self::getCurrentUrl() . "/{$lang}", array(), 302, true);
                 self::shutDown();
             }
         } else {
             // check the existing shortURL parameters
             // validation of the first parameter as language code
             if (ZLanguage::isLangParam($args[0]) && in_array($args[0], ZLanguage::getInstalledLanguages())) {
                 // checks if the language is not enforced and this url is passing the default lang
                 if (!ZLanguage::getLangUrlRule() && $lang == $args[0]) {
                     // redirects the passed arguments without the default site language
                     array_shift($args);
                     foreach ($args as $k => $v) {
                         $args[$k] = urlencode($v);
                     }
                     self::redirect(self::getBaseUrl() . $frontController . ($args ? implode('/', $args) : ''), array(), 302, true);
                     self::shutDown();
                 }
                 self::queryStringSetVar('lang', $args[0], $request);
                 array_shift($args);
             } elseif (ZLanguage::getLangUrlRule()) {
                 // if the lang is forced, redirects the passed arguments plus the lang
                 foreach ($args as $k => $v) {
                     $args[$k] = urlencode($v);
                 }
                 $langTheme = isset($_GET['theme']) ? "{$lang}/{$_GET['theme']}" : $lang;
                 self::redirect(self::getBaseUrl() . $frontController . $langTheme . '/' . implode('/', $args), array(), 302, true);
                 self::shutDown();
             }
             // check if there are remaining arguments
             if ($args) {
                 // try the first argument as a module
                 $modinfo = ModUtil::getInfoFromName($args[0]);
                 if ($modinfo) {
                     array_shift($args);
                 }
             }
             // if that fails maybe it's a theme
             if ($args && !$modinfo) {
                 $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($args[0]));
                 if ($themeinfo) {
                     self::queryStringSetVar('theme', $themeinfo['name'], $request);
                     $request->attributes->set('_theme', $themeinfo['name']);
                     // now shift the vars and continue as before
                     array_shift($args);
                     if ($args) {
                         $modinfo = ModUtil::getInfoFromName($args[0]);
                         if ($modinfo) {
                             array_shift($args);
                         }
                     }
                 }
             }
             // if there are parameters (not homepage)
             // try to see if there's a default shortURLs module
             if ($args && !$modinfo) {
                 // add the default module handler into the code
                 $modinfo = ModUtil::getInfoFromName(self::getVar('shorturlsdefaultmodule'));
             }
         }
         // check if there is a module and a custom url handler for it
         // if not decode the url using the default handler
         if ($modinfo && $modinfo['type'] != 0) {
             // prepare the arguments to the module handler
             array_unshift($args, '');
             // support for 1.2- empty parameter due the initial explode
             array_unshift($args, $modinfo['url']);
             // set the REQUEST parameters
             self::queryStringSetVar('module', $modinfo['name'], $request);
             // the user.function name can be the second argument string, set a default
             // later the custom module handler (if exists) must setup a new one if needed
             self::queryStringSetVar('type', 'user', $request);
             if (isset($args[2])) {
                 self::queryStringSetVar('func', $args[2], $request);
             } else {
                 self::queryStringSetVar('func', 'main', $request);
             }
             if (!ModUtil::apiFunc($modinfo['name'], 'user', 'decodeurl', array('vars' => $args))) {
                 // any remaining arguments are specific to the module
                 $argscount = count($args);
                 for ($i = 3; $i < $argscount; $i = $i + 2) {
                     if (isset($args[$i]) && isset($args[$i + 1])) {
                         self::queryStringSetVar($args[$i], urldecode($args[$i + 1]), $request);
                     }
                 }
             }
         }
     }
     $module = ucfirst(FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING));
     $func = ucfirst(FormUtil::getPassedValue('func', null, 'GETPOST', FILTER_SANITIZE_STRING));
     $type = ucfirst(FormUtil::getPassedValue('type', null, 'GETPOST', FILTER_SANITIZE_STRING));
     $arguments = array();
     if (!$module) {
         // set the start parameters
         $module = self::getVar('startpage');
         $type = self::getVar('starttype');
         $func = self::getVar('startfunc');
         $args = explode(',', self::getVar('startargs'));
         foreach ($args as $arg) {
             if (!empty($arg)) {
                 $argument = explode('=', $arg);
                 $arguments[$argument[0]] = $argument[1];
             }
         }
     } else {
         $arguments = $_GET;
         unset($arguments['module']);
         unset($arguments['type']);
         unset($arguments['func']);
     }
     if ($shorturls) {
         $request->query->replace($_GET);
     }
     $request->attributes->set('_zkModule', strtolower($module));
     // legacy - this is how they are received originally
     $request->attributes->set('_zkType', strtolower($type));
     // legacy - this is how they are received originally
     $request->attributes->set('_zkFunc', strtolower($func));
     // legacy - this is how they are received originally
     $request->attributes->set('_zkArgs', $arguments);
 }
Пример #8
0
    /**
     * delete a theme
     *
     */
    public function delete($args)
    {
        $themename = FormUtil::getPassedValue('themename', isset($args['themename']) ? $args['themename'] : null, 'REQUEST');
        $objectid = FormUtil::getPassedValue('objectid', isset($args['objectid']) ? $args['objectid'] : null, 'REQUEST');
        $confirmation = FormUtil::getPassedValue('confirmation', null, 'POST');
        if (!empty($objectid)) {
            $mid = $objectid;
        }

        // Get the theme info
        $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($themename));

        if ($themeinfo == false) {
            return LogUtil::registerError($this->__('Sorry! No such theme found.'), 404);
        }

        // Security check
        if (!SecurityUtil::checkPermission('Theme::', "$themename::", ACCESS_DELETE)) {
            return LogUtil::registerPermissionError();
        }

        // Check for confirmation.
        if (empty($confirmation)) {
            // No confirmation yet

            // Add the message id
            $this->view->assign($themeinfo);

            // Return the output that has been generated by this function
            return $this->view->fetch('theme_admin_delete.tpl');
        }

        // If we get here it means that the user has confirmed the action
        $this->checkCsrfToken();

        $deletefiles = FormUtil::getPassedValue('deletefiles', 0, 'POST');

        // Delete the admin message
        // The return value of the function is checked
        if (ModUtil::apiFunc('Theme', 'admin', 'delete', array('themename' => $themename, 'deletefiles' => $deletefiles))) {
            // Success
            LogUtil::registerStatus($this->__('Done! Deleted it.'));
        }

        // This function generated no output, and so now it is complete we redirect
        // the user to an appropriate page for them to carry on their work
        $this->redirect(ModUtil::url('Theme', 'admin', 'view'));
    }
Пример #9
0
 /**
  * Constructor.
  *
  * @param ContainerBuilder $container ServiceManager.
  * @param string           $moduleName     Module name ("zikula" for system plugins).
  * @param integer|null     $caching        Whether or not to cache (Zikula_View::CACHE_*) or use config variable (null).
  */
 public function __construct(ContainerBuilder $container, $moduleName = '', $caching = null)
 {
     $this->container = $container;
     $this->dispatcher = $this->container->get('event_dispatcher');
     $this->request = $this->container->get('request');
     // set the error reporting level
     $this->error_reporting = isset($container['error_reporting']) ? $container['error_reporting'] : E_ALL;
     $this->allow_php_tag = true;
     // get variables from input
     $module = $this->request->attributes->get('_module', null);
     $type = $this->request->attributes->get('_controller', 'user');
     $func = $this->request->attributes->get('_action', 'index');
     // set vars based on the module structures
     $this->homepage = empty($module) ? true : false;
     $this->type = strtolower(!$this->homepage ? $type : System::getVar('starttype'));
     $this->func = strtolower(!$this->homepage ? $func : System::getVar('startfunc'));
     // Initialize the module property with the name of
     // the topmost module. For Hooks, Blocks, API Functions and others
     // you need to set this property to the name of the respective module!
     $this->toplevelmodule = ModUtil::getName();
     if (!$moduleName) {
         $moduleName = $this->toplevelmodule;
     }
     $this->modinfo = ModUtil::getInfoFromName($moduleName);
     $this->module = array($moduleName => $this->modinfo);
     // initialise environment vars
     $this->language = ZLanguage::getLanguageCode();
     $this->baseurl = System::getBaseUrl();
     $this->baseuri = System::getBaseUri();
     // system info
     $this->themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));
     $this->theme = $this->themeinfo['directory'];
     //---- Plugins handling -----------------------------------------------
     // add plugin paths
     switch ($this->modinfo['type']) {
         case ModUtil::TYPE_MODULE:
             $mpluginPath = "modules/" . $this->modinfo['directory'] . "/Resources/views/plugins";
             break;
         case ModUtil::TYPE_SYSTEM:
             $mpluginPath = "system/" . $this->modinfo['directory'] . "/Rsources/views/plugins";
             break;
         default:
             $mpluginPath = "system/" . $this->modinfo['directory'] . "/Rsources/views/plugins";
     }
     // add standard plugin search path
     $this->plugins_dir = array();
     $this->addPluginDir('config/Resources/plugins');
     // Official override
     $this->addPluginDir('config/plugins');
     // Official override
     $this->addPluginDir(ZIKULA_ROOT . '/../src/legacy/viewplugins');
     // Core plugins
     $this->addPluginDir("themes/{$this->theme}/Resources/views/plugins");
     // Theme plugins
     $this->addPluginDir(SMARTY_DIR . 'plugins');
     // Smarty core plugins
     $this->addPluginDir($mpluginPath);
     // Plugins for current module
     // check if the 'type' parameter in the URL is admin and if yes,
     // include system/Admin/templates/plugins to the plugins_dir array
     if ($type === 'admin') {
         if (!$this instanceof Zikula_View_Theme) {
             $this->addPluginDir('system/AdminModule/Resources/views/plugins');
         } else {
             $this->load_filter('output', 'admintitle');
         }
     }
     //---- Cache handling -------------------------------------------------
     if ($caching && in_array((int) $caching, array(0, 1, 2))) {
         $this->caching = (int) $caching;
     } else {
         $this->caching = (int) ModUtil::getVar('Theme', 'render_cache');
     }
     $this->compile_id = '';
     $this->cache_id = '';
     // template compilation
     $this->compile_dir = CacheUtil::getLocalDir('view_compiled');
     $this->compile_check = ModUtil::getVar('Theme', 'render_compile_check');
     $this->force_compile = ModUtil::getVar('Theme', 'render_force_compile');
     // template caching
     $this->cache_dir = CacheUtil::getLocalDir('view_cache');
     $this->cache_lifetime = ModUtil::getVar('Theme', 'render_lifetime');
     $this->expose_template = ModUtil::getVar('Theme', 'render_expose_template') == true ? true : false;
     // register resource type 'z' this defines the way templates are searched
     // during {include file='my_template.tpl'} this enables us to store selected module
     // templates in the theme while others can be kept in the module itself.
     $this->register_resource('z', array('Zikula_View_Resource', 'z_get_template', 'z_get_timestamp', 'z_get_secure', 'z_get_trusted'));
     // set 'z' as default resource type
     $this->default_resource_type = 'z';
     // process some plugins specially when Render cache is enabled
     if (!$this instanceof Zikula_View_Theme && $this->caching) {
         $this->register_nocache_plugins();
     }
     // register the 'nocache' block to allow dynamic zones caching templates
     $this->register_block('nocache', array('Zikula_View_Resource', 'block_nocache'), false);
     // For ajax requests we use the short urls filter to 'fix' relative paths
     if ($this->container->get('zikula')->getStage() & \Zikula\Core\Core::STAGE_AJAX && System::getVar('shorturls')) {
         $this->load_filter('output', 'shorturls');
     }
     // register prefilters
     $this->register_prefilter('z_prefilter_add_literal');
     $this->register_prefilter('z_prefilter_gettext_params');
     // assign some useful settings
     $this->assign('homepage', $this->homepage)->assign('modinfo', $this->modinfo)->assign('module', $moduleName)->assign('toplevelmodule', $this->toplevelmodule)->assign('type', $this->type)->assign('func', $this->func)->assign('lang', $this->language)->assign('themeinfo', $this->themeinfo)->assign('themepath', $this->baseurl . 'themes/' . $this->theme)->assign('baseurl', $this->baseurl)->assign('baseuri', $this->baseuri);
     // for {gt} template plugin to detect gettext domain
     if ($this->modinfo['type'] == ModUtil::TYPE_MODULE) {
         $this->domain = ZLanguage::getModuleDomain($this->modinfo['name']);
     }
     // make render object available to modifiers
     parent::assign('zikula_view', $this);
     // add ServiceManager, EventManager and others to all templates
     parent::assign('container', $this->container);
     parent::assign('dispatcher', $this->dispatcher);
     parent::assign('zikula_core', $this->container->get('zikula'));
     parent::assign('request', $this->request);
     parent::assign('modvars', ModUtil::getModvars());
     // Get all modvars from any modules that have accessed their modvars at least once.
     $this->add_core_data();
     // metadata for SEO
     if (!isset($this->container['zikula_view.metatags'])) {
         $this->container['zikula_view.metatags'] = new ArrayObject(array());
     }
     parent::assign('metatags', $this->container['zikula_view.metatags']);
     $event = new GenericEvent($this);
     $this->dispatcher->dispatch('view.init', $event);
 }
Пример #10
0
    public function display($blockinfo)
    {
        // check if the module is available
        if (!ModUtil::available('Theme')) {
            return;
        }

        // check if theme switching is allowed
        if (!System::getVar('theme_change')) {
            return;
        }

        // security check
        if (!SecurityUtil::checkPermission( "Themeswitcherblock::", "$blockinfo[title]::", ACCESS_READ)) {
            return;
        }

        // Get variables from content block
        $vars = BlockUtil::varsFromContent($blockinfo['content']);

        // Defaults
        if (empty($vars['format'])) {
            $vars['format'] = 1;
        }

        // get some use information about our environment
        $currenttheme = UserUtil::getTheme();

        // get all themes in our environment
        $themes = ThemeUtil::getAllThemes();

        // get some use information about our environment
        $currenttheme = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));

        // get all themes in our environment
        $themes = ThemeUtil::getAllThemes(ThemeUtil::FILTER_USER);

        $previewthemes = array();
        $currentthemepic = null;
        foreach ($themes as $themeinfo) {
            $themename = $themeinfo['name'];
            if (file_exists($themepic = 'themes/'.DataUtil::formatForOS($themeinfo['directory']).'/images/preview_small.png')) {
                $themeinfo['previewImage'] = $themepic;
            } else {
                $themeinfo['previewImage'] = 'system/Theme/images/preview_small.png';
            }
            $previewthemes[$themename] = $themeinfo;
            if ($themename == $currenttheme['name']) {
                $currentthemepic = $themeinfo['previewImage'];
            }
        }

        $this->view->assign($vars)
                   ->assign('currentthemepic', $currentthemepic)
                   ->assign('currenttheme', $currenttheme)
                   ->assign('themes', $previewthemes);

        $blockinfo['content'] = $this->view->fetch('theme_block_themeswitcher.tpl');

        return BlockUtil::themeBlock($blockinfo);
    }
Пример #11
0
    /**
     * Display a block based on the current theme.
     *
     * @param array $blockinfo Block info.
     *
     * @return string The rendered output.
     */
    public static function themeBlock($blockinfo)
    {
        static $themeinfo, $themedir, $upb, $downb;

        if (!isset($blockinfo['bid'])) {
            $blockinfo['bid'] = '';
        }
        if (!isset($blockinfo['title'])) {
            $blockinfo['title'] = '';
        }

        if (UserUtil::isLoggedIn() && ModUtil::getVar('Blocks', 'collapseable') == 1 && isset($blockinfo['collapsable']) && ($blockinfo['collapsable'] == '1')) {
            if (!isset($themeinfo)) {
                $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));
                $themedir = DataUtil::formatForOS($themeinfo['directory']);
            }

            // check for collapsable menus being enabled, and setup the collapsable menu image.
            if (!isset($upb)) {
                if (file_exists('themes/' . $themedir . '/images/upb.png')) {
                    $upb = '<img src="themes/' . $themedir . '/images/upb.png" alt="-" />';
                } elseif (file_exists('themes/' . $themedir . '/images/14_layer_raiselayer.png')) {
                    $upb = '<img src="themes/' . $themedir . '/images/14_layer_raiselayer.png" alt="-" />';
                } else {
                    $upb = '<img src="images/icons/extrasmall/14_layer_raiselayer.png" alt="-" />';
                }
            }
            if (!isset($downb)) {
                if (file_exists('themes/' . $themedir . '/images/downb.png')) {
                    $downb = '<img src="themes/' . $themedir . '/images/downb.png" alt="+" />';
                } elseif (file_exists('themes/' . $themedir . '/images/14_layer_lowerlayer.png')) {
                    $downb = '<img src="themes/' . $themedir . '/images/14_layer_lowerlayer.png" alt="+" />';
                } else {
                    $downb = '<img src="images/icons/extrasmall/14_layer_lowerlayer.png" alt="+" />';
                }
            }

            if (self::checkUserBlock($blockinfo) == '1') {
                if (!empty($blockinfo['title'])) {
                    $blockinfo['minbox'] = '<a href="' . DataUtil::formatForDisplay(ModUtil::url('Blocks', 'user', 'changestatus', array('bid' => $blockinfo['bid']))) . '">' . $upb . '</a>';
                }
            } else {
                $blockinfo['content'] = '';
                if (!empty($blockinfo['title'])) {
                    $blockinfo['minbox'] = '<a href="' . DataUtil::formatForDisplay(ModUtil::url('Blocks', 'user', 'changestatus', array('bid' => $blockinfo['bid']))) . '">' . $downb . '</a>';
                }
            }
            // end collapseable menu config
        } else {
            $blockinfo['minbox'] = '';
        }

        return Zikula_View_Theme::getInstance()->themesidebox($blockinfo);
    }
Пример #12
0
 /**
  * Display a block based on the current theme.
  *
  * @param array $blockinfo Block info.
  *
  * @return string The rendered output.
  */
 public static function themeBlock($blockinfo)
 {
     static $themeinfo, $themedir, $upb, $downb;
     if (!isset($blockinfo['bid'])) {
         $blockinfo['bid'] = '';
     }
     if (!isset($blockinfo['title'])) {
         $blockinfo['title'] = '';
     }
     if (UserUtil::isLoggedIn() && ModUtil::getVar('ZikulaBlocksModule', 'collapseable') == 1 && isset($blockinfo['collapsable']) && $blockinfo['collapsable'] == '1') {
         if (!isset($themeinfo)) {
             $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));
             $themedir = DataUtil::formatForOS($themeinfo['directory']);
         }
         // check for collapsable menus being enabled, and setup the collapsable menu image.
         if (!isset($upb)) {
             if (file_exists('themes/' . $themedir . '/images/upb.png')) {
                 $upb = '<img src="themes/' . $themedir . '/images/upb.png" alt="-" />';
             } elseif (file_exists('themes/' . $themedir . '/images/14_layer_raiselayer.png')) {
                 $upb = '<img src="themes/' . $themedir . '/images/14_layer_raiselayer.png" alt="-" />';
             } else {
                 $upb = '<img src="images/icons/extrasmall/14_layer_raiselayer.png" alt="-" />';
             }
         }
         if (!isset($downb)) {
             if (file_exists('themes/' . $themedir . '/images/downb.png')) {
                 $downb = '<img src="themes/' . $themedir . '/images/downb.png" alt="+" />';
             } elseif (file_exists('themes/' . $themedir . '/images/14_layer_lowerlayer.png')) {
                 $downb = '<img src="themes/' . $themedir . '/images/14_layer_lowerlayer.png" alt="+" />';
             } else {
                 $downb = '<img src="images/icons/extrasmall/14_layer_lowerlayer.png" alt="+" />';
             }
         }
         $checkUserBlock = self::checkUserBlock($blockinfo);
         if ($checkUserBlock) {
             if (!empty($blockinfo['title'])) {
                 $blockinfo['minbox'] = '<a href="' . DataUtil::formatForDisplay(ModUtil::url('ZikulaBlocksModule', 'user', 'changestatus', array('bid' => $blockinfo['bid']))) . '">' . $upb . '</a>';
             }
         } else {
             $blockinfo['content'] = '';
             if (!empty($blockinfo['title'])) {
                 $blockinfo['minbox'] = '<a href="' . DataUtil::formatForDisplay(ModUtil::url('ZikulaBlocksModule', 'user', 'changestatus', array('bid' => $blockinfo['bid']))) . '">' . $downb . '</a>';
             }
         }
         // end collapseable menu config
     } else {
         $blockinfo['minbox'] = '';
     }
     // try twig theme first (note: theme is already set by this point)
     $container = ServiceUtil::getManager();
     $twigBasedThemeBlock = $container->get('zikula_core.common.theme_engine')->wrapBcBlockInTheme($blockinfo);
     if ($twigBasedThemeBlock) {
         return $twigBasedThemeBlock;
     }
     // theme is not twig based revert to smarty
     return Zikula_View_Theme::getInstance()->themesidebox($blockinfo);
 }
Пример #13
0
    /**
     * Constructor.
     *
     * @param Zikula_ServiceManager $serviceManager ServiceManager.
     * @param string                $moduleName     Module name ("zikula" for system plugins).
     * @param integer|null          $caching        Whether or not to cache (Zikula_View::CACHE_*) or use config variable (null).
     */
    public function __construct(Zikula_ServiceManager $serviceManager, $moduleName = '', $caching = null)
    {
        $this->serviceManager = $serviceManager;
        $this->eventManager = $this->serviceManager->getService('zikula.eventmanager');
        $this->request = $this->serviceManager->getService('request');

        // set the error reporting level
        $this->error_reporting = isset($GLOBALS['ZConfig']['Debug']['error_reporting']) ? $GLOBALS['ZConfig']['Debug']['error_reporting'] : E_ALL;
        $this->allow_php_tag = true;

        // get variables from input
        $module = FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING);
        $type   = FormUtil::getPassedValue('type', 'user', 'GETPOST', FILTER_SANITIZE_STRING);
        $func   = FormUtil::getPassedValue('func', 'main', 'GETPOST', FILTER_SANITIZE_STRING);

        // set vars based on the module structures
        $this->homepage = empty($module) ? true : false;
        $this->type = strtolower(!$this->homepage ? $type : System::getVar('starttype'));
        $this->func = strtolower(!$this->homepage ? $func : System::getVar('startfunc'));

        // Initialize the module property with the name of
        // the topmost module. For Hooks, Blocks, API Functions and others
        // you need to set this property to the name of the respective module!
        $this->toplevelmodule = ModUtil::getName();

        if (!$moduleName) {
            $moduleName = $this->toplevelmodule;
        }
        $this->modinfo = ModUtil::getInfoFromName($moduleName);
        $this->module  = array($moduleName => $this->modinfo);

        // initialise environment vars
        $this->language = ZLanguage::getLanguageCode();
        $this->baseurl = System::getBaseUrl();
        $this->baseuri = System::getBaseUri();

        // system info
        $this->themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));
        $this->theme = $theme = $this->themeinfo['directory'];

        //---- Plugins handling -----------------------------------------------
        // add plugin paths
        switch ($this->modinfo['type'])
        {
            case ModUtil::TYPE_MODULE :
                $mpluginPath = "modules/" . $this->modinfo['directory'] . "/templates/plugins";
                $mpluginPathOld = "modules/" . $this->modinfo['directory'] . "/pntemplates/plugins";
                break;
            case ModUtil::TYPE_SYSTEM :
                $mpluginPath = "system/" . $this->modinfo['directory'] . "/templates/plugins";
                $mpluginPathOld = "system/" . $this->modinfo['directory'] . "/pntemplates/plugins";
                break;
            default:
                $mpluginPath = "system/" . $this->modinfo['directory'] . "/templates/plugins";
                $mpluginPathOld = "system/" . $this->modinfo['directory'] . "/pntemplates/plugins";
        }

        // add standard plugin search path
        $this->plugins_dir = array();
        $this->addPluginDir('config/plugins'); // Official override
        $this->addPluginDir('lib/viewplugins'); // Core plugins
        $this->addPluginDir("themes/$theme/plugins"); // Theme plugins
        $this->addPluginDir('plugins'); // Smarty core plugins
        $this->addPluginDir($mpluginPath); // Plugins for current module

        // check if the 'type' parameter in the URL is admin and if yes,
        // include system/Admin/templates/plugins to the plugins_dir array
        if ($type === 'admin') {
            if (!$this instanceof Zikula_View_Theme) {
                $this->addPluginDir('system/Admin/templates/plugins');
            } else {
                $this->load_filter('output', 'admintitle');
            }
        }

        // adds legacy plugin paths if needed
        if (System::isLegacyMode()) {
            $this->addPluginDir('lib/legacy/plugins'); // Core legacy plugins
            $this->addPluginDir($mpluginPathOld); // Module plugins (legacy paths)
            $this->addPluginDir("themes/$theme/templates/modules/$moduleName/plugins"); // Module override in themes
        }

        //---- Cache handling -------------------------------------------------
        if ($caching && in_array((int)$caching, array(0, 1, 2))) {
            $this->caching = (int)$caching;
        } else {
            $this->caching = (int)ModUtil::getVar('Theme', 'render_cache');
        }

        // write actions should not be cached or weird things happen
        if (isset($_POST) && count($_POST) != 0) {
            $this->caching = Zikula_View::CACHE_DISABLED;
        }

        $this->compile_id  = '';
        $this->cache_id    = '';

        // template compilation
        $this->compile_dir    = CacheUtil::getLocalDir('view_compiled');
        $this->compile_check  = ModUtil::getVar('Theme', 'render_compile_check');
        $this->force_compile  = ModUtil::getVar('Theme', 'render_force_compile');
        // template caching
        $this->cache_dir      = CacheUtil::getLocalDir('view_cache');
        $this->cache_lifetime = ModUtil::getVar('Theme', 'render_lifetime');

        $this->expose_template = (ModUtil::getVar('Theme', 'render_expose_template') == true) ? true : false;

        // register resource type 'z' this defines the way templates are searched
        // during {include file='my_template.tpl'} this enables us to store selected module
        // templates in the theme while others can be kept in the module itself.
        $this->register_resource('z', array('Zikula_View_Resource',
                                            'z_get_template',
                                            'z_get_timestamp',
                                            'z_get_secure',
                                            'z_get_trusted'));

        // set 'z' as default resource type
        $this->default_resource_type = 'z';

        // process some plugins specially when Render cache is enabled
        if (!$this instanceof Zikula_View_Theme && $this->caching) {
            $this->register_nocache_plugins();
        }

        // register the 'nocache' block to allow dynamic zones caching templates
        $this->register_block('nocache', array('Zikula_View_Resource', 'block_nocache'), false);

        // For ajax requests we use the short urls filter to 'fix' relative paths
        if (($this->serviceManager->getService('zikula')->getStage() & Zikula_Core::STAGE_AJAX) && System::getVar('shorturls')) {
            $this->load_filter('output', 'shorturls');
        }

        // register prefilters
        $this->register_prefilter('z_prefilter_add_literal');

        if ($GLOBALS['ZConfig']['System']['legacy_prefilters']) {
            $this->register_prefilter('z_prefilter_legacy');
        }

        $this->register_prefilter('z_prefilter_gettext_params');
        //$this->register_prefilter('z_prefilter_notifyfilters');

        // assign some useful settings
        $this->assign('homepage', $this->homepage)
             ->assign('modinfo', $this->modinfo)
             ->assign('module', $moduleName)
             ->assign('toplevelmodule', $this->toplevelmodule)
             ->assign('type', $this->type)
             ->assign('func', $this->func)
             ->assign('lang', $this->language)
             ->assign('themeinfo', $this->themeinfo)
             ->assign('themepath', $this->baseurl . 'themes/' . $theme)
             ->assign('baseurl', $this->baseurl)
             ->assign('baseuri', $this->baseuri);

        if (System::isLegacyMode()) {
            $this->assign('stylepath', $this->baseurl . 'themes/' . $theme . '/style')
                 ->assign('scriptpath', $this->baseurl . 'themes/' . $theme . '/javascript')
                 ->assign('imagepath', $this->baseurl . 'themes/' . $theme . '/images')
                 ->assign('imagelangpath', $this->baseurl . 'themes/' . $theme . '/images/' . $this->language);
        }

        // for {gt} template plugin to detect gettext domain
        if ($this->modinfo['type'] == ModUtil::TYPE_MODULE) {
            $this->domain = ZLanguage::getModuleDomain($this->modinfo['name']);
        }

        // make render object available to modifiers
        parent::assign('zikula_view', $this);

        // add ServiceManager, EventManager and others to all templates
        parent::assign('serviceManager', $this->serviceManager);
        parent::assign('eventManager', $this->eventManager);
        parent::assign('zikula_core', $this->serviceManager->getService('zikula'));
        parent::assign('request', $this->request);
        parent::assign('modvars', ModUtil::getModvars()); // Get all modvars from any modules that have accessed their modvars at least once.

        $this->add_core_data();

        // metadata for SEO
        if (!isset($this->serviceManager['zikula_view.metatags'])) {
            $this->serviceManager['zikula_view.metatags'] = new ArrayObject(array());
        }

        parent::assign('metatags', $this->serviceManager['zikula_view.metatags']);

        $event = new Zikula_Event('view.init', $this);
        $this->eventManager->notify($event);
    }
Пример #14
0
/**
 * pnThemeGetInfo
 *
 * Returns information about a theme.
 *
 * @author Mark West
 * @param string $themeid Id of the theme
 * @return array the theme information
 **/
function pnThemeGetInfo($themeid)
{
    LogUtil::log(__f('Warning! Function %1$s is deprecated. Please use %2$s instead.', array('pnThemeGetInfo()', 'ThemeUtil::getInfo()')), E_USER_DEPRECATED);

    return ThemeUtil::getInfo($themeid);
}
Пример #15
0
/**
 * Zikula_View outputfilter to add page variables and additional header global into page header
 *
 * By default this output filter places page variable output immediately prior to the closing
 * head tag (</head>). The output can, optionally, be placed anywhere in the template by adding
 * the HTML comment <!-- pagevars --> to the page template. Note that this must always be in
 * the header for the output to function correctly.
 *
 * @param string      $source Output source.
 * @param Zikula_View $view   Reference to Zikula_View instance.
 *
 * @return string
 */
function smarty_outputfilter_pagevars($source, $view)
{
    $return = '';
    $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));
    $cssjscombine = ModUtil::getVar('ZikulaThemeModule', 'cssjscombine', false);
    $type = $view->getRequest()->get('type');
    $zkType = $view->getRequest()->attributes->get('_zkType');
    $isAdminController = $type == 'admin' || $zkType == 'admin';
    // get list of stylesheets and scripts from JCSSUtil
    $jcss = JCSSUtil::prepareJCSS($cssjscombine, $view->cache_dir, $themeinfo, $isAdminController);
    if (is_array($jcss['stylesheets']) && !empty($jcss['stylesheets'])) {
        foreach ($jcss['stylesheets'] as $stylesheet) {
            if (empty($stylesheet)) {
                continue;
            }
            // check if the stylesheets is in the additional_header array
            if ($themeinfo['xhtml']) {
                $return .= '<link rel="stylesheet" href="' . DataUtil::formatForDisplay($stylesheet) . '" type="text/css" />' . "\n";
            } else {
                $return .= '<link rel="stylesheet" href="' . DataUtil::formatForDisplay($stylesheet) . '" type="text/css">' . "\n";
            }
        }
    }
    // get inline js config and print it just before any script tag
    $jsConfig = JCSSUtil::getJSConfig();
    if (!empty($jsConfig)) {
        $return .= $jsConfig;
    }
    if (is_array($jcss['javascripts']) && !empty($jcss['javascripts'])) {
        foreach ($jcss['javascripts'] as $j => $javascript) {
            if (empty($javascript)) {
                unset($jcss['javascripts'][$j]);
                continue;
            }
            // check if the javascript is in the additional_header array
            $return .= '<script type="text/javascript" src="' . DataUtil::formatForDisplay($javascript) . '"></script>' . "\n";
        }
    }
    $headerContent = PageUtil::getVar('header');
    if (is_array($headerContent) && !empty($headerContent)) {
        $return .= implode("\n", $headerContent) . "\n";
    }
    // if we've got some page vars to add the header wrap the output in
    // suitable identifying comments when in development mode
    $return = trim($return);
    if (!empty($return) && System::getVar('development') != 0) {
        $return = "<!-- zikula pagevars -->\n" . $return . "\n<!-- /zikula pagevars -->";
    }
    // get any body page vars
    $bodyvars = PageUtil::getVar('body');
    if (!empty($bodyvars)) {
        $bodyattribs = '<body ' . @implode(' ', $bodyvars) . '>';
        $source = str_replace('<body>', $bodyattribs, $source);
    }
    // get any footer page vars
    $footervars = PageUtil::getVar('footer');
    if (!empty($footervars)) {
        $footersource = @implode("\n", $footervars) . "\n</body>";
        $source = str_replace('</body>', $footersource, $source);
    }
    // replace the string in the template source
    if (stripos($source, '<!-- pagevars -->')) {
        $source = str_replace('<!-- pagevars -->', $return, $source);
    } else {
        $headPos = stripos($source, '</head>');
        if ($headPos !== false) {
            if ($headPos == strripos($source, '</head>')) {
                // Position of the first </head> matches the last </head> so str_replace is safe
                $source = str_replace('</head>', $return . "\n</head>", $source);
            } else {
                // Position of the first </head> does not match the last </head> so str_replace is NOT safe
                // There was probably a {zdebug} tag opening a _dbgconsole.
                // Need to use preg_replace so we can limit to the first.
                preg_replace('#</head>#i', $return . "\n</head>", $source, 1);
            }
        }
    }
    // return the modified source
    return $source;
}
Пример #16
0
    /**
     * delete a page configuration assignment
     */
    public function deletepageconfigurationassignment($args)
    {
        // Argument check
        if (!isset($args['themename']) && !isset($args['pcname'])) {
            return LogUtil::registerArgsError();
        }

        $themeid = ThemeUtil::getIDFromName($args['themename']);

        // Get the theme info
        $themeinfo = ThemeUtil::getInfo($themeid);

        if ($themeinfo == false) {
            return LogUtil::registerError(__('Sorry! No such item found.'));
        }

        // Security check
        if (!SecurityUtil::checkPermission('Theme::', "$themeinfo[name]::pageconfigurations", ACCESS_DELETE)) {
            return LogUtil::registerPermissionError();
        }

        // read the list of existing page config assignments
        $pageconfigurations = ModUtil::apiFunc('Theme', 'user', 'getpageconfigurations', array('theme' => $args['themename']));

        // remove the requested page configuration
        unset($pageconfigurations[$args['pcname']]);

        // write the page configurations back to the running config
        ModUtil::apiFunc('Theme', 'user', 'writeinifile', array('theme' => $args['themename'], 'assoc_arr' => $pageconfigurations, 'has_sections' => true, 'file' => 'pageconfigurations.ini'));

        return true;
    }
Пример #17
0
 /**
  * Get the user's theme.
  *
  * This function will return the current theme for the user.
  * Order of theme priority:
  *  - page-specific
  *  - category
  *  - user
  *  - system
  *
  * @param boolean $force True to ignore the cache.
  *
  * @return string           the name of the user's theme
  * @throws RuntimeException If this function was unable to calculate theme name.
  */
 public static function getTheme($force = false)
 {
     static $theme;
     if (isset($theme) && !$force) {
         return $theme;
     }
     if (CookieUtil::getCookie('zikulaMobileTheme') == '1' && ModUtil::getVar('Theme', 'enable_mobile_theme', false)) {
         $pagetheme = 'Mobile';
     } else {
         if (CookieUtil::getCookie('zikulaMobileTheme') != '2' && ModUtil::getVar('Theme', 'enable_mobile_theme', false)) {
             include_once "system/Theme/lib/vendor/Mobile_Detect.php";
             $detect = new Mobile_Detect();
             if ($detect->isMobile()) {
                 $pagetheme = 'Mobile';
             }
         } else {
             $pagetheme = FormUtil::getPassedValue('theme', null, 'GETPOST');
         }
     }
     // Page-specific theme
     $type = FormUtil::getPassedValue('type', null, 'GETPOST');
     $qstring = System::serverGetVar('QUERY_STRING');
     if (!empty($pagetheme)) {
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($pagetheme));
         if ($themeinfo['state'] == ThemeUtil::STATE_ACTIVE && ($themeinfo['user'] || $themeinfo['system'] || $themeinfo['admin'] && $type == 'admin') && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             return self::_getThemeFilterEvent($themeinfo['name'], 'page-specific');
         }
     }
     // check for an admin theme
     if (($type == 'admin' || $type == 'adminplugin') && SecurityUtil::checkPermission('::', '::', ACCESS_EDIT)) {
         $admintheme = ModUtil::getVar('Admin', 'admintheme');
         if (!empty($admintheme)) {
             $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($admintheme));
             if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
                 return self::_getThemeFilterEvent($themeinfo['name'], 'admin-theme');
             }
         }
     }
     // set a new theme for the user
     $newtheme = FormUtil::getPassedValue('newtheme', null, 'GETPOST');
     if (!empty($newtheme) && System::getVar('theme_change')) {
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($newtheme));
         if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             if (self::isLoggedIn()) {
                 self::setVar('theme', $newtheme);
             } else {
                 SessionUtil::setVar('theme', $newtheme);
             }
             return self::_getThemeFilterEvent($themeinfo['name'], 'new-theme');
         }
     }
     // User theme
     if (System::getVar('theme_change') || SecurityUtil::checkPermission('::', '::', ACCESS_ADMIN)) {
         if (self::isLoggedIn()) {
             $usertheme = self::getVar('theme');
         } else {
             $usertheme = SessionUtil::getVar('theme');
         }
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($usertheme));
         if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             return self::_getThemeFilterEvent($themeinfo['name'], 'user-theme');
         }
     }
     // default site theme
     $defaulttheme = System::getVar('Default_Theme');
     $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($defaulttheme));
     if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
         return self::_getThemeFilterEvent($themeinfo['name'], 'default-theme');
     }
     if (!System::isInstalling()) {
         throw new RuntimeException(__('UserUtil::getTheme() is unable to calculate theme name.'));
     }
 }
Пример #18
0
 /**
  * Find the path of the file by searching overrides and the module location.
  *
  * @param string $file   Name of file to find (can include relative path).
  * @param string $module Module name.
  *
  * @return mixed string of path or bool false
  */
 public static function _findpath($file, $module = null)
 {
     // if no module specified, default to calling module
     if (empty($module)) {
         $module = ModUtil::getName();
     }
     // Get module info
     $modinfo = ModUtil::getInfoFromName($module);
     if (!$modinfo) {
         throw new \Exception(__f('%1$s: The specified module [%2$s] does not exist.', array('Zikula_Workflow_Util', $module)));
     }
     $moduledir = $modinfo['directory'];
     // determine which folder to look in (system or modules)
     if ($modinfo['type'] == ModUtil::TYPE_SYSTEM) {
         // system module
         $modulepath = "system/{$moduledir}";
     } elseif ($modinfo['type'] == ModUtil::TYPE_MODULE) {
         // non system module
         $modulepath = "modules/{$moduledir}";
     } else {
         throw new \Exception(__f('%s: Unsupported module type.', 'Zikula_Workflow_Util'));
     }
     // ensure module is active
     if (!$modinfo['state'] == 3) {
         throw new \Exception(__f('%1$s: The module [%2$s] is not active.', array('Zikula_Workflow_Util', $module)));
     }
     $themedir = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));
     $themedir = $themedir['directory'];
     $themepath = DataUtil::formatForOS("themes/{$themedir}/workflows/{$moduledir}/{$file}");
     $configpath = DataUtil::formatForOS("config/workflows/{$moduledir}/{$file}");
     $modulepath = DataUtil::formatForOS("{$modulepath}/workflows/{$file}");
     // find the file in themes or config (for overrides), else module dir
     if (is_readable($themepath)) {
         return $themepath;
     } elseif (is_readable($configpath)) {
         return $configpath;
     } elseif (is_readable($modulepath)) {
         return $modulepath;
     }
     return false;
 }
Пример #19
0
 public function loadInformation()
 {
     // Check for failed database connection.
     if (!$this->dbEnabled) {
         return false;
     }
     //
     // load all blocks.
     //
     $this->blocks = ModUtil::apiFunc('Blocks', 'user', 'getall', array('inactive' => true));
     //
     // load all themes
     //
     $filethemes = array();
     // Open the themes directory.
     $handle = opendir('themes');
     // Read the directory contents.
     while ($dir = readdir($handle)) {
         // Skip any files, up-dirs, and certain themes.
         if (substr($dir, 0, 1) == '.' || substr($dir, 0, 5) == 'index' || substr($dir, 0, 3) == 'rss' || substr($dir, 0, 4) == 'Atom' || substr($dir, 0, 7) == 'Printer' || substr($dir, 0, 9) == 'AutoPrint') {
             continue;
         }
         // Catch the theme name.
         $filethemes[] = $dir;
     }
     // Close the directory.
     closedir($handle);
     // Loop through each theme.
     foreach ($filethemes as $theme) {
         $themeid = ThemeUtil::getIDFromName($theme);
         if ($themeid != false) {
             $this->themes['corethemes'][$theme] = ThemeUtil::getInfo(ThemeUtil::getIDFromName($theme));
         } else {
             $this->themes['corethemes'][$theme] = array('name' => $theme, 'state' => 0);
         }
     }
     ksort($this->themes['corethemes']);
     //
     // get site status
     //
     $this->siteInactive = System::getVar('siteoff') == 1;
     //
     // load all modules.
     //
     $mods = DBUtil::selectObjectArray('modules', "WHERE ({$this->dbTables['modules_column']['id']} > 0)", 'type');
     // Loop through modules, sorting.
     foreach ($mods as $mod) {
         if ($mod['type'] == 3) {
             $this->modules['sys_mods'][$mod['name']] = $mod;
         } else {
             if ($mod['type'] == 2) {
                 $this->modules['usr_mods'][$mod['name']] = $mod;
             }
         }
     }
     ksort($this->modules['sys_mods']);
     ksort($this->modules['usr_mods']);
     // check temp directory
     $this->tempdir = System::getVar('temp');
     $tempdirsubs = array('error_logs' => 0, 'idsTmp' => 0, 'purifierCache' => 0, 'view_cache' => 0, 'view_compiled' => 0, 'Theme_cache' => 0, 'Theme_compiled' => 0, 'Theme_Config' => 0);
     $this->tempdirsubsfailed = count($tempdirsubs);
     // Open the temp directory.
     $handle = opendir($this->tempdir);
     if (!$handle) {
         $this->tempdirexists = false;
     } else {
         $this->tempdirexists = true;
         // Read the directory contents.
         // continue if file is not in our wanted array
         while ($dir = readdir($handle)) {
             if (!array_key_exists($dir, $tempdirsubs)) {
                 continue;
             }
             // update the status
             $tempdirsubs[$dir] = 1;
             $this->tempdirsubsfailed--;
         }
         // Close the directory.
         closedir($handle);
     }
     $this->tempdirsubs = $tempdirsubs;
     return true;
 }
Пример #20
0
 /**
  * Get the user's theme.
  *
  * This function will return the current theme for the user.
  * Order of theme priority:
  *  - page-specific
  *  - category
  *  - user
  *  - system
  *
  * @param boolean $force True to ignore the cache.
  *
  * @return string           the name of the user's theme
  * @throws RuntimeException If this function was unable to calculate theme name.
  */
 public static function getTheme($force = false)
 {
     static $theme;
     if (isset($theme) && !$force) {
         return $theme;
     }
     // Page-specific theme
     $request = ServiceUtil::get('request');
     $pagetheme = $request->get('theme', null);
     $type = $request->attributes->get('_controller', null);
     if (!empty($pagetheme)) {
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($pagetheme));
         if ($themeinfo['state'] == ThemeUtil::STATE_ACTIVE && ($themeinfo['user'] || $themeinfo['system'] || $themeinfo['admin'] && $type == 'admin') && is_dir(ZIKULA_ROOT . '/themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             return self::_getThemeFilterEvent($themeinfo['name'], 'page-specific');
         }
     }
     // check for an admin theme
     if (($type == 'admin' || $type == 'adminplugin') && SecurityUtil::checkPermission('::', '::', ACCESS_EDIT)) {
         $admintheme = ModUtil::getVar('Admin', 'admintheme');
         if (!empty($admintheme)) {
             $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($admintheme));
             if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir(ZIKULA_ROOT . '/themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
                 return self::_getThemeFilterEvent($themeinfo['name'], 'admin-theme');
             }
         }
     }
     // set a new theme for the user
     $session = $request->getSession();
     $newtheme = $request->get('newtheme');
     if (!empty($newtheme) && System::getVar('theme_change')) {
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($newtheme));
         if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir(ZIKULA_ROOT . '/themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             if (self::isLoggedIn()) {
                 self::setVar('theme', $newtheme);
             } else {
                 $session->set('theme', $newtheme);
             }
             return self::_getThemeFilterEvent($themeinfo['name'], 'new-theme');
         }
     }
     // User theme
     if (System::getVar('theme_change') || SecurityUtil::checkPermission('::', '::', ACCESS_ADMIN)) {
         if (self::isLoggedIn()) {
             $usertheme = self::getVar('theme');
         } else {
             $usertheme = $session->get('theme');
         }
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($usertheme));
         if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir(ZIKULA_ROOT . '/themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             return self::_getThemeFilterEvent($themeinfo['name'], 'user-theme');
         }
     }
     // default site theme
     $defaulttheme = System::getVar('Default_Theme');
     $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($defaulttheme));
     if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir(ZIKULA_ROOT . '/themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
         return self::_getThemeFilterEvent($themeinfo['name'], 'default-theme');
     }
     if (!System::isInstalling()) {
         throw new RuntimeException(__('UserUtil::getTheme() is unable to calculate theme name.'));
     }
 }
Пример #21
0
if ($action === 'upgrademodules' || $action === 'convertdb' || $action === 'sanitycheck') {
    $username = FormUtil::getPassedValue('username', null, 'POST');
    $password = FormUtil::getPassedValue('password', null, 'POST');
    $authenticationInfo = array('login_id' => $username, 'pass' => $password);
    $authenticationMethod = array('modname' => 'Users', 'method' => 'uname');
    if (!UserUtil::loginUsing($authenticationMethod, $authenticationInfo)) {
        // force action to login
        $action = 'login';
    } else {
        define('_ZINSTALLEDVERSION', $installedVersion);
    }
}
// check if the default theme is compatible with Zikula >= 1.3
$themeName = System::getVar('Default_Theme');
$themeId = ThemeUtil::getIDFromName($themeName);
$theme = ThemeUtil::getInfo($themeId);
$directory = $theme['directory'];
if (!file_exists('themes/' . $directory . '/templates/master.tpl')) {
    if (ThemeUtil::getIDFromName('Andreas08') && file_exists('themes/Andreas08/templates/master.tpl')) {
        System::setVar('Default_Theme', 'Andreas08');
    } elseif (ThemeUtil::getIDFromName('SeaBreeze') && file_exists('themes/SeaBreeze/templates/master.tpl')) {
        System::setVar('Default_Theme', 'SeaBreeze');
    } else {
        _upg_header();
        echo '<p class="z-errormsg">' . __('Theme is not valid!') . '</p>' . "\n";
        _upg_footer();
        die;
    }
}
// deactivate file based shorturls
if (System::getVar('shorturls') && System::getVar('shorturlstype')) {
Пример #22
0
 /**
  * Get the user's theme.
  *
  * This function will return the current theme for the user.
  * Order of theme priority:
  *  - page-specific
  *  - category
  *  - user
  *  - system
  *
  * @param boolean $force True to ignore the cache.
  *
  * @return string           the name of the user's theme
  * @throws RuntimeException If this function was unable to calculate theme name.
  */
 public static function getTheme($force = false)
 {
     // if this method is called from the command line scope, always return a default core theme (ZikulaAndreas08Theme)
     // this prevents calls for the Request object or other unwanted behaviors.
     if (php_sapi_name() == 'cli') {
         return 'ZikulaAndreas08Theme';
     }
     static $pagetheme;
     if (isset($pagetheme) && !$force) {
         return $pagetheme;
     }
     /** @var $request Request */
     $request = \ServiceUtil::get('request');
     $theme = FormUtil::getPassedValue('theme', null, 'GETPOST');
     if (!empty($theme) && SecurityUtil::checkPermission('ZikulaThemeModule::ThemeChange', '::', ACCESS_COMMENT)) {
         // theme passed as parameter takes priority, can be RSS, Atom, Printer or other
         $pagetheme = $theme;
     } else {
         // check for specified alternative site view domain and theme
         $themedomain = ModUtil::getVar('ZikulaThemeModule', 'alt_theme_domain', '');
         if ($themedomain && $_SERVER['SERVER_NAME'] == $themedomain && ModUtil::getVar('ZikulaThemeModule', 'alt_theme_name', '')) {
             $pagetheme = ModUtil::getVar('ZikulaThemeModule', 'alt_theme_name');
         }
     }
     // Retrieve required parameters
     $type = FormUtil::getPassedValue('type', null, 'GETPOST');
     $legacyType = FormUtil::getPassedValue('lct', null, 'GETPOST');
     if ($type != $legacyType) {
         // BC support (see #2051 for example)
         $type = $legacyType;
     }
     if (null === $type) {
         // routing preventing type from being set, get from request attributes
         $type = $request->get('_zkType');
     }
     // Page-specific theme
     $qstring = System::serverGetVar('QUERY_STRING');
     if (!empty($pagetheme)) {
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($pagetheme));
         if ($themeinfo['state'] == ThemeUtil::STATE_ACTIVE && ($themeinfo['user'] || $themeinfo['system'] || $themeinfo['admin'] && $type == 'admin') && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             $pagetheme = $themeinfo['name'];
             $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'page-specific');
             $request->attributes->set('_theme', $themeName);
             return $themeName;
         }
     }
     // check for an admin theme
     // first setting the theme from the method annotation (Core-2.0 FC)
     $router = ServiceUtil::get('router');
     try {
         $parameters = $router->matchRequest($request);
         if (strpos($parameters['_controller'], '::')) {
             list($controllerName, $controllerMethod) = explode('::', $parameters['_controller'], 2);
             $newAdminTheme = ServiceUtil::get('zikula_core.common.theme_engine')->changeThemeByAnnotation($controllerName, $controllerMethod);
             if (false !== $newAdminTheme) {
                 $pagetheme = $newAdminTheme;
                 return $newAdminTheme;
             }
         }
     } catch (\Exception $e) {
         // was a homepage or something that doesn't matter. the request must be an admin route request to be changed.
     }
     $adminSections = array('admin', 'adminplugin');
     if (in_array($type, $adminSections) && SecurityUtil::checkPermission('::', '::', ACCESS_EDIT)) {
         $admintheme = ModUtil::getVar('ZikulaAdminModule', 'admintheme');
         if (!empty($admintheme)) {
             $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($admintheme));
             if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
                 $pagetheme = $themeinfo['name'];
                 $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'admin-theme');
                 $request->attributes->set('_theme', $themeName);
                 return $themeName;
             }
         }
     }
     // set a new theme for the user
     $newtheme = FormUtil::getPassedValue('newtheme', null, 'GETPOST');
     if (!empty($newtheme) && System::getVar('theme_change')) {
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($newtheme));
         if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             if (self::isLoggedIn()) {
                 self::setVar('theme', $newtheme);
             } else {
                 SessionUtil::setVar('theme', $newtheme);
             }
             $pagetheme = $themeinfo['name'];
             $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'new-theme');
             $request->attributes->set('_theme', $themeName);
             return $themeName;
         }
     }
     // User theme
     if (System::getVar('theme_change') || SecurityUtil::checkPermission('::', '::', ACCESS_ADMIN)) {
         if (self::isLoggedIn()) {
             $usertheme = self::getVar('theme');
         } else {
             $usertheme = SessionUtil::getVar('theme');
         }
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($usertheme));
         if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             $pagetheme = $themeinfo['name'];
             $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'user-theme');
             $request->attributes->set('_theme', $themeName);
             return $themeName;
         }
     }
     // default site theme
     $defaulttheme = System::getVar('Default_Theme');
     $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($defaulttheme));
     if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
         $pagetheme = $themeinfo['name'];
         $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'default-theme');
         $request->attributes->set('_theme', $themeName);
         return $themeName;
     }
     if (!System::isInstalling()) {
         throw new RuntimeException(__('UserUtil::getTheme() is unable to calculate theme name.'));
     }
 }
Пример #23
0
 /**
  * Run a module function.
  *
  * @param string  $modname    The name of the module.
  * @param string  $type       The type of function to run.
  * @param string  $func       The specific function to run.
  * @param array   $args       The arguments to pass to the function.
  * @param boolean $api        Whether or not to execute an API (or regular) function.
  * @param string  $instanceof Perform instanceof checking of target class.
  *
  * @throws Zikula_Exception_NotFound If method was not found.
  * @throws InvalidArgumentException  If the controller is not an instance of the class specified in $instanceof.
  *
  * @return mixed.
  */
 public static function exec($modname, $type = 'user', $func = 'main', $args = array(), $api = false, $instanceof = null)
 {
     // define input, all numbers and booleans to strings
     $modname = isset($modname) ? (string) $modname : '';
     $ftype = $api ? 'api' : '';
     $loadfunc = $api ? 'ModUtil::loadApi' : 'ModUtil::load';
     // validate
     if (!System::varValidate($modname, 'mod')) {
         return null;
     }
     // Remove from 1.4
     if (System::isLegacyMode() && $modname == 'Modules') {
         LogUtil::log(__('Warning! "Modules" module has been renamed to "Extensions".  Please update your ModUtil::func() and ModUtil::apiFunc() calls.'));
         $modname = 'Extensions';
     }
     $modinfo = self::getInfo(self::getIDFromName($modname));
     $path = $modinfo['type'] == self::TYPE_SYSTEM ? 'system' : 'modules';
     $controller = null;
     $modfunc = null;
     $loaded = call_user_func_array($loadfunc, array($modname, $type));
     if (self::isOO($modname)) {
         $result = self::getCallable($modname, $type, $func, $api);
         if ($result) {
             $modfunc = $result['callable'];
             $controller = $modfunc[0];
             if (!is_null($instanceof)) {
                 if (!$controller instanceof $instanceof) {
                     throw new InvalidArgumentException(__f('%1$s must be an instance of $2$s', array(get_class($controller), $instanceof)));
                 }
             }
         }
     }
     $modfunc = $modfunc ? $modfunc : "{$modname}_{$type}{$ftype}_{$func}";
     $eventManager = EventUtil::getManager();
     if ($loaded) {
         $preExecuteEvent = new Zikula_Event('module_dispatch.preexecute', $controller, array('modname' => $modname, 'modfunc' => $modfunc, 'args' => $args, 'modinfo' => $modinfo, 'type' => $type, 'api' => $api));
         $postExecuteEvent = new Zikula_Event('module_dispatch.postexecute', $controller, array('modname' => $modname, 'modfunc' => $modfunc, 'args' => $args, 'modinfo' => $modinfo, 'type' => $type, 'api' => $api));
         if (is_callable($modfunc)) {
             $eventManager->notify($preExecuteEvent);
             // Check $modfunc is an object instance (OO) or a function (old)
             if (is_array($modfunc)) {
                 if ($modfunc[0] instanceof Zikula_AbstractController) {
                     $reflection = call_user_func(array($modfunc[0], 'getReflection'));
                     $subclassOfReflection = new ReflectionClass($reflection->getParentClass());
                     if ($subclassOfReflection->hasMethod($modfunc[1])) {
                         // Don't allow front controller to access any public methods inside the controller's parents
                         throw new Zikula_Exception_NotFound();
                     }
                     $modfunc[0]->preDispatch();
                 }
                 $postExecuteEvent->setData(call_user_func($modfunc, $args));
                 if ($modfunc[0] instanceof Zikula_AbstractController) {
                     $modfunc[0]->postDispatch();
                 }
             } else {
                 $postExecuteEvent->setData($modfunc($args));
             }
             return $eventManager->notify($postExecuteEvent)->getData();
         }
         // get the theme
         if (ServiceUtil::getManager()->getService('zikula')->getStage() & Zikula_Core::STAGE_THEME) {
             $theme = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));
             if (file_exists($file = 'themes/' . $theme['directory'] . '/functions/' . $modname . "/{$type}{$ftype}/{$func}.php") || file_exists($file = 'themes/' . $theme['directory'] . '/functions/' . $modname . "/pn{$type}{$ftype}/{$func}.php")) {
                 include_once $file;
                 if (function_exists($modfunc)) {
                     EventUtil::notify($preExecuteEvent);
                     $postExecuteEvent->setData($modfunc($args));
                     return EventUtil::notify($postExecuteEvent)->getData();
                 }
             }
         }
         if (file_exists($file = "config/functions/{$modname}/{$type}{$ftype}/{$func}.php") || file_exists($file = "config/functions/{$modname}/pn{$type}{$ftype}/{$func}.php")) {
             include_once $file;
             if (is_callable($modfunc)) {
                 $eventManager->notify($preExecuteEvent);
                 $postExecuteEvent->setData($modfunc($args));
                 return $eventManager->notify($postExecuteEvent)->getData();
             }
         }
         if (file_exists($file = "{$path}/{$modname}/{$type}{$ftype}/{$func}.php") || file_exists($file = "{$path}/{$modname}/pn{$type}{$ftype}/{$func}.php")) {
             include_once $file;
             if (is_callable($modfunc)) {
                 $eventManager->notify($preExecuteEvent);
                 $postExecuteEvent->setData($modfunc($args));
                 return $eventManager->notify($postExecuteEvent)->getData();
             }
         }
         // try to load plugin
         // This kind of eventhandler should
         // 1. Check $event['modfunc'] to see if it should run else exit silently.
         // 2. Do something like $result = {$event['modfunc']}({$event['args'});
         // 3. Save the result $event->setData($result).
         // 4. $event->setNotify().
         // return void
         // This event means that no $type was found
         $event = new Zikula_Event('module_dispatch.type_not_found', null, array('modfunc' => $modfunc, 'args' => $args, 'modinfo' => $modinfo, 'type' => $type, 'api' => $api), false);
         $eventManager->notify($event);
         if ($preExecuteEvent->isStopped()) {
             return $preExecuteEvent->getData();
         }
         return false;
     }
     // Issue not found exception for controller requests
     if (!System::isLegacyMode() && !$api) {
         throw new Zikula_Exception_NotFound(__f('The requested controller action %s_Controller_%s::%s() could not be found', array($modname, $type, $func)));
     }
 }
Пример #24
0
 /**
  * Get the user's theme.
  *
  * This function will return the current theme for the user.
  * Order of theme priority:
  *  - page-specific
  *  - category
  *  - user
  *  - system
  *
  * @param boolean $force True to ignore the cache.
  *
  * @return string           the name of the user's theme
  * @throws RuntimeException If this function was unable to calculate theme name.
  */
 public static function getTheme($force = false)
 {
     static $pagetheme;
     if (isset($pagetheme) && !$force) {
         return $pagetheme;
     }
     /** @var $request Request */
     $request = \ServiceUtil::get('request');
     $theme = FormUtil::getPassedValue('theme', null, 'GETPOST');
     if (!empty($theme) && SecurityUtil::checkPermission('ZikulaThemeModule::ThemeChange', '::', ACCESS_COMMENT)) {
         // theme passed as parameter takes priority, can be RSS, Atom, Printer or other
         $pagetheme = $theme;
     } else {
         // check for specified alternative site view domain and theme
         $themedomain = ModUtil::getVar('ZikulaThemeModule', 'alt_theme_domain', '');
         if ($themedomain && $_SERVER['SERVER_NAME'] == $themedomain && ModUtil::getVar('ZikulaThemeModule', 'alt_theme_name', '')) {
             $pagetheme = ModUtil::getVar('ZikulaThemeModule', 'alt_theme_name');
         }
     }
     // Retrieve required parameters
     $type = FormUtil::getPassedValue('type', null, 'GETPOST');
     $legacyType = FormUtil::getPassedValue('lct', null, 'GETPOST');
     if ($type != $legacyType) {
         // BC support (see #2051 for example)
         $type = $legacyType;
     }
     if (null === $type) {
         // routing preventing type from being set, get from request attributes
         $type = $request->get('_zkType');
     }
     // Page-specific theme
     $qstring = System::serverGetVar('QUERY_STRING');
     if (!empty($pagetheme)) {
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($pagetheme));
         if ($themeinfo['state'] == ThemeUtil::STATE_ACTIVE && ($themeinfo['user'] || $themeinfo['system'] || $themeinfo['admin'] && $type == 'admin') && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             $pagetheme = $themeinfo['name'];
             $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'page-specific');
             $request->attributes->set('_theme', $themeName);
             return $themeName;
         }
     }
     // check for an admin theme
     $adminSections = array('admin', 'adminplugin');
     if (in_array($type, $adminSections) && SecurityUtil::checkPermission('::', '::', ACCESS_EDIT)) {
         $admintheme = ModUtil::getVar('ZikulaAdminModule', 'admintheme');
         if (!empty($admintheme)) {
             $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($admintheme));
             if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
                 $pagetheme = $themeinfo['name'];
                 $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'admin-theme');
                 $request->attributes->set('_theme', $themeName);
                 return $themeName;
             }
         }
     }
     // set a new theme for the user
     $newtheme = FormUtil::getPassedValue('newtheme', null, 'GETPOST');
     if (!empty($newtheme) && System::getVar('theme_change')) {
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($newtheme));
         if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             if (self::isLoggedIn()) {
                 self::setVar('theme', $newtheme);
             } else {
                 SessionUtil::setVar('theme', $newtheme);
             }
             $pagetheme = $themeinfo['name'];
             $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'new-theme');
             $request->attributes->set('_theme', $themeName);
             return $themeName;
         }
     }
     // User theme
     if (System::getVar('theme_change') || SecurityUtil::checkPermission('::', '::', ACCESS_ADMIN)) {
         if (self::isLoggedIn()) {
             $usertheme = self::getVar('theme');
         } else {
             $usertheme = SessionUtil::getVar('theme');
         }
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($usertheme));
         if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             $pagetheme = $themeinfo['name'];
             $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'user-theme');
             $request->attributes->set('_theme', $themeName);
             return $themeName;
         }
     }
     // default site theme
     $defaulttheme = System::getVar('Default_Theme');
     $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($defaulttheme));
     if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
         $pagetheme = $themeinfo['name'];
         $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'default-theme');
         $request->attributes->set('_theme', $themeName);
         return $themeName;
     }
     if (!System::isInstalling()) {
         throw new RuntimeException(__('UserUtil::getTheme() is unable to calculate theme name.'));
     }
 }
Пример #25
0
 /**
  * Decode the path string into a set of variable/value pairs.
  *
  * This API works in conjunction with the new short urls
  * system to extract a path based variable set into the Get, Post
  * and request superglobals.
  * A sample path is /modname/function/var1:value1.
  *
  * @return void
  */
 public static function queryStringDecode()
 {
     if (self::isInstalling()) {
         return;
     }
     // get our base parameters to work out if we need to decode the url
     $module = FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $func = FormUtil::getPassedValue('func', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $type = FormUtil::getPassedValue('type', null, 'GETPOST', FILTER_SANITIZE_STRING);
     // check if we need to decode the url
     if (self::getVar('shorturls') && (empty($module) && empty($type) && empty($func))) {
         // user language is not set at this stage
         $lang = System::getVar('language_i18n', '');
         $customentrypoint = self::getVar('entrypoint');
         $expectEntrypoint = !self::getVar('shorturlsstripentrypoint');
         $root = empty($customentrypoint) ? 'index.php' : $customentrypoint;
         // check if we hit baseurl, e.g. domain.com/ and if we require the language URL
         // then we should redirect to the language URL.
         if (ZLanguage::isRequiredLangParam() && self::getCurrentUrl() == self::getBaseUrl()) {
             $uri = $expectEntrypoint ? "{$root}/{$lang}" : "{$lang}";
             self::redirect(self::getBaseUrl() . $uri);
             self::shutDown();
         }
         // check if entry point is part of the URL expectation.  If so throw error if it's not present
         // since this URL is technically invalid.
         if ($expectEntrypoint && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) !== 0) {
             $protocol = System::serverGetVar('SERVER_PROTOCOL');
             header("{$protocol} 404 Not Found");
             echo __('The requested URL cannot be found');
             system::shutDown();
         }
         if (!$expectEntrypoint && self::getCurrentUrl() == self::getBaseUrl() . $root) {
             self::redirect(self::getHomepageUrl());
             self::shutDown();
         }
         if (!$expectEntrypoint && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) === 0) {
             $protocol = System::serverGetVar('SERVER_PROTOCOL');
             header("{$protocol} 404 Not Found");
             echo __('The requested URL cannot be found');
             system::shutDown();
         }
         // get base path to work out our current url
         $parsedURL = parse_url(self::getCurrentUri());
         // strip any unwanted content from the provided URL
         $tobestripped = array(self::getBaseUri(), "{$root}");
         $path = str_replace($tobestripped, '', $parsedURL['path']);
         $path = trim($path, '/');
         // split the path into a set of argument strings
         $args = explode('/', rtrim($path, '/'));
         // ensure that each argument is properly decoded
         foreach ($args as $k => $v) {
             $args[$k] = urldecode($v);
         }
         $modinfo = null;
         $frontController = $expectEntrypoint ? "{$root}/" : '';
         // if no arguments present
         if (!$args[0] && !isset($_GET['lang']) && !isset($_GET['theme'])) {
             // we are in the homepage, checks if language code is forced
             if (ZLanguage::getLangUrlRule() && $lang) {
                 // and redirect then
                 $response = new RedirectResponse(self::getCurrentUrl() . "/{$lang}");
                 $respose->send();
                 System::shutDown();
             }
         } else {
             // check the existing shortURL parameters
             // validation of the first parameter as language code
             if (ZLanguage::isLangParam($args[0]) && in_array($args[0], ZLanguage::getInstalledLanguages())) {
                 // checks if the language is not enforced and this url is passing the default lang
                 if (!ZLanguage::getLangUrlRule() && $lang == $args[0]) {
                     // redirects the passed arguments without the default site language
                     array_shift($args);
                     foreach ($args as $k => $v) {
                         $args[$k] = urlencode($v);
                     }
                     $response = new RedirectResponse(self::getBaseUrl() . $frontController . ($args ? implode('/', $args) : ''));
                     $respose->send();
                     System::shutDown();
                 }
                 self::queryStringSetVar('lang', $args[0]);
                 array_shift($args);
             } elseif (ZLanguage::getLangUrlRule()) {
                 // if the lang is forced, redirects the passed arguments plus the lang
                 foreach ($args as $k => $v) {
                     $args[$k] = urlencode($v);
                 }
                 $langTheme = isset($_GET['theme']) ? "{$lang}/{$_GET['theme']}" : $lang;
                 $response = new RedirectResponse(self::getBaseUrl() . $frontController . $langTheme . '/' . implode('/', $args));
                 $response->send();
                 System::shutDown();
             }
             // check if there are remaining arguments
             if ($args) {
                 // try the first argument as a module
                 $modinfo = ModUtil::getInfoFromName($args[0]);
                 if ($modinfo) {
                     array_shift($args);
                 }
             }
             // if that fails maybe it's a theme
             if ($args && !$modinfo) {
                 $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($args[0]));
                 if ($themeinfo) {
                     self::queryStringSetVar('theme', $themeinfo['name']);
                     // now shift the vars and continue as before
                     array_shift($args);
                     if ($args) {
                         $modinfo = ModUtil::getInfoFromName($args[0]);
                         if ($modinfo) {
                             array_shift($args);
                         }
                     }
                 }
             }
             // if there are parameters (not homepage)
             // try to see if there's a default shortURLs module
             if ($args && !$modinfo) {
                 // add the default module handler into the code
                 $modinfo = ModUtil::getInfoFromName(self::getVar('shorturlsdefaultmodule'));
             }
         }
         // check if there is a module and a custom url handler for it
         // if not decode the url using the default handler
         if ($modinfo && $modinfo['type'] != 0) {
             // prepare the arguments to the module handler
             array_unshift($args, '');
             // support for 1.2- empty parameter due the initial explode
             array_unshift($args, $modinfo['url']);
             // set the REQUEST parameters
             self::queryStringSetVar('module', $modinfo['name']);
             // the user.function name can be the second argument string, set a default
             // later the custom module handler (if exists) must setup a new one if needed
             self::queryStringSetVar('type', 'user');
             if (isset($args[2])) {
                 self::queryStringSetVar('func', $args[2]);
             } else {
                 self::queryStringSetVar('func', 'index');
             }
             if (!ModUtil::apiFunc($modinfo['name'], 'user', 'decodeurl', array('vars' => $args))) {
                 // any remaining arguments are specific to the module
                 $argscount = count($args);
                 for ($i = 3; $i < $argscount; $i = $i + 2) {
                     if (isset($args[$i]) && isset($args[$i + 1])) {
                         self::queryStringSetVar($args[$i], urldecode($args[$i + 1]));
                     }
                 }
             }
         }
     }
 }
Пример #26
0
    /**
     * write an ini file to the running configuration directory
     */
    public function writeinifile($args)
    {
        // check our input
        if (!isset($args['file']) || empty($args['file'])) {
            return LogUtil::registerArgsError();
        }

        if (!isset($args['theme']) || empty($args['theme'])) {
            return LogUtil::registerArgsError();
        }

        // get the theme info
        $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($args['theme']));

        $content = ModUtil::apiFunc('theme', 'user', 'createinifile', array('has_sections' => $args['has_sections'], 'assoc_arr' => $args['assoc_arr']));

        $ostemp  = CacheUtil::getLocalDir();
        $ostheme = DataUtil::formatForOS($themeinfo['directory']);
        $osfile  = DataUtil::formatForOS($args['file']);

        // verify the writable paths
        $tpath = 'themes/'.$ostheme.'/templates/config';

        if (is_writable($tpath.'/'.$osfile)) {
            $handle = fopen($tpath.'/'.$osfile, 'w+');

        } else {
            if (!file_exists($zpath = $ostemp.'/Theme_Config/'.$ostheme)) {
                mkdir($zpath, $this->serviceManager['system.chmod_dir'], true);
            }

            if (!file_exists($zpath.'/'.$osfile) || is_writable($zpath.'/'.$osfile)) {
                $handle = fopen($zpath.'/'.$osfile, 'w+');
            } else {
                return LogUtil::registerError($this->__f("Error! Cannot write in '%1$s' or '%2$s' to store the contents of '%3$s'.", array($tpath, $zpath, $osfile)));
            }
        }

        // validate the resulting handler and the write operation result
        if (!isset($handle) || !is_resource($handle)) {
            return LogUtil::registerError($this->__f('Error! Could not open file so that it could be written to: %s', $osfile));

        } else {
            if (fwrite($handle, $content) === false) {
                fclose($handle);

                return LogUtil::registerError($this->__f('Error! Could not write to file: %s', $osfile));
            }
            fclose($handle);

            return true;
        }
    }