예제 #1
0
 /**
  * Handle page load event KernelEvents::REQUEST.
  *
  * @param GetResponseEvent $event
  *
  * @return void
  */
 public function pageload(GetResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     if (\System::isInstalling() || \System::isUpgrading()) {
         return;
     }
     $openSearchEnabled = ModUtil::getVar('ZikulaSearchModule', 'opensearch_enabled');
     if ($openSearchEnabled && SecurityUtil::checkPermission('ZikulaSearchModule::', '::', ACCESS_READ)) {
         // The current user has the rights to search the page.
         PageUtil::addVar('header', '<link rel="search" type="application/opensearchdescription+xml" title="' . DataUtil::formatForDisplay(System::getVar('sitename')) . '" href="' . DataUtil::formatForDisplay($this->router->generate('zikulasearchmodule_user_opensearch')) . '" />');
     }
 }
예제 #2
0
 /**
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $em = ServiceUtil::get('doctrine.entitymanager');
     try {
         if (\System::isInstalling()) {
             $uid = 2;
         } else {
             $uid = UserUtil::getVar('uid');
         }
         $user = $em->getReference('ZikulaUsersModule:UserEntity', $uid);
         $this->blameableListener->setUserValue($user);
     } catch (\Exception $e) {
         // silently fail - likely installing and tables not available
     }
 }
예제 #3
0
 /**
  * Handle module install event.
  *
  * @param ModuleStateEvent $event
  *
  * @return void
  */
 public function moduleInstall(ModuleStateEvent $event)
 {
     $module = $event->getModule();
     if ($module) {
         $modName = $module->getName();
     } else {
         // Legacy for non Symfony-styled modules.
         $modInfo = $event->modinfo;
         $modName = $modInfo['name'];
     }
     if (!\System::isInstalling()) {
         $category = ModUtil::getVar('ZikulaAdminModule', 'defaultcategory');
         ModUtil::apiFunc('ZikulaAdminModule', 'admin', 'addmodtocategory', array('module' => $modName, 'category' => $category));
     }
 }
예제 #4
0
 public function onKernelResponse(FilterResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     if (\System::isInstalling()) {
         return;
     }
     $response = $event->getResponse();
     $request = $event->getRequest();
     if ($response instanceof PlainResponse || $response instanceof JsonResponse || $request->isXmlHttpRequest() || $response instanceof RedirectResponse) {
         return;
     }
     // if theme has already been processed the new way, stop here
     if (!isset($response->legacy) && !$request->attributes->get('_legacy', false)) {
         return;
     }
     Zikula_View_Theme::getInstance()->themefooter($response);
 }
 /**
  * Strip the Front Controller (index.php) from the URI
  *
  * @param GetResponseEvent $event An GetResponseEvent instance
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     if (\System::isInstalling()) {
         return;
     }
     $requestUri = $event->getRequest()->getRequestUri();
     $frontController = \System::getVar('entrypoint', 'index.php');
     $stripEntryPoint = (bool) \System::getVar('shorturlsstripentrypoint', false);
     $containsFrontController = strpos($requestUri, "{$frontController}/") !== false;
     if ($containsFrontController && $stripEntryPoint) {
         $url = str_ireplace("{$frontController}/", "", $requestUri);
         $response = new RedirectResponse($url, 301);
         $event->setResponse($response);
         $event->stopPropagation();
     }
 }
예제 #6
0
 public function onKernelRequestSiteOff(GetResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     $response = $event->getResponse();
     $request = $event->getRequest();
     if ($response instanceof PlainResponse || $response instanceof JsonResponse || $request->isXmlHttpRequest()) {
         return;
     }
     if (\System::isInstalling()) {
         return;
     }
     // Get variables
     $module = strtolower($request->query->get('module'));
     $type = strtolower($request->query->get('type'));
     $func = strtolower($request->query->get('func'));
     $siteOff = (bool) \System::getVar('siteoff');
     $hasAdminPerms = \SecurityUtil::checkPermission('ZikulaSettingsModule::', 'SiteOff::', ACCESS_ADMIN);
     $urlParams = $module == 'users' && $type == 'user' && $func == 'siteofflogin';
     // params are lowercase
     $versionCheck = \Zikula_Core::VERSION_NUM != \System::getVar('Version_Num');
     // Check for site closed
     if ($siteOff && !$hasAdminPerms && !$urlParams || $versionCheck) {
         $hasOnlyOverviewAccess = \SecurityUtil::checkPermission('ZikulaUsersModule::', '::', ACCESS_OVERVIEW);
         if ($hasOnlyOverviewAccess && \UserUtil::isLoggedIn()) {
             \UserUtil::logout();
         }
         // initialise the language system to enable translations (#1764)
         $lang = \ZLanguage::getInstance();
         $lang->setup($request);
         $response = new Response();
         $response->headers->add(array('HTTP/1.1 503 Service Unavailable'));
         $response->setStatusCode(503);
         $content = (require_once \System::getSystemErrorTemplate('siteoff.tpl'));
         // move to CoreBundle and use Twig
         $response->setContent($content);
         $event->setResponse($response);
         $event->stopPropagation();
     }
 }
예제 #7
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     if (\System::isInstalling()) {
         return;
     }
     // Check if compression is desired
     if (\System::getVar('UseCompression') != 1) {
         return;
     }
     // Check if zlib extension is available
     if (!extension_loaded('zlib')) {
         return;
     }
     // Set compression on
     ini_set('zlib.output_handler', '');
     ini_set('zlib.output_compression', 'On');
     ini_set('zlib.output_compression_level', 6);
 }
예제 #8
0
파일: tables.php 프로젝트: rmaiwald/core
/**
 * 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();
    }
}
/**
 * Zikula_View function to display a list box with a list of active modules.
 *
 * Either user or admin capable or all modules.
 *
 * Available parameters:
 *   - name:       Name for the control (optional) if not present then only the option tags are output
 *   - id:         ID for the control
 *   - selected:   Selected value
 *   - capability: Show modules with this capability, all or $capability.
 *   - assign:     If set, the results are assigned to the corresponding variable instead of printed out
 *
 * Example
 *
 *     {html_select_modules name=mod selected=$mymod}
 *
 *     <select name="mod">
 *         <option value="">&bsp;</option>
 *         {html_select_modules selected=$mythemechoice}
 *     </select>
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @see    function.html_select_modules.php::smarty_function_html_select_modules()
 * @return string A drop down containing a list of modules.
 */
