/** * Update module information. * * @param array $args All parameters passed to this function. * numeric $args['id'] The id number of the module to update. * string $args['displayname'] The new display name of the module. * string $args['description'] The new description of the module. * * @return boolean True on success, false on failure. */ public function update($args) { // Argument check if (!isset($args['id']) || !is_numeric($args['id']) || !isset($args['displayname']) || !isset($args['description']) || !isset($args['url'])) { return LogUtil::registerArgsError(); } // Security check if (!SecurityUtil::checkPermission('Extensions::', "::{$args['id']}", ACCESS_ADMIN)) { return LogUtil::registerPermissionError(); } // check for duplicate display names // get the module info for the module being updated $moduleinforeal = ModUtil::getInfo($args['id']); // validate URL $moduleinfourl = ModUtil::getInfoFromName($args['url']); // If the two real module name don't match then the new display name can't be used if ($moduleinfourl && $moduleinfourl['name'] != $moduleinforeal['name']) { return LogUtil::registerError($this->__('Error! Could not save the module URL information. A duplicate module URL was detected.')); } if (empty($args['url'])) { return LogUtil::registerError($this->__('Error! Module URL is a required field, please enter a unique name.')); } if (empty($args['displayname'])) { return LogUtil::registerError($this->__('Error! Module URL is a required field, please enter a unique name.')); } // Rename operation $obj = array('id' => $args['id'], 'displayname' => $args['displayname'], 'description' => $args['description'], 'url' => $args['url']); if (!DBUtil::updateObject($obj, 'modules')) { return LogUtil::registerError($this->__('Error! Could not save your changes.')); } return true; }
/** * Smarty function to display the category menu for admin links. This also adds the * navtabs.css to the page vars array for stylesheets. * * Admin * {admincategorymenu} * * @see function.admincategorymenu.php::smarty_function_admincategoreymenu() * @param array $params All attributes passed to this function from the template * @param object $view Reference to the Zikula_View object * @return string the results of the module function */ function smarty_function_admincategorymenu($params, $view) { PageUtil::addVar('stylesheet', ThemeUtil::getModuleStylesheet('Admin')); $modinfo = ModUtil::getInfoFromName($view->getTplVar('toplevelmodule')); $acid = ModUtil::apiFunc('AdminModule', 'admin', 'getmodcategory', array('mid' => $modinfo['id'])); return ModUtil::func('AdminModule', 'admin', 'categorymenu', array('acid' => $acid)); }
/** * Smarty function to display the category menu for admin links. This also adds the * navtabs.css to the page vars array for stylesheets. * * Admin * {admincategorymenu} * * @see function.admincategorymenu.php::smarty_function_admincategorymenu() * @param array $params All attributes passed to this function from the template * @param \Zikula_View $view Reference to the Zikula_View object * @return string the results of the module function */ function smarty_function_admincategorymenu($params, \Zikula_View $view) { PageUtil::addVar('stylesheet', ThemeUtil::getModuleStylesheet('ZikulaAdminModule')); $modinfo = ModUtil::getInfoFromName($view->getTplVar('toplevelmodule')); $acid = ModUtil::apiFunc('ZikulaAdminModule', 'admin', 'getmodcategory', array('mid' => $modinfo['id'])); $path = array('_controller' => 'ZikulaAdminModule:Admin:categorymenu', 'acid' => $acid); $subRequest = $view->getRequest()->duplicate(array(), null, $path); return $view->getContainer()->get('http_kernel')->handle($subRequest, \Symfony\Component\HttpKernel\HttpKernelInterface::SUB_REQUEST)->getContent(); }
/** * Returns the route's path prepended with the bundle prefix. * * @param null $container Can be used to set the container for \ServiceUtil in case it is not already set. * * @return string */ public function getPathWithBundlePrefix($container = null) { if (!isset($this->options['zkNoBundlePrefix']) || !$this->options['zkNoBundlePrefix']) { $bundle = $this->getBundle(); if (!\ServiceUtil::hasContainer()) { \ServiceUtil::setContainer($container); } $modinfo = \ModUtil::getInfoFromName($bundle); return "/" . $modinfo["url"] . $this->path; } return $this->path; }
/** * Smarty function to displaya modules online manual * * Admin * {adminonlinemanual} * * @see function.admincategorymenu.php::smarty_function_admincategoreymenu() * @param array $params All attributes passed to this function from the template * @param object $smarty Reference to the Smarty object * @param int xhtml if set, the link to the navtabs.css will be xhtml compliant * @return string the results of the module function */ function smarty_function_adminonlinemanual($params, $smarty) { LogUtil::log(__f('Warning! Template plugin {%1$s} is deprecated.', array('adminonlinemanual')), E_USER_DEPRECATED); $lang = ZLanguage::transformFS(ZLanguage::getLanguageCode()); $modinfo = ModUtil::getInfoFromName(ModUtil::getName()); $modpath = $modinfo['type'] == ModUtil::TYPE_SYSTEM ? 'system' : 'modules'; $file = DataUtil::formatForOS("{$modpath}/{$modinfo['directory']}/lang/{$lang}/manual.html"); $man_link = ''; if (is_readable($file)) { PageUtil::addVar('javascript', 'zikula.ui'); $man_link = '<div style="margin-top: 20px; text-align:center">[ <a id="online_manual" href="' . $file . '">' . __('Online manual') . '</a> ]</div>' . "\n"; $man_link .= '<script type="text/javascript">var online_manual = new Zikula.UI.Window($(\'online_manual\'),{resizable: true})</script>' . "\n"; } return $man_link; }
/** * Smarty function build module header in user content page. * * {moduleheader} * * Available parameters: * modname Module name to display header for (optional, defaults to current module) * type Type for module links (defaults to 'user') * title Title to display in header (optional, defaults to module name) * titlelink Link to attach to title (optional, defaults to none) * setpagetitle If set to true, {pagesetvar} is used to set page title * insertstatusmsg If set to true, {insert name='getstatusmsg'} is put in front of template * menufirst If set to true, menu is first, then title * putimage If set to true, module image is also displayed next to title * * @param array $params All attributes passed to this function from the template. * @param Zikula_View $view Reference to the Zikula_View object. * * @return string A formatted string containing navigation for the module admin panel. */ function smarty_function_moduleheader($params, $view) { if (!isset($params['modname']) || !ModUtil::available($params['modname'])) { $params['modname'] = ModUtil::getName(); } if (empty($params['modname'])) { return false; } $type = isset($params['type']) ? $params['type'] : 'user'; $assign = isset($params['assign']) ? $params['assign'] : null; $menufirst = isset($params['menufirst']) ? $params['menufirst'] : false; $putimage = isset($params['putimage']) ? $params['putimage'] : false; $setpagetitle = isset($params['setpagetitle']) ? $params['setpagetitle'] : false; $insertstatusmsg = isset($params['insertstatusmsg']) ? $params['insertstatusmsg'] : false; $cutlenght = isset($params['cutlenght']) ? $params['cutlenght'] : 20; if ($putimage) { $image = isset($params['image']) ? $params['image'] : ModUtil::getModuleImagePath($params['modname']); } else { $image = ''; } if (!isset($params['title'])) { $modinfo = ModUtil::getInfoFromName($params['modname']); if (isset($modinfo['displayname'])) { $params['title'] = $modinfo['displayname']; } else { $params['title'] = ModUtil::getName(); } } $titlelink = isset($params['titlelink']) ? $params['titlelink'] : false; $renderer = Zikula_View::getInstance('Theme'); $renderer->setCaching(Zikula_View::CACHE_DISABLED); $renderer->assign('userthemename', UserUtil::getTheme()); $renderer->assign('modname', $params['modname']); $renderer->assign('type', $params['type']); $renderer->assign('title', $params['title']); $renderer->assign('titlelink', $titlelink); $renderer->assign('truncated', mb_strlen($params['title']) > $cutlenght); $renderer->assign('titletruncated', mb_substr($params['title'], 0, $cutlenght) . '...'); $renderer->assign('setpagetitle', $setpagetitle); $renderer->assign('insertstatusmsg', $insertstatusmsg); $renderer->assign('menufirst', $menufirst); $renderer->assign('image', $image); if ($assign) { $view->assign($assign, $renderer->fetch('moduleheader.tpl')); } else { return $renderer->fetch('moduleheader.tpl'); } }
/** * Aggressively load models. * * This helper is required because we are using PEAR naming standards with * our own autoloading. Doctrine's model loading doesn't take this into * account in non agressive modes. * * In general, this method is NOT required. * * @param string $modname Module name to load models for. * * @return void */ public static function loadModels($modname) { $modname = isset($modname) ? strtolower((string) $modname) : ''; $modinfo = ModUtil::getInfoFromName($modname); $osdir = DataUtil::formatForOS($modinfo['directory']); $base = $modinfo['type'] == ModUtil::TYPE_MODULE ? 'modules' : 'system'; $dm = Doctrine_Manager::getInstance(); $save = $dm->getAttribute(Doctrine_Core::ATTR_MODEL_LOADING); $dm->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_AGGRESSIVE); $path = "{$base}/{$osdir}/lib/{$osdir}/Model"; // prevent exception when model folder does not exist if (file_exists($path)) { Doctrine_Core::loadModels(realpath($path)); } $dm->setAttribute(Doctrine::ATTR_MODEL_LOADING, $save); }
/** * Event handler. * * @param Zikula_Event $event Event. * * @return void */ public function handler(Zikula_Event $event) { // subject must be an instance of Theme class. $theme = $event->getSubject(); if (!$theme instanceof Theme) { return; } // register output filter to add MultiHook environment if requried if (ModUtil::available('MultiHook')) { $modinfo = ModUtil::getInfoFromName('MultiHook'); if (version_compare($modinfo['version'], '5.0', '>=') == 1) { $theme->load_filter('output', 'multihook'); ModUtil::apiFunc('MultiHook', 'theme', 'preparetheme'); } } }
/** * Zikula_View function to get all session variables. * * This function gets all session vars from the Zikula system assigns the names and * values to two array. This is being used in pndebug to show them. * * Example * {debugenvironment} * * @param array $params All attributes passed to this function from the template. * @param Zikula_View $view Reference to the Zikula_View object. * * @return void */ function smarty_function_debugenvironment($params, Zikula_View $view) { $view->assign('_ZSession_keys', array_keys($_SESSION)); $view->assign('_ZSession_vals', array_values($_SESSION)); $view->assign('_smartyversion', $view->_version); $_theme = ModUtil::getInfoFromName('ZikulaThemeModule'); $view->assign('_themeversion', $_theme['version']); $view->assign('_force_compile', ModUtil::getVar('ZikulaThemeModule', 'force_compile') ? __('On') : __('Off')); $view->assign('_compile_check', ModUtil::getVar('ZikulaThemeModule', 'compile_check') ? __('On') : __('Off')); $view->assign('_baseurl', System::getBaseUrl()); $view->assign('_baseuri', System::getBaseUri()); $plugininfo = isset($view->_plugins['function']['zdebug']) ? $view->_plugins['function']['zdebug'] : $view->_plugins['function']['zpopup']; $view->assign('_template', $plugininfo[1]); $view->assign('_path', $view->get_template_path($plugininfo[1])); $view->assign('_line', $plugininfo[2]); }
/** * 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) { return z_exit(__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}"; } else { if ($modinfo['type'] == ModUtil::TYPE_MODULE) { // non system module $modulepath = "modules/{$moduledir}"; } else { return z_exit(__f('%s: Unsupported module type.', 'Zikula_Workflow_Util')); } } // ensure module is active if (!$modinfo['state'] == 3) { return z_exit(__f('%1$s: The module [%2$s] is not active.', array('Zikula_Workflow_Util', $module))); } $themedir = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme())); $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; } else { if (is_readable($configpath)) { return $configpath; } else { if (is_readable($modulepath)) { return $modulepath; } else { return false; } } } }
public function newVersionAvailable() { $lastNewVersionCheck = \ModUtil::getVar('CmfcmfMediaModule', 'lastNewVersionCheck', 0); if (time() - 24 * 60 * 60 > $lastNewVersionCheck && $this->versionChecker->checkRateLimit()) { \ModUtil::setVar('CmfcmfMediaModule', 'lastNewVersionCheck', time()); $info = \ModUtil::getInfoFromName('CmfcmfMediaModule'); if (($release = $this->versionChecker->getReleaseToUpgradeTo($info['version'])) !== false) { \ModUtil::setVar('CmfcmfMediaModule', 'newVersionAvailable', $release['tag_name']); return $release['tag_name']; } } $newVersionAvailable = \ModUtil::getVar('CmfcmfMediaModule', 'newVersionAvailable', false); if ($newVersionAvailable != false) { return $newVersionAvailable; } return false; }
/** * {@inheritDoc} */ public function generateI18nPatterns($routeName, Route $route) { $patterns = array(); foreach ($route->getOption('i18n_locales') ?: $this->locales as $locale) { // Check if translation exists in the translation catalogue to avoid errors being logged by // the new LoggingTranslator of Symfony 2.6. However, the LoggingTranslator did not implement // the interface until Symfony 2.6.5, so an extra check is needed. if ($this->translator instanceof TranslatorBagInterface || $this->translator instanceof LoggingTranslator) { // Check if route is translated. if (!$this->translator->getCatalogue($locale)->has($routeName, $this->translationDomain)) { // No translation found. $i18nPattern = $route->getPath(); } else { // Get translation. $i18nPattern = $this->translator->trans($routeName, array(), $this->translationDomain, $locale); } } else { // if no translation exists, we use the current pattern if ($routeName === ($i18nPattern = $this->translator->trans($routeName, array(), $this->translationDomain, $locale))) { $i18nPattern = $route->getPath(); } } /////////////////////////////////////// // Begin customizations // prefix with zikula module url if requested if ($route->hasDefault('_zkModule')) { $zkNoBundlePrefix = $route->getOption('zkNoBundlePrefix'); if (!isset($zkNoBundlePrefix) || !$zkNoBundlePrefix) { $modinfo = \ModUtil::getInfoFromName($route->getDefault('_zkModule')); $i18nPattern = "/" . $modinfo["url"] . $i18nPattern; } } // End customizations /////////////////////////////////////// // prefix with locale if requested if (self::STRATEGY_PREFIX === $this->strategy || self::STRATEGY_PREFIX_EXCEPT_DEFAULT === $this->strategy && $this->defaultLocale !== $locale) { $i18nPattern = '/' . $locale . $i18nPattern; if (null !== $route->getOption('i18n_prefix')) { $i18nPattern = $route->getOption('i18n_prefix') . $i18nPattern; } } $patterns[$i18nPattern][] = $locale; } return $patterns; }
/** * display block */ public function display($blockinfo) { // Security check if (!SecurityUtil::checkPermission('Admin:adminnavblock', "{$blockinfo['title']}::{$blockinfo['bid']}", ACCESS_ADMIN)) { return; } // Get variables from content block $vars = BlockUtil::varsFromContent($blockinfo['content']); // Call the modules API to get the items if (!ModUtil::available('Admin')) { return; } $items = ModUtil::apiFunc('Admin', 'admin', 'getall'); // Check for no items returned if (empty($items)) { return; } // get admin capable modules $adminmodules = ModUtil::getAdminMods(); $adminmodulescount = count($adminmodules); // Display each item, permissions permitting $admincategories = array(); foreach ($items as $item) { if (SecurityUtil::checkPermission('Admin::', "{$item['catname']}::{$item['cid']}", ACCESS_READ)) { $adminlinks = array(); foreach ($adminmodules as $adminmodule) { // Get all modules in the category $catid = ModUtil::apiFunc('Admin', 'admin', 'getmodcategory', array('mid' => ModUtil::getIdFromName($adminmodule['name']))); if ($catid == $item['cid'] || $catid == false && $item['cid'] == $this->getVar('defaultcategory')) { $modinfo = ModUtil::getInfoFromName($adminmodule['name']); $menutexturl = ModUtil::url($modinfo['name'], 'admin'); $menutexttitle = $modinfo['displayname']; $adminlinks[] = array('menutexturl' => $menutexturl, 'menutexttitle' => $menutexttitle); } } $admincategories[] = array('url' => ModUtil::url('Admin', 'admin', 'adminpanel', array('cid' => $item['cid'])), 'title' => DataUtil::formatForDisplay($item['catname']), 'modules' => $adminlinks); } } $this->view->assign('admincategories', $admincategories); // Populate block info and pass to theme $blockinfo['content'] = $this->view->fetch('admin_block_adminnav.tpl'); return BlockUtil::themeBlock($blockinfo); }
/** * Populate pntables array for Users module. * * This function is called internally by the core whenever the module is * loaded. It delivers the table information to the core. * It can be loaded explicitly using the ModUtil::dbInfoLoad() API function. * * @param string $forVersion The module version number for which db information should be returned. * * @return array The table information. */ function ZikulaUsersModule_tables($forVersion = null) { if (!isset($forVersion)) { if (isset($GLOBALS['_ZikulaUpgrader']['_ZikulaUpgradeFrom12x']) && $GLOBALS['_ZikulaUpgrader']['_ZikulaUpgradeFrom12x']) { // This check comes before System::isInstalling(). return Users_tables_for_113(); } if (System::isInstalling()) { // new installs return Users_tables_for_220(); } // Remaining cases - this should be deleted. $usersModInfo = ModUtil::getInfoFromName('ZikulaUsersModule'); $forVersion = $usersModInfo['version']; } if (version_compare($forVersion, '2.2.0') >= 0) { return Users_tables_for_220(); } else { return Users_tables_for_113(); } }
public function display($blockinfo) { // security check $this->throwForbiddenUnless(SecurityUtil::checkPermission('Content:SubPagesBlock:', "{$blockinfo['title']}::", ACCESS_READ), LogUtil::getErrorMsgPermission()); // Break out options from our content field $vars = BlockUtil::varsFromContent($blockinfo['content']); // --- Setting of the Defaults if (!isset($vars['usecaching'])) { $vars['usecaching'] = false; } if (!isset($vars['checkinmenu'])) { $vars['checkinmenu'] = true; } // decode the query string (works with and without shorturls) System::queryStringDecode(); $query['module'] = isset($_REQUEST['module']) ? $_REQUEST['module'] : 'notcontent'; $query['func'] = isset($_REQUEST['func']) ? $_REQUEST['func'] : 'notview'; $query['pid'] = isset($_REQUEST['pid']) ? $_REQUEST['pid'] : 0; $this->view->setCacheId($blockinfo['bid']); $this->view->setCaching($vars['usecaching']); if (!$vars['usecaching'] || $vars['usecaching'] && !$this->view->is_cached('block/subpages.tpl')) { $modinfo = ModUtil::getInfoFromName('content'); if (strtolower($query['module']) == $modinfo['url'] && strtolower($query['func']) == 'view' && $query['pid'] > 0) { $options = array('orderBy' => 'setLeft', 'makeTree' => true, 'includeContent' => false, 'enableEscape' => false, 'filter' => array()); // checkInMenu, checkActive is done implicitely $options['filter']['checkInMenu'] = $vars['checkinmenu']; $options['filter']['parentId'] = $query['pid']; $pages = ModUtil::apiFunc('Content', 'Page', 'getPages', $options); if ($pages === false) { return false; } } else { $pages = null; } $this->view->assign('subPages', $pages); } $blockinfo['content'] = $this->view->fetch('block/subpages.tpl'); return BlockUtil::themeBlock($blockinfo); }
/** * Simple PEAR autoloader and handling for non-PEAR classes. * * @param string $class Class name. * * @return boolean */ public static function autoload($class) { // load from maps $map = self::$map; if (isset($map[$class])) { $path = ZLOADER_PATH . "$map[$class]/$class.php"; if (file_exists($path)) { return include $path; } } // Classloader for SystemPlugin if (strpos($class, 'SystemPlugin') === 0) { $array = explode('_', $class); $pluginName = $array[1]; $name = substr($class, strlen("SystemPlugin_{$pluginName}") + 1, strlen($class)); $path = str_replace('_', '/', "plugins/$pluginName/lib/$pluginName/$name.php"); if (file_exists($path)) { return include $path; } } // Classloader for ModulePlugin if (strpos($class, 'ModulePlugin') === 0) { $array = explode('_', $class); $moduleName = $array[1]; $pluginName = $array[2]; $modinfo = ModUtil::getInfoFromName($moduleName); $base = ($modinfo['type'] == ModUtil::TYPE_MODULE) ? 'modules' : 'system'; $name = substr($class, strlen("ModulePlugin_{$moduleName}_{$pluginName}") + 1, strlen($class)); $path = str_replace('_', '/', "$base/$moduleName/plugins/$pluginName/lib/$pluginName/$name.php"); if (file_exists($path)) { return include $path; } } // Classloader for ModulePlugin if (strpos($class, 'Themes') === 0) { $array = explode('_', $class); $themeName = $array[1]; $name = substr($class, strlen("Themes") + 1, strlen($class)); $path = str_replace('_', '/', "themes/$themeName/lib/$name.php"); if (file_exists($path)) { return include $path; } } // generic PEAR style namespace to path, i.e Foo_Bar -> Foo/Bar.php if (strpos($class, '_')) { $array = explode('_', $class); $prefix = (isset($map[$array[0]]) ? $map[$array[0]] . '/' : ''); $path = ZLOADER_PATH . $prefix . str_replace('_', '/', $class) . '.php'; if (file_exists($path)) { return include $path; } } $file = "lib/$class.php"; if (file_exists($file)) { return include $file; } }
/** * Get module info. * * @return array */ public function getModInfo() { if (!$this->modinfo) { $this->modinfo = ModUtil::getInfoFromName($this->name); } return $this->modinfo; }
/** * Validation method previous authentication. * * @param array $authenticationMethod Auth method. * @param string $reentrantURL Reentrant URL (optional). * * @throws Zikula_Exception_Fatal * * @return true */ private static function preAuthenticationValidation(array $authenticationMethod, $reentrantURL = null) { if (empty($authenticationMethod) || count($authenticationMethod) != 2) { throw new Zikula_Exception_Fatal(__f('An invalid %1$s parameter was received.', array('authenticationMethod'))); } if (!isset($authenticationMethod['modname']) || !is_string($authenticationMethod['modname']) || empty($authenticationMethod['modname'])) { throw new Zikula_Exception_Fatal(__f('An invalid %1$s parameter was received.', array('modname'))); } elseif (!ModUtil::getInfoFromName($authenticationMethod['modname'])) { throw new Zikula_Exception_Fatal(__f('The authentication module \'%1$s\' could not be found.', array($authenticationMethod['modname']))); } elseif (!ModUtil::available($authenticationMethod['modname'])) { throw new Zikula_Exception_Fatal(__f('The authentication module \'%1$s\' is not available.', array($authenticationMethod['modname']))); } elseif (!ModUtil::loadApi($authenticationMethod['modname'], 'Authentication')) { throw new Zikula_Exception_Fatal(__f('The authentication module \'%1$s\' could not be loaded.', array($authenticationMethod['modname']))); } if (!isset($authenticationMethod['method']) || !is_string($authenticationMethod['method']) || empty($authenticationMethod['method'])) { throw new Zikula_Exception_Fatal(__f('An invalid %1$s parameter was received.', array('method'))); } elseif (!ModUtil::apiFunc($authenticationMethod['modname'], 'Authentication', 'supportsAuthenticationMethod', array('method' => $authenticationMethod['method']), 'Zikula_Api_AbstractAuthentication')) { throw new Zikula_Exception_Fatal(__f('The authentication method \'%1$s\' is not supported by the authentication module \'%2$s\'.', array($authenticationMethod['method'], $authenticationMethod['modname']))); } if (ModUtil::apiFunc($authenticationMethod['modname'], 'Authentication', 'isReentrant', null, 'Zikula_Api_AbstractAuthentication') && (!isset($reentrantURL) || empty($reentrantURL))) { throw new Zikula_Exception_Fatal(__f('The authentication module \'%1$s\' is reentrant. A %2$s is required.', array($authenticationMethod['modname'], 'reentrantURL'))); } return true; }
/** * Get the modules stylesheet from several possible sources. * * @param string $modname The modules name (optional, defaults to top level module). * @param string $stylesheet The stylesheet file (optional). * * @return string Path of the stylesheet file, relative to PN root folder. */ public static function getModuleStylesheet($modname = '', $stylesheet = '') { // default for the module if (empty($modname)) { $modname = ModUtil::getName(); } $modname = preg_match('/\\w+Module$/', $modname) ? $modname : $modname . 'Module'; // default for the style sheet if (empty($stylesheet)) { $stylesheet = ModUtil::getVar($modname, 'modulestylesheet'); if (empty($stylesheet)) { $stylesheet = 'style.css'; } } $osstylesheet = DataUtil::formatForOS($stylesheet); $osmodname = DataUtil::formatForOS($modname); // config directory $configstyledir = 'config/style'; $configpath = "{$configstyledir}/{$osmodname}"; // theme directory $theme = DataUtil::formatForOS(UserUtil::getTheme()); $themepath = "themes/{$theme}/Resources/public/css/{$osmodname}"; // module directory $modinfo = ModUtil::getInfoFromName($modname); $osmoddir = DataUtil::formatForOS($modinfo['directory']); $modpath = "modules/{$osmoddir}/Resources/public/css"; $syspath = "system/{$osmoddir}/Resources/public/css"; // search for the style sheet $csssrc = ''; foreach (array($configpath, $themepath, $modpath, $syspath) as $path) { if (is_readable("{$path}/{$osstylesheet}")) { $csssrc = "{$path}/{$osstylesheet}"; break; } } return $csssrc; }
/** * Get module info. * * @return array */ public function getModInfo() { if (!$this->modinfo) { // this is deliberate lazy load for dependency. $this->modinfo = \ModUtil::getInfoFromName($this->moduleName); } return $this->modinfo; }
/** * Loads a single plugin. * * @param string $name Plugin's name. * @param array $config Plugin's config. * * @return integer The plugin's id. */ public function loadPluginLegacy($name, $config = array()) { $module = $this->getConfig()->getModule(); if (strpos($name, '@')) { list($module, $name) = explode('@', $name, 2); } if ($this->isLoaded("{$module}@{$name}")) { return true; } $class = 'FilterUtil_Filter_' . $name; $file = 'filter.' . $name . '.class.php'; // Load hierarchy $dest = array(); if ($module != 'core' && ModUtil::available($module)) { $modinfo = ModUtil::getInfoFromName($module); $modpath = $modinfo['type'] == ModUtil::TYPE_SYSTEM ? 'system' : 'modules'; $directory = $modinfo['directory']; $dest[] = "config/filter/{$directory}/{$file}"; $dest[] = "{$modpath}/{$directory}/filter/{$file}"; } $dest[] = "config/filter/{$file}"; Loader::loadOneFile($dest); $config = array(); $this->addCommon($config); $obj = new $class($config); $this->_plg[] = $obj; end($this->_plg); $key = key($this->_plg); $obj =& $this->_plg[$key]; $obj->setID($key); $this->_registerPlugin($key); $this->_loaded["{$module}@{$name}"] = $key; return key(end($this->_plg)); }
/** * Zikula_View function to provide easy access to an image * * This function provides an easy way to include an image. The function will return the * full source path to the image. It will as well provite the width and height attributes * if none are set. * * Available parameters: * - src The file name of the image * - modname The well-known name of a module (default: the current module) * - modplugin The name of the plugin in the passed module * - sysplugin The name of the system plugin * - width, height If set, they will be passed. If none is set, they are obtained from the image * - alt If not set, an empty string is being assigned * - title If set it will be passed as a title attribute * - assign If set, the results are assigned to the corresponding variable instead of printed out * - optional If set then the plugin will not return an error if an image is not found * - default If set then a default image is used should the requested image not be found (Note: full path required) * - set If modname is 'core' then the set parameter is set to define the directory in /images/ * - nostoponerror If set and error ocurs (image not found or src is no image), do not trigger_error, but return false * - retval If set indicated the field to return instead the array of values (src, width, etc.) * - fqurl If set the image path is absolute, if not relative * - all remaining parameters are passed to the image tag * * Example: {img src='heading.png'} * Output: <img src="modules/Example/images/en/heading.png" alt="" width="261" height="69" /> * * Example: {img src='heading.png' width='100' border='1' __alt='foobar'} * Output: <img src="modules/Example/images/en/heading.png" width="100" border="1" alt="foobar" /> * * Example: {img src='xhtml11.png' modname='core' set='powered'} * Output: <img src="themes/Theme/images/powered/xhtml11.png" alt="" width="88" height="31" /> * * Example: {img src='iconX.png' modname='ModName' modplugin='Plug1' set='icons'} * Output: <img src="modules/ModName/plugins/Plug1/images/icons/iconX.png" alt="" width="16" height="16" /> * * Example: {img src='iconY.png' sysplugin='Plug2' set='icons/small'} * Output: <img src="plugins/Plug2/images/icons/small/iconY.png" alt="" width="16" height="16" /> * * If the parameter assign is set, the results are assigned as an array. The components of * this array are the same as the attributes of the img tag; additionally an entry 'imgtag' is * set to the complete image tag. * * Example: * {img src="heading.png" assign="myvar"} * {$myvar.src} * {$myvar.width} * {$myvar.imgtag} * * Output: * modules/Example/images/en/heading.gif * 261 * <img src="modules/Example/images/en/heading.gif" alt="" width="261" height="69" /> * * @param array $params All attributes passed to this function from the template. * @param Zikula_View $view Reference to the Zikula_View object. * * @return string|void The img tag, null if $params['nostoponerror'] true and there is an error. */ function smarty_function_img($params, Zikula_View $view) { $nostoponerror = isset($params['nostoponerror']) && $params['nostoponerror'] ? true : false; if (!isset($params['src']) || !$params['src']) { if (!$nostoponerror) { $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('img', 'src'))); return; } else { return false; } } // process the image location $modname = isset($params['modname']) ? $params['modname'] : $view->toplevelmodule; $modplugin = isset($params['modplugin']) ? $params['modplugin'] : null; $sysplugin = isset($params['sysplugin']) ? $params['sysplugin'] : null; // process the image set $set = isset($params['set']) ? $params['set'] : null; $osset = DataUtil::formatForOS($set); // if the module name is 'core' if ($modname == 'core') { if (System::isLegacyMode() && (strpos($osset, 'icons/') !== false || strpos($osset, 'global/') !== false) && strpos($params['src'], '.gif')) { LogUtil::log(__f('Core image %s does not exist, please use the png format (called from %s).', array($params['src'], $view->getTemplatePath())), E_USER_DEPRECATED); $params['src'] = str_replace('.gif', '.png', $params['src']); } } // always provide an alt attribute. // if none is set, assign an empty one. $params['alt'] = isset($params['alt']) ? $params['alt'] : ''; // prevent overwriting surrounding titles (#477) if (isset($params['title']) && empty($params['title'])) { unset($params['title']); } // language $lang = ZLanguage::transformFS(ZLanguage::getLanguageCode()); if ($sysplugin) { $osplugdir = DataUtil::formatForOS($sysplugin); $pluglangpath = "plugins/{$osplugdir}/images/{$lang}"; $plugpath = "plugins/{$osplugdir}/images"; // form the array of paths $paths = array($pluglangpath, $plugpath); } else { // module directory if ($modname != 'core') { $modinfo = ModUtil::getInfoFromName($modname); $osmoddir = DataUtil::formatForOS($modinfo['directory']); $moduleDir = $modinfo['type'] == ModUtil::TYPE_SYSTEM ? 'system' : 'modules'; } if ($modplugin) { $osmodplugdir = DataUtil::formatForOS($modplugin); $modpluglangpath = "{$moduleDir}/{$osmoddir}/plugins/{$osmodplugdir}/Resources/public/images/{$lang}"; $modplugpath = "{$moduleDir}/{$osmoddir}/plugins/{$osmodplugdir}/Resources/public/images"; $modpluglangpathOld = "{$moduleDir}/{$osmoddir}/plugins/{$osmodplugdir}/images/{$lang}"; $modplugpathOld = "{$moduleDir}/{$osmoddir}/plugins/{$osmodplugdir}/images"; // form the array of paths $paths = array($modpluglangpath, $modplugpath, $modpluglangpathOld, $modplugpathOld); } else { // theme directory $ostheme = DataUtil::formatForOS(UserUtil::getTheme()); $theme = ThemeUtil::getTheme($ostheme); $themePath = null === $theme ? '' : $theme->getRelativePath() . '/Resources/public/images'; $themepath = $themePath; $corethemepath = "themes/{$ostheme}/images"; if ($modname == 'core') { $modpath = "images"; $paths = array($themepath, $corethemepath, $modpath); } else { $osmodname = DataUtil::formatForOS($modname); $themelangpath = "{$themePath}/{$lang}"; $themelangpathOld = "themes/{$ostheme}/templates/modules/{$osmodname}/images/{$lang}"; $themepathOld = "themes/{$ostheme}/templates/modules/{$osmodname}/images"; $module = ModUtil::getModule($modinfo['name']); $moduleBasePath = null === $module ? '' : $module->getRelativePath() . '/Resources/public/images'; $modlangpath = "{$moduleBasePath}/{$lang}"; $modpath = $moduleBasePath; $modlangpathOld = "{$moduleDir}/{$osmoddir}/images/{$lang}"; $modpathOld = "{$moduleDir}/{$osmoddir}/images"; $modlangpathOld2 = "{$moduleDir}/{$osmoddir}/pnimages/{$lang}"; $modpathOld2 = "{$moduleDir}/{$osmoddir}/pnimages"; // form the array of paths if (preg_match('/^admin.(png|gif|jpg)$/', $params['src'])) { // special processing for modules' admin icon $paths = array($modlangpath, $modpath, $modlangpathOld, $modpathOld, $modlangpathOld, $modpathOld, $modlangpathOld2, $modpathOld2); } else { $paths = array($themelangpath, $themepath, $themelangpathOld, $themepathOld, $corethemepath, $modlangpath, $modpath, $modlangpathOld, $modpathOld, $modlangpathOld2, $modpathOld2); } } } } $ossrc = DataUtil::formatForOS($params['src']); // search for the image $imgsrc = ''; foreach ($paths as $path) { $fullpath = $path . ($osset ? "/{$osset}/" : '/') . $ossrc; if (is_readable($fullpath)) { $imgsrc = $fullpath; break; } } if ($imgsrc == '' && isset($params['default'])) { $imgsrc = $params['default']; } // default for the optional flag $optional = isset($params['optional']) ? $params['optional'] : true; if ($imgsrc == '') { if ($optional) { if (!$nostoponerror) { $view->trigger_error(__f("%s: Image '%s' not found", array('img', DataUtil::formatForDisplay(($set ? "{$set}/" : '') . $params['src'])))); return; } else { return false; } } return; } // If neither width nor height is set, get these parameters. // If one of them is set, we do NOT obtain the real dimensions. // This way it is easy to scale the image to a certain dimension. if (!isset($params['width']) && !isset($params['height'])) { if (!($_image_data = @getimagesize($imgsrc))) { if (!$nostoponerror) { $view->trigger_error(__f("%s: Image '%s' is not a valid image file", array('img', DataUtil::formatForDisplay(($set ? "{$set}/" : '') . $params['src'])))); return; } else { return false; } } $params['width'] = $_image_data[0]; $params['height'] = $_image_data[1]; } $basepath = isset($params['fqurl']) && $params['fqurl'] ? System::getBaseUrl() : System::getBaseUri(); $params['src'] = $basepath . '/' . $imgsrc; $retval = isset($params['retval']) ? $params['retval'] : null; $assign = isset($params['assign']) ? $params['assign'] : null; unset($params['modname']); unset($params['retval']); unset($params['assign']); if (isset($params['altml'])) { // legacy unset($params['altml']); } if (isset($params['titleml'])) { // legacy unset($params['titleml']); } unset($params['optional']); unset($params['default']); unset($params['set']); unset($params['nostoponerror']); unset($params['fqurl']); $imgtag = '<img '; foreach ($params as $key => $value) { $imgtag .= $key . '="' . $value . '" '; } $imgtag .= '/>'; if (!empty($retval) && isset($params[$retval])) { return $params[$retval]; } elseif (!empty($assign)) { $params['imgtag'] = $imgtag; $view->assign($assign, $params); } else { return $imgtag; } }
/** * decode the custom url string * * @author Mark West * @return bool true if successful, false otherwise */ public function decodeurl($args) { // check we actually have some vars to work with if (!is_array($args) || !isset($args['vars']) || !is_array($args['vars']) || !count($args['vars'])) { throw new \InvalidArgumentException(__('Invalid arguments array received.')); } // define the available user functions $funcs = array('main', 'view', 'display', 'edit'); // return if function url scheme is not being customised $customFuncs = array('view', 'display'); // set the correct function name based on our input if (empty($args['vars'][2])) { // no func and no vars = main System::queryStringSetVar('func', 'main'); return true; } else { if (in_array($args['vars'][2], $funcs) && !in_array($args['vars'][2], $customFuncs)) { // normal url scheme, no need for special decoding return false; } } $func = $args['vars'][2]; // usually the language is in $args['vars'][0], except no mod name is in the url and we are set as start app $modInfo = ModUtil::getInfoFromName('Reviews'); $lang = strtolower($args['vars'][0]) == $modInfo['url'] ? $args['vars'][1] : $args['vars'][0]; // remove some unrequired parameters foreach ($_GET as $k => $v) { if (in_array($k, array('module', 'type', 'func', 'lang', 'ot', 'prop', 'cat')) === false) { unset($_GET[$k]); } } // process all args except language and module $urlVars = array_slice($args['vars'], 2); // all except [0] and [1] // get arguments as string $url = implode('/', $urlVars); // check if default view urls end with a trailing slash if ($func == 'view' && strpos($url, '.') === false && substr($url, -1) != '/') { // add missing trailing slash $url .= '/'; } $isDefaultModule = System::getVar('shorturlsdefaultmodule', '') == $modInfo['name']; if (!$isDefaultModule) { $url = $modInfo['url'] . '/' . $url; } // initialise url routing rules $routerFacade = new Reviews_RouterFacade(); // get router itself for convenience $router = $routerFacade->getRouter(); // read params out of url $parameters = $router->parse($url); //var_dump($parameters); if (!$parameters || !is_array($parameters)) { return false; } // post processing if (!isset($parameters['func'])) { $parameters['func'] = 'view'; } $func = $parameters['func']; // convert group folder to object type $parameters['ot'] = $routerFacade->getObjectTypeFromGroupingFolder($parameters['ot'], $func); // handle special templates $displayDefaultEnding = System::getVar('shorturlsext', ''); $endingPrefix = $func == 'view' ? '.' : ''; if (isset($parameters[$func . 'ending']) && !empty($parameters[$func . 'ending']) && $parameters[$func . 'ending'] != $endingPrefix . $displayDefaultEnding) { if ($func == 'view') { $parameters[$func . 'ending'] = str_replace($endingPrefix, '', $parameters[$func . 'ending']); } $parameters['use' . $parameters[$func . 'ending'] . 'ext'] = '1'; unset($parameters[$func . 'ending']); } // rename id to objid (primary key for display pages, optional filter id for view pages) /* may be obsolete now if (isset($parameters['id'])) { $parameters[strtolower($parameters['ot']) . 'id'] = $parameters['id']; unset($parameters['id']); }*/ // write vars to GET foreach ($parameters as $k => $v) { System::queryStringSetVar($k, $v); } return true; }
/** * Load a block. * * @param string $modname Module name. * @param string $block Name of the block. * * @throws LogicException Uf OO-Block is not a Zikula_Controller_AbstractBlock object. * @return bool True on successful load, false otherwise. */ public static function load($modname, $block) { $sm = ServiceUtil::getManager(); $modinfo = ModUtil::getInfoFromName($modname); $serviceId = strtolower('block.' . $modinfo['name'] . '_' . 'Block_' . $block); if ($sm->hasService($serviceId)) { return $sm->getService($serviceId); } if ($modinfo['type'] == ModUtil::TYPE_MODULE) { ZLanguage::bindModuleDomain($modinfo['name']); } $basedir = ($modinfo['type'] == ModUtil::TYPE_SYSTEM) ? 'system' : 'modules'; $moddir = DataUtil::formatForOS($modinfo['directory']); $blockdir = "$basedir/$moddir/lib/$moddir/Block"; $ooblock = "$blockdir/" . ucwords($block) . '.php'; ModUtil::load($modname); $isOO = ModUtil::isOO($modname); if (!$isOO) { $blockdirOld = $moddir . '/pnblocks'; $incfile = DataUtil::formatForOS($block . '.php'); if (file_exists("$basedir/$blockdirOld/$incfile")) { include_once "$basedir/$blockdirOld/$incfile"; } else { return false; } } // get the block info if ($isOO) { $className = ucwords($modinfo['name']) . '_' . 'Block_' . ucwords($block); $r = new ReflectionClass($className); $blockInstance = $r->newInstanceArgs(array($sm)); try { if (!$blockInstance instanceof Zikula_Controller_AbstractBlock) { throw new LogicException(sprintf('Block %s must inherit from Zikula_Controller_AbstractBlock', $className)); } } catch (LogicException $e) { if (System::isDevelopmentMode()) { throw $e; } else { LogUtil::registerError('A fatal error has occured which can be viewed only in development mode.', 500); return false; } } $sm->attachService($serviceId, $blockInstance); } $result = ($isOO ? $blockInstance : true); if ($isOO) { $blocks_modules[$block] = call_user_func(array($blockInstance, 'info')); } else { $infofunc = "{$modname}_{$block}block_info"; $blocks_modules[$block] = $infofunc(); } // set the module and keys for the new block $blocks_modules[$block]['bkey'] = $block; $blocks_modules[$block]['module'] = $modname; $blocks_modules[$block]['mid'] = ModUtil::getIdFromName($modname); // merge the blockinfo in the global list of blocks if (!isset($GLOBALS['blocks_modules'])) { $GLOBALS['blocks_modules'] = array(); } $GLOBALS['blocks_modules'][$blocks_modules[$block]['mid']][$block] = $blocks_modules[$block]; // Initialise block if required (new-style) if ($isOO) { call_user_func(array($blockInstance, 'init')); } else { $initfunc = "{$modname}_{$block}block_init"; $initfunc(); } // add stylesheet to the page vars, this makes manual loading obsolete PageUtil::addVar('stylesheet', ThemeUtil::getModuleStylesheet($modname)); return $result; }
/** * Add a plugins dir to _plugin_dir property array. * * @param string $module Module name. * @param string $plugin Plugin name. * * @return void */ private function _addPluginsDir($module, $plugin) { if (empty($module)) { return; } $modinfo = ModUtil::getInfoFromName($module); if (!$modinfo) { return; } switch ($modinfo['type']) { case ModUtil::TYPE_SYSTEM: $pluginsDir = "system/{$modinfo['directory']}/plugins/$plugin/templates/plugins"; break; case ModUtil::TYPE_MODULE: $pluginsDir = "modules/{$modinfo['directory']}/plugins/$plugin/templates/plugins"; break; case ModUtil::TYPE_CORE: $pluginsDir = "plugins/$plugin/templates/plugins"; break; } $this->addPluginDir($pluginsDir); }
/** * Perform the search. * * @param string $args['g'] query string to search * @param bool $args['firstPage'] is this first search attempt? is so - basic search is performed * @param string $args['searchtype'] (optional) search type (default='AND') * @param string $args['searchorder'] (optional) search order (default='newest') * @param int $args['numlimit'] (optional) number of items to return (default value based on Search settings, -1 for no limit) * @param int $args['page'] (optional) page number (default=1) * @param array $args['active'] (optional) array of search plugins to search (if empty all plugins are used) * @param array $args['modvar'] (optional) array with extrainfo for search plugins * * @return array array of items array and result count, or false on failure */ public function search($args) { // query string and firstPage params are required if (!isset($args['q']) || empty($args['q']) || !isset($args['firstPage'])) { return LogUtil::registerArgsError(); } $vars = array(); $vars['q'] = $args['q']; $vars['searchtype'] = isset($args['searchtype']) && !empty($args['searchtype']) ? $args['searchtype'] : 'AND'; $vars['searchorder'] = isset($args['searchorder']) && !empty($args['searchorder']) ? $args['searchorder'] : 'newest'; $vars['numlimit'] = isset($args['numlimit']) && !empty($args['numlimit']) ? $args['numlimit'] : $this->getVar('itemsperpage', 25); $vars['page'] = isset($args['page']) && !empty($args['page']) ? (int)$args['page'] : 1; $firstPage = isset($args['firstPage']) ? $args['firstPage'] : false; $active = isset($args['active']) && is_array($args['active']) && !empty($args['active']) ? $args['active'] : array(); $modvar = isset($args['modvar']) && is_array($args['modvar']) && !empty($args['modvar']) ? $args['modvar'] : array(); // work out row index from page number $vars['startnum'] = $vars['numlimit'] > 0 ? (($vars['page'] - 1) * $vars['numlimit']) + 1 : 1; // Load database stuff ModUtil::dbInfoLoad('Search'); $dbtable = DBUtil::getTables(); $userId = (int)UserUtil::getVar('uid'); $searchTable = $dbtable['search_result']; $searchColumn = $dbtable['search_result_column']; // Create restriction on result table (so user only sees own results) $userResultWhere = "$searchColumn[session] = '" . session_id() . "'"; // Do all the heavy database stuff on the first page only if ($firstPage) { // Clear current search result for current user - before showing the first page // Clear also older searches from other users. $dbDriverName = strtolower(Doctrine_Manager::getInstance()->getCurrentConnection()->getDriverName()); $where = $userResultWhere; if ($dbDriverName == 'pgsql') { $where .= " OR $searchColumn[found] + INTERVAL '8 HOUR' < NOW()"; } else { $where .= " OR DATE_ADD($searchColumn[found], INTERVAL 8 HOUR) < NOW()"; } DBUtil::deleteWhere('search_result', $where); // get all the search plugins $search_modules = ModUtil::apiFunc('Search', 'user', 'getallplugins'); // Ask active modules to find their items and put them into $searchTable for the current user // At the same time convert modules list from numeric index to modname index $searchModulesByName = array(); foreach ($search_modules as $mod) { // check we've a valid search plugin if (isset($mod['functions']) && (empty($active) || isset($active[$mod['title']]))) { foreach ($mod['functions'] as $contenttype => $function) { if (isset($modvar[$mod['title']])) { $param = array_merge($vars, $modvar[$mod['title']]); } else { $param = $vars; } $searchModulesByName[$mod['name']] = $mod; $ok = ModUtil::apiFunc($mod['title'], 'search', $function, $param); if (!$ok) { LogUtil::registerError($this->__f('Error! \'%1$s\' module returned false in search function \'%2$s\'.', array($mod['title'], $function))); return System::redirect(ModUtil::url('Search', 'user', 'main')); } } } } // Count number of found results $resultCount = DBUtil::selectObjectCount('search_result', $userResultWhere); SessionUtil::setVar('searchResultCount', $resultCount); SessionUtil::setVar('searchModulesByName', $searchModulesByName); } else { $resultCount = SessionUtil::getVar('searchResultCount'); $searchModulesByName = SessionUtil::getVar('searchModulesByName'); } // Fetch search result - do sorting and paging in database // Figure out what to sort by switch ($args['searchorder']) { case 'alphabetical': $sort = 'title'; break; case 'oldest': $sort = 'created'; break; case 'newest': $sort = 'created DESC'; break; default: $sort = 'title'; break; } // Get next N results from the current user's result set // The "checker" object is used to: // 1) do secondary access control (deprecated more or less) // 2) let the modules add "url" to the found (and viewed) items $checker = new search_result_checker($searchModulesByName); $sqlResult = DBUtil::selectObjectArrayFilter('search_result', $userResultWhere, $sort, $vars['startnum'] - 1, $vars['numlimit'], '', $checker, null); // add displayname of modules found $cnt = count($sqlResult); for ($i = 0; $i < $cnt; $i++) { $modinfo = ModUtil::getInfoFromName($sqlResult[$i]['module']); $sqlResult[$i]['displayname'] = $modinfo['displayname']; } $result = array( 'resultCount' => $resultCount, 'sqlResult' => $sqlResult ); return $result; }
/** * 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])); } } } } } }
/** * GetVar. * * Returns the value(s) of a page variable. In the case of * a mulit valued variable, this is an array containing all assigned * values. * * @param string $varname The name of the page variable. * @param mixed $default Default return value. * * @return mixed Contents of the variable */ public static function getVar($varname, $default = null) { global $_pageVars; if (System::isLegacyMode()) { $sm = ServiceUtil::getManager(); $metaTags = $sm->getParameter('zikula_view.metatags'); switch ($varname) { case 'description': return $metaTags['description']; break; case 'keywords': return $metaTags['keywords']; break; case 'rawtext': LogUtil::log(__f('Warning! The page variable %1$s is deprecated. Please use %2$s instead.', array('rawtext', 'header')), E_USER_DEPRECATED); $varname = 'header'; break; } } // check for $_pageVars sanity if (!isset($_pageVars)) { $_pageVars = array(); } elseif (!is_array($_pageVars)) { return false; } if (isset($_pageVars[$varname]) && isset($_pageVars[$varname]['contents'])) { if ($varname == 'title') { $title = System::getVar('pagetitle', ''); if (!empty($title) && $title != '%pagetitle%') { $title = str_replace('%pagetitle%', $_pageVars[$varname]['contents'], $title); $title = str_replace('%sitename%', System::getVar('sitename', ''), $title); $moduleInfo = ModUtil::getInfoFromName(ModUtil::getName()); $moduleDisplayName = $moduleInfo['displayname']; $title = str_replace('%modulename%', $moduleDisplayName, $title); return $title; } } return $_pageVars[$varname]['contents']; } elseif (isset($_pageVars[$varname]['default'])) { return $_pageVars[$varname]['default']; } return $default; }
/** * Zikula_View function to include module specific javascripts * * Available parameters: * - modname module name (if not set, the current module is assumed) * if modname="" than we will look into the main javascript folder * - script name of the external javascript file (mandatory) * - modonly javascript will only be included when the the current module is $modname * - onload function to be called with onLoad handler in body tag, makes sense with assign set only, see example #2 * - assign if set, the tag and the script filename are returned * * Example: {modulejavascript modname=foobar script=module_admin_config.js modonly=1 } * Output: <script type="text/javascript" src="modules/foobar/javascript/module_admin_config.js"> * * Example: {modulejavascript modname=foobar script=module_admin_config.js modonly=1 onload="dosomething()" assign=myjs } * Output: nothing, but assigns a variable containing several values: * $myjs.scriptfile = "modules/foobar/javascript/module_admin_config.js" * $myjs.tag = "<script type=\"text/javascript\" src=\"modules/foobar/javascript/module_admin_config.js\"></script>" * $myjs.onload = "onLoad=\"dosomething()\""; * Possible code in master.tpl would be: * * ... * { $myjs.tag } * </head> * <body { $myjs.onload } > * ... * * which results in * * ... * <script type="text/javascript" src="modules/foobar/javascript/module_admin_config.js"></script> * </head> * <body onLoad="dosomething()" > * ... * * if foobar is the current module. * * @param array $params All attributes passed to this function from the template. * @param Zikula_View $view Reference to the Zikula_View object. * * @return string The tag. */ function smarty_function_modulejavascript($params, Zikula_View $view) { // check if script is set (mandatory) if (!isset($params['script'])) { $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('modulejavascript', 'script'))); return false; } // check if modname is set and if not, if $modonly is set if (!isset($params['modname'])) { if (isset($params['modonly'])) { // error - we want $modonly only with $modname $view->trigger_error(__f('Error! in %1$s: parameter \'%2$s\' only supported together with \'%3$s\' set.', array('modulejavascript', 'modonly', 'modname'))); return; } // we use the current module name $params['modname'] = ModUtil::getName(); } if (isset($params['modonly']) && $params['modname'] != ModUtil::getName()) { // current module is not $modname - do nothing and return silently return; } // if modname is empty, we will search the main javascript folder if ($params['modname'] == '') { $searchpaths = array('javascript', 'javascript/ajax'); } else { // theme directory $theme = DataUtil::formatForOS(UserUtil::getTheme()); $osmodname = DataUtil::formatForOS($params['modname']); $themepath = "themes/{$theme}/javascript/{$osmodname}"; // module directory $modinfo = ModUtil::getInfoFromName($params['modname']); $osmoddir = DataUtil::formatForOS($modinfo['directory']); $modpath = "modules/{$osmoddir}/javascript"; $syspath = "system/{$osmoddir}/javascript"; $modpathOld = "modules/{$osmoddir}/pnjavascript"; $syspathOld = "system/{$osmoddir}/pnjavascript"; $searchpaths = array($themepath, $modpath, $syspath, $modpathOld, $syspathOld); } $osscript = DataUtil::formatForOS($params['script']); // search for the javascript $scriptsrc = ''; foreach ($searchpaths as $path) { if (is_readable("{$path}/{$osscript}")) { $scriptsrc = "{$path}/{$osscript}"; break; } } // if no module javascript has been found then return no content $tag = empty($scriptsrc) ? '' : '<script type="text/javascript" src="' . $scriptsrc . '"></script>'; // onLoad event handler used? $onload = isset($params['onload']) ? 'onLoad="' . $params['onload'] . '"' : ''; if (isset($params['assign'])) { $return = array(); $return['scriptfile'] = $scriptsrc; $return['tag'] = $tag; $return['onload'] = $onload; $view->assign($params['assign'], $return); } else { return $tag; } }
/** * Bind module plugin domain. * * @param string $moduleName Module name. * @param string $pluginName Plugin name. * * @return boolean */ public static function bindModulePluginDomain($moduleName, $pluginName) { // system modules are in the zikula domain $module = ModUtil::getInfoFromName($moduleName); if ($module['type'] == ModUtil::TYPE_SYSTEM) { return 'zikula'; } $_this = self::getInstance(); $domain = self::getModulePluginDomain($moduleName, $pluginName); $dir = is_dir("modules/{$moduleName}/plugins/{$pluginName}/Resources/locale") ? "modules/{$moduleName}/plugins/{$pluginName}/Resources/locale" : "modules/{$moduleName}/plugins/{$pluginName}/locale"; $path = $_this->searchOverrides($domain, $dir); return self::bindDomain($domain, $path); }