function smarty_function_html_select_modules($params, Zikula_View $view)
{
    // we'll make use of the html_options plugin to simplfiy this plugin
    require_once $view->_get_plugin_filepath('function', 'html_options');
    // set some defaults
    if (isset($params['type'])) {
        // bc
        $params['capability'] = $params['type'];
    }
    if (!isset($params['capability'])) {
        $params['capability'] = 'all';
    }
    // get the modules
    switch ($params['capability']) {
        case 'all':
            $modules = ModUtil::getAllMods();
            break;
        default:
            $modules = ModUtil::getModulesCapableOf($params['capability']);
            break;
    }
    // process our list of modules for input to the html_options plugin
    $moduleslist = array();
    $installerArray = array('ZikulaBlocksModule', 'ZikulaErrorsModule', 'ZikulaPermissionsModule', 'ZikulaCategoriesModule', 'ZikulaGroupsModule', 'ZikulaThemeModule', 'ZikulaUsersModule', 'ZikulaSearchModule');
    if (!empty($modules)) {
        foreach ($modules as $module) {
            if (!(System::isInstalling() && in_array($module['name'], $installerArray))) {
                $moduleslist[$module['name']] = $module['displayname'];
            }
        }
    }
    natcasesort($moduleslist);
    // get the formatted list
    $output = smarty_function_html_options(array('options' => $moduleslist, 'selected' => isset($params['selected']) ? $params['selected'] : null, 'name' => isset($params['name']) ? $params['name'] : null, 'id' => isset($params['id']) ? $params['id'] : null), $view);
    if (isset($params['assign']) && !empty($params['assign'])) {
        $view->assign($params['assign'], $output);
    } else {
        return $output;
    }
}
예제 #10
0
파일: Route.php 프로젝트: rmaiwald/core
 public function reloadAllRoutes(ContainerInterface $sm = null)
 {
     if (!isset($sm)) {
         $sm = \ServiceUtil::getManager();
     }
     set_time_limit(300);
     $bundles = $sm->get('kernel')->getModules();
     $request = $sm->get('request');
     $dom = \ZLanguage::getModuleDomain('ZikulaRoutesModule');
     // See http://doctrine-orm.readthedocs.org/en/latest/reference/transactions-and-concurrency.html#approach-2-explicitly
     $this->getEntityManager()->beginTransaction();
     // suspend auto-commit
     $this->removeAll(false);
     try {
         foreach ($bundles as $bundle) {
             //$this->entityManager->getRepository('ZikulaRoutesModule:RouteEntity')->removeAllOfModule($bundle, false);
             try {
                 $routeCollection = $sm->get('zikularoutesmodule.routing_finder')->find($bundle);
             } catch (\Exception $e) {
                 $message = __f('Error! Routes for %s bundle could not be loaded: %s', array($bundle->getName(), $e->getMessage()), $dom);
                 if (\System::isInstalling()) {
                     \LogUtil::registerError($message);
                 } else {
                     $request->getSession()->getFlashBag()->add('error', $message);
                 }
                 continue;
             }
             $this->addRouteCollection($bundle, $routeCollection);
         }
         $this->getEntityManager()->getConnection()->commit();
     } catch (\Exception $e) {
         $this->getEntityManager()->getConnection()->rollback();
         $this->getEntityManager()->close();
         throw $e;
     }
     if (!\System::isInstalling()) {
         $request->getSession()->getFlashBag()->add('status', __('Done! Routes reloaded.', $dom));
     }
 }
/**
 * Permission check for workflow schema 'none'.
 * This function allows to calculate complex permission checks.
 * It receives the object the workflow engine is being asked to process and the permission level the action requires.
 *
 * @param array  $obj         The currently treated object.
 * @param int    $permLevel   The required workflow permission level.
 * @param int    $currentUser Id of current user.
 * @param string $actionId    Id of the workflow action to be executed.
 *
 * @return bool Whether the current user is allowed to execute the action or not.
 */
function ZikulaRoutesModule_workflow_none_permissioncheck($obj, $permLevel, $currentUser, $actionId)
{
    // Make sure not to check permission on installation.
    if (\System::isInstalling()) {
        return true;
    }
    // calculate the permission component
    $objectType = $obj['_objectType'];
    $component = 'ZikulaRoutesModule:' . ucfirst($objectType) . ':';
    // calculate the permission instance
    $idFields = ModUtil::apiFunc('ZikulaRoutesModule', 'selection', 'getIdFields', array('ot' => $objectType));
    $instanceId = '';
    foreach ($idFields as $idField) {
        if (!empty($instanceId)) {
            $instanceId .= '_';
        }
        $instanceId .= $obj[$idField];
    }
    $instance = $instanceId . '::';
    // now perform the permission check
    $result = SecurityUtil::checkPermission($component, $instance, $permLevel, $currentUser);
    return $result;
}
 public function createThemedResponse(FilterResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     if (\System::isInstalling()) {
         return;
     }
     $response = $event->getResponse();
     $route = $event->getRequest()->attributes->has('_route') ? $event->getRequest()->attributes->get('_route') : '0';
     // default must not be '_'
     if (!$response instanceof Response || is_subclass_of($response, '\\Symfony\\Component\\HttpFoundation\\Response') || $event->getRequest()->isXmlHttpRequest() || false === strpos($response->headers->get('Content-Type'), 'text/html') || $route[0] === '_') {
         return;
     }
     // all responses are assumed to be themed. PlainResponse will have already returned.
     $twigThemedResponse = $this->themeEngine->wrapResponseInTheme($response);
     if ($twigThemedResponse) {
         $event->setResponse($twigThemedResponse);
     } else {
         // theme is not a twig based theme, revert to smarty
         $smartyThemedResponse = Zikula_View_Theme::getInstance()->themefooter($response);
         $event->setResponse($smartyThemedResponse);
     }
 }
예제 #13
0
 /**
  * {@inheritdoc}
  */
 public function write($sessionId, $vars)
 {
     if (System::isInstalling()) {
         return true;
     }
     // http host is not given for CLI requests for example
     $ipDefault = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
     $obj = $this->storage->getBag('attributes')->get('obj');
     $obj['sessid'] = $sessionId;
     $obj['vars'] = $vars;
     $obj['remember'] = $this->storage->getBag('attributes')->get('rememberme', 0);
     $obj['uid'] = $this->storage->getBag('attributes')->get('uid', 0);
     $obj['ipaddr'] = $this->storage->getBag('attributes')->get('obj/ipaddr', $ipDefault);
     $obj['lastused'] = date('Y-m-d H:i:s', $this->storage->getMetadataBag()->getLastUsed());
     $query = $this->conn->executeQuery('SELECT * FROM session_info WHERE sessid=:id', array('id' => $sessionId));
     if (!($res = $query->fetch(\PDO::FETCH_ASSOC))) {
         $res = $this->conn->executeUpdate('INSERT INTO session_info (sessid, ipaddr, lastused, uid, remember, vars)
         VALUES (:sessid, :ipaddr, :lastused, :uid, :remember, :vars)', array('sessid' => $obj['sessid'], 'ipaddr' => $obj['ipaddr'], 'lastused' => $obj['lastused'], 'uid' => $obj['uid'], 'remember' => $obj['remember'], 'uid' => $obj['uid'], 'vars' => $obj['vars']));
     } else {
         // check for regenerated session and update ID in database
         $res = $this->conn->executeUpdate('UPDATE session_info SET ipaddr = :ipaddr, lastused = :lastused, uid = :uid, remember = :remember, vars = :vars WHERE sessid = :sessid', array('sessid' => $obj['sessid'], 'ipaddr' => $obj['ipaddr'], 'lastused' => $obj['lastused'], 'uid' => $obj['uid'], 'remember' => $obj['remember'], 'uid' => $obj['uid'], 'vars' => $obj['vars']));
     }
     return (bool) $res;
 }
예제 #14
0
파일: Core.php 프로젝트: projectesIF/Sirius
 /**
  * Initialise Zikula.
  *
  * Carries out a number of initialisation tasks to get Zikula up and
  * running.
  *
  * @param integer $stage Stage to load.
  *
  * @return boolean True initialisation successful false otherwise.
  */
 public function init($stage = self::STAGE_ALL)
 {
     $coreInitEvent = new Zikula_Event('core.init', $this);
     // store the load stages in a global so other API's can check whats loaded
     $this->stage = $this->stage | $stage;
     if ($stage & self::STAGE_PRE && $this->stage & ~self::STAGE_PRE) {
         ModUtil::flushCache();
         System::flushCache();
         $this->eventManager->notify(new Zikula_Event('core.preinit', $this));
     }
     // Initialise and load configuration
     if ($stage & self::STAGE_CONFIG) {
         if (System::isLegacyMode()) {
             require_once 'lib/legacy/Compat.php';
         }
         // error reporting
         if (!System::isInstalling()) {
             // this is here because it depends on the config.php loading.
             $event = new Zikula_Event('setup.errorreporting', null, array('stage' => $stage));
             $this->eventManager->notify($event);
         }
         // initialise custom event listeners from config.php settings
         $coreInitEvent->setArg('stage', self::STAGE_CONFIG);
         $this->eventManager->notify($coreInitEvent);
     }
     // Check that Zikula is installed before continuing
     if (System::getVar('installed') == 0 && !System::isInstalling()) {
         System::redirect(System::getBaseUrl() . 'install.php?notinstalled');
         System::shutDown();
     }
     if ($stage & self::STAGE_DB) {
         try {
             $dbEvent = new Zikula_Event('core.init', $this, array('stage' => self::STAGE_DB));
             $this->eventManager->notify($dbEvent);
         } catch (PDOException $e) {
             if (!System::isInstalling()) {
                 header('HTTP/1.1 503 Service Unavailable');
                 require_once System::getSystemErrorTemplate('dbconnectionerror.tpl');
                 System::shutDown();
             } else {
                 return false;
             }
         }
     }
     if ($stage & self::STAGE_TABLES) {
         // Initialise dbtables
         ModUtil::dbInfoLoad('Extensions', 'Extensions');
         ModUtil::initCoreVars();
         ModUtil::dbInfoLoad('Settings', 'Settings');
         ModUtil::dbInfoLoad('Theme', 'Theme');
         ModUtil::dbInfoLoad('Users', 'Users');
         ModUtil::dbInfoLoad('Groups', 'Groups');
         ModUtil::dbInfoLoad('Permissions', 'Permissions');
         ModUtil::dbInfoLoad('Categories', 'Categories');
         if (!System::isInstalling()) {
             ModUtil::registerAutoloaders();
         }
         $coreInitEvent->setArg('stage', self::STAGE_TABLES);
         $this->eventManager->notify($coreInitEvent);
     }
     if ($stage & self::STAGE_SESSIONS) {
         SessionUtil::requireSession();
         $coreInitEvent->setArg('stage', self::STAGE_SESSIONS);
         $this->eventManager->notify($coreInitEvent);
     }
     // Have to load in this order specifically since we cant setup the languages until we've decoded the URL if required (drak)
     // start block
     if ($stage & self::STAGE_LANGS) {
         $lang = ZLanguage::getInstance();
     }
     if ($stage & self::STAGE_DECODEURLS) {
         System::queryStringDecode();
         $coreInitEvent->setArg('stage', self::STAGE_DECODEURLS);
         $this->eventManager->notify($coreInitEvent);
     }
     if ($stage & self::STAGE_LANGS) {
         $lang->setup();
         $coreInitEvent->setArg('stage', self::STAGE_LANGS);
         $this->eventManager->notify($coreInitEvent);
     }
     // end block
     if ($stage & self::STAGE_MODS) {
         // Set compression on if desired
         if (System::getVar('UseCompression') == 1) {
             //ob_start("ob_gzhandler");
         }
         ModUtil::load('SecurityCenter');
         $coreInitEvent->setArg('stage', self::STAGE_MODS);
         $this->eventManager->notify($coreInitEvent);
     }
     if ($stage & self::STAGE_THEME) {
         // register default page vars
         PageUtil::registerVar('title');
         PageUtil::setVar('title', System::getVar('defaultpagetitle'));
         PageUtil::registerVar('keywords', true);
         PageUtil::registerVar('stylesheet', true);
         PageUtil::registerVar('javascript', true);
         PageUtil::registerVar('jsgettext', true);
         PageUtil::registerVar('body', true);
         PageUtil::registerVar('header', true);
         PageUtil::registerVar('footer', true);
         $theme = Zikula_View_Theme::getInstance();
         // set some defaults
         // Metadata for SEO
         $this->serviceManager['zikula_view.metatags']['description'] = System::getVar('defaultmetadescription');
         $this->serviceManager['zikula_view.metatags']['keywords'] = System::getVar('metakeywords');
         $coreInitEvent->setArg('stage', self::STAGE_THEME);
         $this->eventManager->notify($coreInitEvent);
     }
     // check the users status, if not 1 then log him out
     if (UserUtil::isLoggedIn()) {
         $userstatus = UserUtil::getVar('activated');
         if ($userstatus != Users_Constant::ACTIVATED_ACTIVE) {
             UserUtil::logout();
             // TODO - When getting logged out this way, the existing session is destroyed and
             //        then a new one is created on the reentry into index.php. The message
             //        set by the registerStatus call below gets lost.
             LogUtil::registerStatus(__('You have been logged out.'));
             System::redirect(ModUtil::url('Users', 'user', 'login'));
         }
     }
     if ($stage & self::STAGE_POST && $this->stage & ~self::STAGE_POST) {
         $this->eventManager->notify(new Zikula_Event('core.postinit', $this, array('stages' => $stage)));
     }
 }
예제 #15
0
파일: DBUtil.php 프로젝트: rmaiwald/core
 /**
  * Execute SQL, check for errors and return result. Uses Doctrine's DBAL to generate DB-portable paging code.
  *
  * @param string  $sql          The SQL statement to execute.
  * @param integer $limitOffset  The lower limit bound (optional) (default=-1).
  * @param integer $limitNumRows The upper limit bound (optional) (default=-1).
  * @param boolean $exitOnError  Whether to exit on error (default=true) (optional).
  * @param boolean $verbose      Whether to be verbose (default=true) (optional).
  *
  * @return mixed     The result set of the successfully executed query or false on error.
  * @throws Exception No SQL statment.
  */
 public static function executeSQL($sql, $limitOffset = -1, $limitNumRows = -1, $exitOnError = true, $verbose = true)
 {
     if (!$sql) {
         throw new Exception(__('No SQL statement to execute'));
     }
     $connection = Doctrine_Manager::getInstance()->getCurrentConnection();
     if (!$connection && System::isInstalling()) {
         return false;
     }
     try {
         if ($limitNumRows > 0) {
             $tStr = strtoupper(substr(trim($sql), 0, 7));
             // Grab first 7 chars to allow syntax like "(SELECT" which may happen with UNION statements
             if (strpos($tStr, 'SELECT') === false) {
                 // TODO D [use normal Select instead of showing an error message if paging is desired for something different than SELECTs] (Guite)
                 throw new Exception(__('Paging parameters can only be used for SELECT statements'));
             }
             if ($limitOffset > 0) {
                 $sql = $connection->modifyLimitQuery($sql, $limitNumRows, $limitOffset);
             } else {
                 $sql = $connection->modifyLimitQuery($sql, $limitNumRows);
             }
         }
         $stmt = $connection->prepare($sql);
         //$stmt->setHydrationMode(Doctrine_Core::HYDRATE_RECORD);
         if ($stmt->execute()) {
             $result = $stmt;
         }
         if ($result) {
             // catch manual SQL which requires cache flushes
             $tab = null;
             $sql = strtolower(trim(preg_replace("/\\s+/", " ", $sql)));
             if (strpos($sql, 'update') === 0) {
                 list(, $tab, ) = explode(' ', $sql);
             }
             if (strpos($sql, 'delete') === 0) {
                 list(, , $tab, ) = explode(' ', $sql);
             }
             if ($tab && strpos($tab, 'session_info') === false) {
                 self::flushCache($tab);
             }
             return $result;
         }
     } catch (Exception $e) {
         echo 'Error in DBUtil::executeSQL: ' . $sql . '<br />' . $e->getMessage() . '<br />';
         if (System::isDevelopmentMode() && SecurityUtil::checkPermission('.*', '.*', ACCESS_ADMIN)) {
             echo nl2br($e->getTraceAsString());
         }
         if ($exitOnError) {
             System::shutDown();
         }
     }
     return false;
 }
예제 #16
0
 /**
  * Gets the modules table.
  *
  * Small wrapper function to avoid duplicate sql.
  *
  * @return array An array modules table.
  */
 public static function getModsTable()
 {
     if (!isset(self::$cache['modstable'])) {
         self::$cache['modstable'] = array();
     }
     if (!self::$cache['modstable'] || System::isInstalling()) {
         self::$cache['modstable'] = DBUtil::selectObjectArray('modules', '', '', -1, -1, 'id');
         foreach (self::$cache['modstable'] as $mid => $module) {
             if (!isset($module['url']) || empty($module['url'])) {
                 self::$cache['modstable'][$mid]['url'] = $module['displayname'];
             }
             self::$cache['modstable'][$mid]['capabilities'] = unserialize($module['capabilities']);
             self::$cache['modstable'][$mid]['securityschema'] = unserialize($module['securityschema']);
         }
     }
     // add Core module (hack).
     self::$cache['modstable'][0] = array('id' => '0', 'name' => 'zikula', 'type' => self::TYPE_CORE, 'directory' => '', 'displayname' => 'Zikula Core v' . Zikula_Core::VERSION_NUM, 'version' => Zikula_Core::VERSION_NUM, 'state' => self::STATE_ACTIVE);
     return self::$cache['modstable'];
 }
예제 #17
0
 /**
  * Set encoding.
  *
  * @return void
  */
 private function setEncoding()
 {
     if (preg_match('#utf([-]{0,1})8#', $this->dbCharset)) {
         $this->encoding = 'utf-8';
         return;
     } elseif (preg_match('#^latin([0-9]{1,2})#', $this->dbCharset)) {
         $this->encoding = preg_replace('#latin([0-9]{1,2})#', 'iso-8859-$1', $this->dbCharset);
         return;
     } elseif (System::isInstalling()) {
         $this->encoding = 'utf-8';
     } else {
         $this->registerError(__f("Error! Could not set encoding based on database character set '%s'.", $this->dbCharset));
     }
 }
예제 #18
0
 /**
  * Gets the modules table.
  *
  * Small wrapper function to avoid duplicate sql.
  *
  * @return array An array modules table.
  */
 public static function getModsTable()
 {
     if (!isset(self::$cache['modstable'])) {
         self::$cache['modstable'] = array();
     }
     if (!self::$cache['modstable'] || System::isInstalling()) {
         // get entityManager
         $sm = ServiceUtil::getManager();
         $entityManager = $sm->get('doctrine')->getEntityManager();
         // get all modules
         $modules = $entityManager->getRepository('Zikula\\Core\\Doctrine\\Entity\\Extension')->findAll();
         foreach ($modules as $module) {
             $module = $module->toArray();
             if (!isset($module['url']) || empty($module['url'])) {
                 $module['url'] = strtolower($module['displayname']);
             }
             self::$cache['modstable'][$module['id']] = $module;
         }
         // add Core module (hack).
         self::$cache['modstable'][0] = array('id' => 0, 'name' => 'zikula', 'type' => self::TYPE_CORE, 'directory' => '', 'displayname' => 'Zikula Core v' . \Zikula\Core\Core::VERSION_NUM, 'version' => \Zikula\Core\Core::VERSION_NUM, 'state' => self::STATE_ACTIVE);
     }
     return self::$cache['modstable'];
 }
예제 #19
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.'));
     }
 }
예제 #20
0
 /**
  * Set database charset.
  *
  * @return void
  */
 private function setDBCharset()
 {
     $this->dbCharset = System::isInstalling() ? 'utf8' : strtolower(Doctrine_Manager::getInstance()->getCurrentConnection()->getCharset());
 }
예제 #21
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.'));
     }
 }
 private function addBootstrapCss($basePath)
 {
     $overrideBootstrapPath = '';
     if (!\System::isInstalling()) {
         $overrideBootstrapPath = \ThemeUtil::getVar('bootstrapPath', '');
         // allows for theme override of bootstrap css path
     }
     if (empty($overrideBootstrapPath)) {
         $bootstrapFontAwesomePath = $this->params['zikula.stylesheet.bootstrap-font-awesome.path'];
         $this->cssAssetBag->add(["{$basePath}/{$bootstrapFontAwesomePath}" => 0]);
     }
     if (!empty($overrideBootstrapPath)) {
         $fontAwesomePath = $this->params['zikula.stylesheet.fontawesome.min.path'];
         $this->cssAssetBag->add(["{$basePath}/{$overrideBootstrapPath}" => 0, "{$basePath}/{$fontAwesomePath}" => 1]);
     }
 }
예제 #23
0
 /**
  * Format a variable for HTML display. This method is recursive array safe.
  *
  * @param string $var The variable to format.
  *
  * @return string The formatted variable.
  */
 public static function formatForDisplayHTML($var)
 {
     // This search and replace finds the text 'x@y' and replaces
     // it with HTML entities, this provides protection against
     // email harvesters
     //
     // Note that the use of \024 and \022 are needed to ensure that
     // this does not break HTML tags that might be around either
     // the username or the domain name
     static $search = array('/([^\\024])@([^\\022])/se');
     static $replace = array('"&#" .
                             sprintf("%03d", ord("\\1")) .
                             ";&#064;&#" .
                             sprintf("%03d", ord("\\2")) . ";";');
     static $allowedtags = null;
     static $outputfilter;
     static $event;
     if (!$event) {
         $event = new GenericEvent();
     }
     if (!isset($allowedtags)) {
         $allowedHTML = array();
         $allowableHTML = System::getVar('AllowableHTML');
         if (is_array($allowableHTML)) {
             foreach ($allowableHTML as $k => $v) {
                 if ($k == '!--') {
                     if ($v != 0) {
                         $allowedHTML[] = "{$k}.*?--";
                     }
                 } else {
                     switch ($v) {
                         case 0:
                             break;
                         case 1:
                             $allowedHTML[] = "/?{$k}\\s*/?";
                             break;
                         case 2:
                             $allowedHTML[] = "/?\\s*{$k}" . "(\\s+[\\w:]+\\s*=\\s*(\"[^\"]*\"|'[^']*'))*" . '\\s*/?';
                             break;
                     }
                 }
             }
         }
         if (count($allowedHTML) > 0) {
             $allowedtags = '~<\\s*(' . implode('|', $allowedHTML) . ')\\s*>~is';
         } else {
             $allowedtags = '';
         }
     }
     if (!isset($outputfilter)) {
         if (ModUtil::available('SecurityCenterModule') && !System::isInstalling()) {
             $outputfilter = System::getVar('outputfilter');
         } else {
             $outputfilter = 0;
         }
     }
     if (is_array($var)) {
         foreach ($var as $k => $v) {
             $var[$k] = self::formatForDisplayHTML($v);
         }
     } else {
         // Run additional filters
         if ($outputfilter > 0) {
             $event->setData($var)->setArgument('filter', $outputfilter);
             $var = EventUtil::dispatch('system.outputfilter', $event)->getData();
         }
         // Preparse var to mark the HTML that we want
         if (!empty($allowedtags)) {
             $var = preg_replace($allowedtags, "\\1", $var);
         }
         // Encode email addresses
         $var = preg_replace($search, $replace, $var);
         // Fix html entities
         $var = htmlspecialchars($var);
         // Fix the HTML that we want
         $var = preg_replace_callback('#\\022([^\\024]*)\\024#', create_function('$m', 'return DataUtil::formatForDisplayHTML_callback($m);'), $var);
         // Fix entities if required
         if (System::getVar('htmlentities')) {
             $var = preg_replace('/&amp;([a-z#0-9]+);/i', "&\\1;", $var);
         }
     }
     return $var;
 }
예제 #24
0
 /**
  * Perform some checks that might result in a die() upon failure.
  *
  * Listens on the 'core.preinit' event.
  *
  * @param Zikula_Event $event Event.
  *
  * @return void
  */
 public function systemCheck(Zikula_Event $event)
 {
     $die = false;
     if (get_magic_quotes_runtime()) {
         echo __('Error! Zikula does not support PHP magic_quotes_runtime - please disable this feature in php.ini.');
         $die = true;
     }
     if (ini_get('magic_quotes_gpc')) {
         echo __('Error! Zikula does not support PHP magic_quotes_gpc = On - please disable this feature in your php.ini file.');
         $die = true;
     }
     if (ini_get('register_globals')) {
         echo __('Error! Zikula does not support PHP register_globals = On - please disable this feature in your php.ini or .htaccess file.');
         $die = true;
     }
     // check PHP version, shouldn't be necessary, but....
     $x = explode('.', str_replace('-', '.', phpversion()));
     $phpVersion = "{$x['0']}.{$x['1']}.{$x['2']}";
     if (version_compare($phpVersion, Zikula_Core::PHP_MINIMUM_VERSION, '>=') == false) {
         echo __f('Error! Zikula requires PHP version %1$s or greater. Your server seems to be using version %2$s.', array(Zikula_Core::PHP_MINIMUM_VERSION, $phpVersion));
         $die = true;
     }
     // token_get_all needed for Smarty
     if (!function_exists('token_get_all')) {
         echo __("Error! PHP 'token_get_all()' is required but unavailable.");
         $die = true;
     }
     // mb_string is needed too
     if (!function_exists('mb_get_info')) {
         echo __("Error! PHP must have the mbstring extension loaded.");
         $die = true;
     }
     if (!function_exists('fsockopen')) {
         echo __("Error! The PHP function 'fsockopen()' is needed within the Zikula mailer module, but is not available.");
         $die = true;
     }
     if ($die) {
         echo __("Please configure your server to meet the Zikula system requirements.");
         exit;
     }
     if (System::isDevelopmentMode() || System::isInstalling()) {
         $temp = $this->serviceManager->getArgument('temp');
         if (!is_dir($temp) || !is_writable($temp)) {
             echo __f('The temporary directory "%s" and its subfolders must be writable.', $temp) . '<br />';
             die(__('Please ensure that the permissions are set correctly on your server.'));
         }
         $folders = array($temp, "{$temp}/error_logs", "{$temp}/view_compiled", "{$temp}/view_cache", "{$temp}/Theme_compiled", "{$temp}/Theme_cache", "{$temp}/Theme_Config", "{$temp}/Theme_cache", "{$temp}/purifierCache", "{$temp}/idsTmp");
         foreach ($folders as $folder) {
             if (!is_dir($folder)) {
                 mkdir($folder, $this->serviceManager->getArgument('system.chmod_dir'), true);
             }
             if (!is_writable($folder)) {
                 echo __f("System error! Folder '%s' was not found or is not writable.", $folder) . '<br />';
                 $die = true;
             }
         }
     }
     if ($die) {
         echo __('Please ensure that the permissions are set correctly for the mentioned folders.');
         exit;
     }
 }
예제 #25
0
 /**
  * Create a block position.
  *
  * @param string $args['name'] name of the position.
  * @param string $args['description'] description of the position.
  *
  * @return mixed position ID on success, false on failure.
  */
 public function createposition($args)
 {
     // Argument check
     if (!isset($args['name']) || !strlen($args['name']) || !isset($args['description'])) {
         return LogUtil::registerArgsError();
     }
     // Security check
     if (!System::isInstalling() && !SecurityUtil::checkPermission('Blocks::position', "{$args['name']}::", ACCESS_ADD)) {
         return LogUtil::registerPermissionError();
     }
     $positions = ModUtil::apiFunc('Blocks', 'user', 'getallpositions');
     if (isset($positions) && is_array($positions)) {
         foreach ($positions as $position) {
             if ($position['name'] == $args['name']) {
                 return LogUtil::registerError($this->__('Error! There is already a block position with the name you entered.'));
             }
         }
     }
     $item = array('name' => $args['name'], 'description' => $args['description']);
     if (!DBUtil::insertObject($item, 'block_positions', 'pid')) {
         return LogUtil::registerError($this->__('Error! Could not create the new item.'));
     }
     // Return the id of the newly created item to the calling process
     return $item['pid'];
 }
예제 #26
0
 /**
  * Load system plugins.
  *
  * Implements 'core.init' event when Zikula_Core::STAGE_TABLES.
  *
  * @param Zikula_Event $event The event handler.
  *
  * @return void
  */
 public function systemPlugins(Zikula_Event $event)
 {
     if ($event['stage'] & Zikula_Core::STAGE_TABLES) {
         if (!System::isInstalling()) {
             ServiceUtil::loadPersistentServices();
             PluginUtil::loadPlugins(realpath(realpath('.') . '/plugins'), "SystemPlugin");
             EventUtil::loadPersistentEvents();
         }
     }
 }
예제 #27
0
파일: LogUtil.php 프로젝트: Silwereth/core
 /**
  * Log the given message under the given level
  *
  * @param string $msg   The message to log.
  * @param string $level The log to log this message under(optional)(default='DEFAULT').
  *
  * @return void
  */
 public static function log($msg, $level = Log::DEBUG)
 {
     if (System::isInstalling()) {
         return;
     }
     $serviceManager = ServiceUtil::getManager();
     if (!$serviceManager->has('logger')) {
         return;
     }
     // @todo remove in 1.5.0 this is a BC hack - drak
     if ($level === E_USER_DEPRECATED) {
         $level = Log::DEBUG;
     }
     /** @var Log $logger */
     $logger = $serviceManager->get('logger');
     $logger->log($level, $msg);
 }
예제 #28
0
 /**
  * Configure caching.
  *
  * Listens for 'doctrine.configure' events.
  * Subject is expected to be the Doctrine_Manager.
  *
  * @param Zikula_Event $event Event.
  *
  * @return void
  */
 public function configureCache(Zikula_Event $event)
 {
     $manager = $event->getSubject();
     if (!System::isInstalling() && $this->serviceManager['dbcache.enable']) {
         $type = $this->serviceManager['dbcache.type'];
         // Setup Doctrine Caching
         $type = ucfirst(strtolower($type));
         $doctrineCacheClass = "Doctrine_Cache_{$type}";
         $r = new ReflectionClass($doctrineCacheClass);
         $options = array('prefix' => 'dd');
         if (strpos($type, 'Memcache') === 0) {
             $servers = $this->serviceManager['dbcache.servers'];
             $options = array_merge($options, array('servers' => $servers, 'compression' => $this->serviceManager['dbcache.compression']));
         }
         $cacheDriver = $this->serviceManager->attachService('doctrine.cachedriver', $r->newInstance($options));
         $manager->setAttribute(Doctrine_Core::ATTR_QUERY_CACHE, $cacheDriver);
         $manager->setAttribute(Doctrine_Core::ATTR_RESULT_CACHE, $cacheDriver);
         // implment resultcache lifespan configuration variable
         $manager->setAttribute(Doctrine_Core::ATTR_RESULT_CACHE_LIFESPAN, $this->serviceManager['dbcache.cache_result_ttl']);
         // Support for multisites to prevent clashes
         $name = 'default';
         // todo - drak
         $cacheDriver->setOption('prefix', md5(serialize($this->serviceManager['databases'][$name])));
     }
 }
예제 #29
0
 /**
  * Gets the themes table.
  *
  * Small wrapper function to avoid duplicate sql.
  *
  * @access private
  * @return array Modules table.
  */
 public static function getThemesTable()
 {
     static $themestable;
     if (!isset($themestable) || System::isInstalling()) {
         // get entityManager
         $sm = ServiceUtil::getManager();
         $entityManager = $sm->get('doctrine')->getEntityManager();
         // get all themes
         $themes = $entityManager->getRepository('ThemeModule\\Entity\\Theme')->findAll();
         foreach ($themes as $theme) {
             $theme = $theme->toArray();
             $theme['i18n'] = is_dir("themes/{$theme['name']}/Resources/locale") ? 1 : 0;
             $themestable[$theme['id']] = $theme;
         }
     }
     return $themestable;
 }
예제 #30
0
    /**
     * add a module to a category
     * @param  string $args['module']   name of the module
     * @param  int    $args['category'] number of the category
     * @return mixed  admin category ID on success, false on failure
     */
    public function addmodtocategory($args)
    {
        if (!isset($args['module']) ||
            !isset($args['category'])) {
            return LogUtil::registerArgsError();
        }

        // this function is called durung the init process so we have to check in installing
        // is set as alternative to the correct permission check
        if (!System::isInstalling() && !SecurityUtil::checkPermission('Admin::Category', "::", ACCESS_ADD)) {
            return LogUtil::registerPermissionError ();
        }

        $entity = $this->name . '_Entity_AdminModule';

        // get module id
        $mid = (int)ModUtil::getIdFromName($args['module']);

        $item = $this->entityManager->getRepository($entity)->findOneBy(array('mid' => $mid));
        if (!$item) {
            $item = new $entity;
        }

        $values = array();
        $values['cid'] = (int)$args['category'];
        $values['mid'] = $mid;
        $values['sortorder'] = ModUtil::apiFunc('Admin', 'admin', 'countModsInCat', array('cid' => $args['category']));

        $item->merge($values);
        $this->entityManager->persist($item);
        $this->entityManager->flush();

        // Return success
        return true;
    }