Example #1
0
 public static function getEFMConfig()
 {
     require_once 'modules/Scribite/plugins/Xinha/vendor/xinha/contrib/php-xinha.php';
     $zikulaBaseURI = rtrim(System::getBaseUri(), '/');
     $zikulaBaseURI = ltrim($zikulaBaseURI, '/');
     // define backend configuration for the plugin
     $IMConfig = array();
     $IMConfig['images_dir'] = '/files/';
     $IMConfig['images_url'] = 'files/';
     $IMConfig['files_dir'] = '/files/';
     $IMConfig['files_url'] = 'files';
     $IMConfig['thumbnail_prefix'] = 't_';
     $IMConfig['thumbnail_dir'] = 't';
     $IMConfig['resized_prefix'] = 'resized_';
     $IMConfig['resized_dir'] = '';
     $IMConfig['tmp_prefix'] = '_tmp';
     $IMConfig['max_filesize_kb_image'] = 2000;
     // maximum size for uploading files in 'insert image' mode (2000 kB here)
     $IMConfig['max_filesize_kb_link'] = 5000;
     // maximum size for uploading files in 'insert link' mode (5000 kB here)
     // Maximum upload folder size in Megabytes.
     // Use 0 to disable limit
     $IMConfig['max_foldersize_mb'] = 0;
     $IMConfig['allowed_image_extensions'] = array("jpg", "gif", "png");
     $IMConfig['allowed_link_extensions'] = array("jpg", "gif", "pdf", "ip", "txt", "psd", "png", "html", "swf", "xml", "xls");
     xinha_pass_to_php_backend($IMConfig);
     return $IMConfig;
 }
/**
 * Zikula_View function to obtain base URL for this site
 *
 * This function obtains the base URL for the site. The base url is defined as the
 * full URL for the site minus any file information  i.e. everything before the
 * 'index.php' from your start page.
 * Unlike the API function System::getBaseUrl, the results of this function are already
 * sanitized to display, so it should not be passed to the safetext modifier.
 *
 * Available parameters:
 *   - assign:   If set, the results are assigned to the corresponding variable instead of printed out
 *
 * Example
 *   {getbaseurl}
 *
 * @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 base URL of the site.
 */
function smarty_function_getbaseuri($params, Zikula_View $view)
{
    LogUtil::log(__f('Warning! Template plugin {%1$s} is deprecated, please use {%2$s} instead.', array('getbaseuri', '$baseuri')), E_USER_DEPRECATED);
    $assign = isset($params['assign']) ? $params['assign'] : null;
    $result = htmlspecialchars(System::getBaseUri());
    if ($assign) {
        $view->assign($assign, $result);
    } else {
        return $result;
    }
}
Example #3
0
 /**
  * Generate a configuration for javascript and return script tag to embed in HTML HEAD.
  *
  * @return string HTML code with script tag
  */
 public static function getJSConfig()
 {
     $return = '';
     $config = array('entrypoint' => System::getVar('entrypoint', 'index.php'), 'baseURL' => System::getBaseUrl(), 'baseURI' => System::getBaseUri() . '/', 'ajaxtimeout' => (int) System::getVar('ajaxtimeout', 5000), 'lang' => ZLanguage::getLanguageCode(), 'sessionName' => session_name());
     $config = DataUtil::formatForDisplay($config);
     $return .= "<script type=\"text/javascript\">/* <![CDATA[ */ \n";
     if (System::isLegacyMode()) {
         $return .= 'document.location.entrypoint="' . $config['entrypoint'] . '";';
         $return .= 'document.location.ajaxtimeout=' . $config['ajaxtimeout'] . ";\n";
     }
     $return .= "if (typeof(Zikula) == 'undefined') {var Zikula = {};}\n";
     $return .= "Zikula.Config = " . json_encode($config) . "\n";
     $return .= ' /* ]]> */</script>' . "\n";
     return $return;
 }
/**
 * 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]);
}
Example #5
0
 public function start()
 {
     $config = array('gc_probability' => System::getVar('gc_probability'), 'gc_divisor' => 10000, 'gc_maxlifetime' => System::getVar('secinactivemins'));
     $path = System::getBaseUri();
     if (empty($path)) {
         $path = '/';
     } elseif (substr($path, -1, 1) != '/') {
         $path .= '/';
     }
     $config['cookie_path'] = $path;
     $host = System::serverGetVar('HTTP_HOST');
     if (($pos = strpos($host, ':')) !== false) {
         $host = substr($host, 0, $pos);
     }
     // PHP configuration variables
     // Set lifetime of session cookie
     $seclevel = System::getVar('seclevel');
     switch ($seclevel) {
         case 'High':
             // Session lasts duration of browser
             $lifetime = 0;
             // Referer check
             // ini_set('session.referer_check', $host.$path);
             $config['referer_check'] = $host;
             break;
         case 'Medium':
             // Session lasts set number of days
             $lifetime = System::getVar('secmeddays') * 86400;
             break;
         case 'Low':
         default:
             // (Currently set to 1 year)
             $lifetime = 31536000;
             break;
     }
     $config['cookie_lifetime'] = $lifetime;
     $this->storage->setOptions($config);
     return parent::start();
 }
function smarty_function_iwqvuserprintstate($params, &$smarty) {
    $dom = ZLanguage::getModuleDomain('IWqv');
    if (!isset($params['class'])) {
        $params['class'] = 'pn-menuitem-title';
    }

    $html = "<span class=\"" . $params['class'] . "\">";
    if (count($params['states']) > 0) {
        if (isset($params['states'][2]) && $params['sections'] == $params['states'][2]) {
            // All the sections are revised
            $html.="<img src=\"" . System::getBaseUri() . "/modules/IWqv/pnimages/state_corrected.gif\" alt=\"" . __('Corrected', $dom) . "\">";
        } else if (isset($params['states'][1]) && $params['states'][1] > 0) {
            // There is at least one section to revise
            $html.="<img src=\"" . System::getBaseUri() . "/modules/IWqv/pnimages/state_delivered.gif\" alt=\"" . __('Delivered', $dom) . "\">";
        } else {
            // The qv is started
            $html.="<img src=\"" . System::getBaseUri() . "/modules/IWqv/pnimages/state_started.gif\" alt=\"" . __('Started', $dom) . "\">";
        }
    }

    $html.="</span>\n";

    return $html;
}
Example #7
0
 /**
  * Save combined pagevars.
  *
  * @param array  $files     Files.
  * @param string $ext       Extention.
  * @param string $cache_dir Cache directory.
  *
  * @return array Array of file with combined pagevars file and remote files
  */
 private static function save($files, $ext, $cache_dir)
 {
     $themevars = ModUtil::getVar('ZikulaThemeModule');
     $lifetime = $themevars['cssjscombine_lifetime'];
     $hash = md5(serialize($files) . UserUtil::getTheme());
     $cachedFile = "{$cache_dir}/{$hash}_{$ext}.php";
     $cachedFileUri = "{$hash}_{$ext}.php";
     if (is_readable($cachedFile) && ($lifetime == -1 || filemtime($cachedFile) + $lifetime > time())) {
         return System::getBaseUri() . '/jcss.php?f=' . $cachedFileUri;
     }
     switch ($ext) {
         case 'css':
             $ctype = 'text/css';
             break;
         case 'js':
             $ctype = 'text/javascript';
             break;
         default:
             $ctype = 'text/plain';
             break;
     }
     $includedFiles = array();
     $outputFiles = array();
     $contents = array();
     $dest = fopen($cachedFile, 'w');
     foreach ($files as $file) {
         if (!empty($file)) {
             // skip remote files from combining
             if (is_file($file)) {
                 self::readfile($contents, $file, $ext);
                 $includedFiles[] = $file;
             } else {
                 $outputFiles[] = $file;
             }
         }
     }
     array_unshift($contents, "/* --- Combined file written: " . DateUtil::getDateTime() . " */\n\n");
     array_unshift($contents, "/* --- Combined files:\n" . implode("\n", $includedFiles) . "\n*/\n\n");
     $contents = implode('', $contents);
     // optional minify
     if ($themevars['cssjsminify'] && $ext == 'css') {
         // Remove comments.
         $contents = trim(preg_replace('/\\/\\*.*?\\*\\//s', '', $contents));
         // Compress whitespace.
         $contents = preg_replace('/\\s+/', ' ', $contents);
         // Additional whitespace optimisation -- spaces around certain tokens is not required by CSS
         $contents = preg_replace('/\\s*(;|\\{|\\}|:|,)\\s*/', '\\1', $contents);
     }
     global $ZConfig;
     $signingKey = md5(serialize($ZConfig['DBInfo']['databases']['default']));
     $signature = md5($contents . $ctype . $lifetime . $themevars['cssjscompress'] . $signingKey);
     $data = array('contents' => $contents, 'ctype' => $ctype, 'lifetime' => $lifetime, 'gz' => $themevars['cssjscompress'], 'signature' => $signature);
     fwrite($dest, serialize($data));
     fclose($dest);
     $combined = System::getBaseUri() . '/jcss.php?f=' . $cachedFileUri;
     array_unshift($outputFiles, $combined);
     return $outputFiles;
 }
Example #8
0
/**
 * Available params:
 *  - image         (string)        Path to source image (required)
 *  - width         (int)           Thumbnail width in pixels or 'auto' (optional, default value based on 'default' preset)
 *  - height        (int)           Thumbnail width in pixels or 'auto' (optional, default value based on 'default' preset)
 *  - mode          (string)        Thumbnail mode; 'inset' or 'outbound' (optional, default 'inset')
 *                                  In outbound mode auto width or height gives the same effect as inset
 *  - extension     (string)        File extension for thumbnails: jpg, png, gif; null for original file type
 *                                  (optional, default value based on 'default' preset)
 *  - options       (array)         Options array given to the thumbnail Imagine method call.
 *  - options[jpeg_quality]          
 *                  (int)           Thumbnail jpeg quality in % [0-100], where 100% is best quality (optional, default value based on 'default' preset)
 *  - options[png_compression_level] 
 *                  (int)           Thumbnail png compression level [0-9], where 0 is no compression (optional, default value based on 'default' preset)
 *  - objectid      (string)        Unique signature for object, which owns this thumbnail (optional)
 *  - preset        (string|object) Name of preset defined in Imagine or custom preset passed as instance of
 *                                  SystemPlugin_Imagine_Preset; if given inline options ('width', 'heigth', 'mode'
 *                                  and 'extension') are ignored (optional)
 *  - manager       (object)        Instance of SystemPlugin_Imagine_Manager; if given inline options ('width',
 *                                  'heigth', 'mode' and 'extension') are ignored (optional)
 *  - fqurl         (boolean)       If set the thumb path is absolute, if not relative
 *  - tag           (boolean)       If set to true - full <img> tag will be generated. Tag attributes should be
 *                                  passed with "img_" prefix (for example: "img_class"). Getttext prefix may be
 *                                  used for translations (for example: "__img_alt")
 *
 * Examples
 *
 * Basic usage with inline options:
 *  {thumb image='path/to/image.png' width='100' height='100' mode='inset' extension='jpg'}
 *  {thumb image='path/to/image.png' width='150' height='auto' mode='inset' extension='png'}
 *  {thumb image='path/to/image.jpg' width='150' 'jpeg_quality'=50}
 *
 * Using preset define in Imagine plugin
 *  {thumb image='path/to/image.png' objectid='123' preset='my_preset'}
 *
 * Using custom preset, defined in module and passed to template
 *  {thumb image='path/to/image.png' objectid='123' preset=$preset}
 *
 * Using custom SystemPlugin_Imagine_Manager instance, defined in module and passed to template
 *  {thumb image='path/to/image.png' objectid='123' manager=$manager}
 *
 * Generating full img tag
 *  {thumb image='path/to/image.png' objectid='123' preset=$preset tag=true __img_alt='Alt text, gettext prefix may be used' img_class='image-class'}
 * This will generate:
 *  <img src="thumb/path" widht="100" height="100" alt="Alt text, gettext prefix may be used" class="image-class" />
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the {@link Zikula_View} object.
 *
 * @return string thumb path
 */
function smarty_function_thumb($params, Zikula_View $view)
{
    if (!isset($params['image']) || empty($params['image'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('smarty_function_thumb', 'image')));
        return false;
    }
    $image = $params['image'];
    $objectId = isset($params['objectid']) ? $params['objectid'] : null;
    if (isset($params['manager']) && $params['manager'] instanceof SystemPlugin_Imagine_Manager) {
        $manager = $params['manager'];
    } else {
        $manager = $view->getContainer()->get('systemplugin.imagine.manager');
    }
    if (isset($params['preset']) && $params['preset'] instanceof SystemPlugin_Imagine_Preset) {
        $preset = $params['preset'];
    } elseif (isset($params['preset']) && $manager->getPlugin()->hasPreset($params['preset'])) {
        $preset = $manager->getPlugin()->getPreset($params['preset']);
    } else {
        $preset = array();
        $preset['width'] = isset($params['width']) ? $params['width'] : 'auto';
        $preset['height'] = isset($params['height']) ? $params['height'] : 'auto';
        $preset['mode'] = isset($params['mode']) ? $params['mode'] : null;
        $preset['extension'] = isset($params['extension']) ? $params['extension'] : null;
        $preset['options'] = isset($params['options']) ? $params['options'] : array();
        $preset = array_filter($preset);
    }
    $manager->setPreset($preset);
    $thumb = $manager->getThumb($image, $objectId);
    $basePath = isset($params['fqurl']) && $params['fqurl'] ? System::getBaseUrl() : System::getBaseUri();
    $result = "{$basePath}/{$thumb}";
    if (isset($params['tag']) && $params['tag']) {
        $thumbSize = @getimagesize($thumb);
        $attributes = array();
        $attributes[] = "src=\"{$basePath}/{$thumb}\"";
        $attributes[] = $thumbSize[3];
        // width and height
        // get tag params
        foreach ($params as $key => $value) {
            if (strpos($key, 'img_') === 0) {
                $key = str_replace('img_', '', $key);
                $attributes[$key] = "{$key}=\"{$value}\"";
            }
        }
        if (!isset($attributes['alt'])) {
            $attributes[] = 'alt=""';
        }
        $attributes = implode(' ', $attributes);
        $result = "<img {$attributes} />";
    }
    if (isset($params['assign'])) {
        $view->assign($params['assign'], $result);
    } else {
        return $result;
    }
}
 public function getUrl()
 {
     return \System::getBaseUri() . '/' . $this->getPath();
 }
Example #10
0
 /**
  * Create a comment for a specific item
  *
  * This is a standard function that is called with the results of the
  * form supplied by EZComments_user_view to create a new item
  *
  * @param $comment the comment (taken from HTTP put)
  * @param $mod the name of the module the comment is for (taken from HTTP put)
  * @param $objectid ID of the item the comment is for (taken from HTTP put)
  * @param $redirect URL to return to (taken from HTTP put)
  * @param $subject The subject of the comment (if any) (taken from HTTP put)
  * @param $replyto The ID of the comment for which this an anser to (taken from HTTP put)
  * @since 0.1
  */
 public function create($args)
 {
     $mod = isset($args['mod']) ? $args['mod'] : FormUtil::getPassedValue('mod', null, 'POST');
     $objectid = isset($args['objectid']) ? $args['objectid'] : FormUtil::getPassedValue('objectid', null, 'POST');
     $areaid = isset($args['areaid']) ? $args['areaid'] : FormUtil::getPassedValue('areaid', null, 'POST');
     $comment = isset($args['comment']) ? $args['comment'] : FormUtil::getPassedValue('comment', null, 'POST');
     $subject = isset($args['subject']) ? $args['subject'] : FormUtil::getPassedValue('subject', null, 'POST');
     $replyto = isset($args['replyto']) ? $args['replyto'] : FormUtil::getPassedValue('replyto', null, 'POST');
     $owneruid = isset($args['owneruid']) ? $args['owneruid'] : FormUtil::getPassedValue('owneruid', null, 'POST');
     $redirect = isset($args['redirect']) ? $args['redirect'] : FormUtil::getPassedValue('redirect', null, 'POST');
     $useurl = isset($args['useurl']) ? $args['useurl'] : FormUtil::getPassedValue('useurl', null, 'POST');
     // check if the user logged in and if we're allowing anon users to
     // set a name and email address
     if (!UserUtil::isLoggedIn()) {
         $anonname = isset($args['anonname']) ? $args['anonname'] : FormUtil::getPassedValue('anonname', null, 'POST');
         $anonmail = isset($args['anonmail']) ? $args['anonmail'] : FormUtil::getPassedValue('anonmail', null, 'POST');
         $anonwebsite = isset($args['anonwebsite']) ? $args['anonwebsite'] : FormUtil::getPassedValue('anonwebsite', null, 'POST');
     } else {
         $anonname = '';
         $anonmail = '';
         $anonwebsite = '';
     }
     if (!isset($owneruid) || !($owneruid > 1)) {
         $owneruid = 0;
     }
     $redirect = str_replace('&amp;', '&', base64_decode($redirect));
     $redirect = !empty($redirect) ? $redirect : System::serverGetVar('HTTP_REFERER');
     $useurl = base64_decode($useurl);
     // save the submitted data if any error occurs
     $ezcomment = unserialize(SessionUtil::getVar('ezcomment', 'a:0:{}'));
     if (isset($ezcomment[$mod][$objectid])) {
         unset($ezcomment[$mod][$objectid]);
     }
     if (!empty($subject)) {
         $ezcomment[$mod][$objectid]['subject'] = $subject;
     }
     if (!empty($comment)) {
         $ezcomment[$mod][$objectid]['comment'] = $comment;
     }
     if (!empty($anonname)) {
         $ezcomment[$mod][$objectid]['anonname'] = $anonname;
     }
     if (!empty($anonmail)) {
         $ezcomment[$mod][$objectid]['anonmail'] = $anonmail;
     }
     if (!empty($anonwebsite)) {
         $ezcomment[$mod][$objectid]['anonwebsite'] = $anonwebsite;
     }
     // Confirm authorisation code
     // check csrf token
     SessionUtil::setVar('ezcomment', serialize($ezcomment));
     $this->checkCsrfToken();
     SessionUtil::delVar('ezcomment');
     // and check we've actually got a comment....
     if (empty($comment)) {
         SessionUtil::setVar('ezcomment', serialize($ezcomment));
         return LogUtil::registerError($this->__('Error! The comment contains no text.'), null, $redirect . "#commentform_{$mod}_{$objectid}");
     }
     // Check hooked modules for validation
     $hookvalidators = $this->notifyHooks(new Zikula_ValidationHook('ezcomments.ui_hooks.comments.validate_edit', new Zikula_Hook_ValidationProviders()))->getValidators();
     if ($hookvalidators->hasErrors()) {
         SessionUtil::setVar('ezcomment', serialize($ezcomment));
         return LogUtil::registerError($this->__('Error! The hooked content does not validate. Could it possibly be that a captcha code was entered incorrectly?'), null, $redirect . "#commentform_{$mod}_{$objectid}");
     }
     // now parse out the hostname+subfolder from the url for storing in the DB
     $url = str_replace(System::getBaseUri(), '', $useurl);
     $id = ModUtil::apiFunc('EZComments', 'user', 'create', array('mod' => $mod, 'objectid' => $objectid, 'areaid' => $areaid, 'url' => $url, 'comment' => $comment, 'subject' => $subject, 'replyto' => $replyto, 'uid' => UserUtil::getVar('uid'), 'owneruid' => $owneruid, 'useurl' => $useurl, 'redirect' => $redirect, 'anonname' => $anonname, 'anonmail' => $anonmail, 'anonwebsite' => $anonwebsite));
     if ($id) {
         // clear respective cache
         ModUtil::apiFunc('EZComments', 'user', 'clearItemCache', array('id' => $id, 'modname' => $mod, 'objectid' => $objectid, 'url' => $url));
     } else {
         // redirect if it was not successful
         SessionUtil::setVar('ezcomment', $ezcomment);
         System::redirect($redirect . "#commentform_{$mod}_{$objectid}");
     }
     // clean/set the session data
     if (isset($ezcomment[$mod][$objectid])) {
         unset($ezcomment[$mod][$objectid]);
         if (empty($ezcomment[$mod])) {
             unset($ezcomment[$mod]);
         }
     }
     if (empty($ezcomment)) {
         SessionUtil::delVar('ezcomment');
     } else {
         SessionUtil::setVar('ezcomment', serialize($ezcomment));
     }
     return System::redirect($redirect . '#comment' . $id);
 }
Example #11
0
/**
 * 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;
    }
}
Example #12
0
 private static function resolveSymfonyAsset($path)
 {
     if (is_array($path)) {
         $return = array();
         foreach ($path as $key => $value) {
             $return[$key] = self::resolveSymfonyAsset($value);
         }
         return $return;
     }
     if (substr($path, 0, 1) != "@") {
         return $path;
     }
     $sm = \ServiceUtil::getManager();
     $kernel = $sm->get('kernel');
     $root = realpath($kernel->getRootDir() . "/../");
     $fullPath = $kernel->locateResource($path);
     $path = System::getBaseUri() . str_replace(DIRECTORY_SEPARATOR, '/', substr($fullPath, strlen($root)));
     return $path;
 }
Example #13
0
/**
 * 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)
 *   - 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 and fill pnimg_error instead
 *   - 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}
 * <img src="/Theme/images/powered/xhtml11.png" alt="" width="88" height="31"  />
 *
 * 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'])) ? true : false;

    if (!isset($params['src'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('img', 'src')));
        if ($nostoponerror == true) {
            return;
        } else {
            return false;
        }
    }

    // default for the module
    $modname = isset($params['modname']) ? $params['modname'] : $view->toplevelmodule;

    // if the module name is 'core' then we require an image set
    if ($modname == 'core') {
        if (!isset($params['set'])) {
            $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('img', 'set')));
            if ($nostoponerror == true) {
                return;
            } else {
                return false;
            }
        }
        $osset = DataUtil::formatForOS($params['set']);
        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_DEPRECATED);
            $params['src'] = str_replace('.gif', '.png', $params['src']);
        }
    }

    // default for the optional flag
    $optional = isset($params['optional']) ? $params['optional'] : true;

    // always provide an alt attribute.
    // if none is set, assign an empty one.
    $params['alt'] = isset($params['alt']) ? $params['alt'] : '';

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

    // prevent overwriting surrounding titles (#477)
    if (empty($params['title'])) {
        unset($params['title']);
    }

    // language
    $lang =  ZLanguage::transformFS(ZLanguage::getLanguageCode());

    // theme directory
    $theme         = DataUtil::formatForOS(UserUtil::getTheme());
    $osmodname     = DataUtil::formatForOS($modname);
    $themelangpath = "themes/$theme/templates/modules/$osmodname/images/$lang";
    $themepath     = "themes/$theme/templates/modules/$osmodname/images";
    $corethemepath = "themes/$theme/images";

    // module directory
    $modinfo       = ModUtil::getInfoFromName($modname);
    $osmoddir      = DataUtil::formatForOS($modinfo['directory']);
    $moduleDir     = ($modinfo['type'] == ModUtil::TYPE_SYSTEM ? 'system' : 'modules');
    if ($modname == 'core') {
        $modpath        = "images/$osset";
    } else {
        $modlangpath    = "$moduleDir/$osmoddir/images/$lang";
        $modpath        = "$moduleDir/$osmoddir/images";
        $modlangpathOld = "$moduleDir/$osmoddir/pnimages/$lang";
        $modpathOld     = "$moduleDir/$osmoddir/pnimages";
    }
    $ossrc = DataUtil::formatForOS($params['src']);

    // form the array of paths
    if ($modname == 'core') {
        $paths = array($themepath, $corethemepath, $modpath);
    } else {
        $paths = array($themelangpath, $themepath, $corethemepath, $modlangpath, $modpath, $modlangpathOld, $modpathOld);
    }

    // search for the image
    $imgsrc = '';
    foreach ($paths as $path) {
        if (is_readable("$path/$ossrc")) {
            $imgsrc = "$path/$ossrc";
            break;
        }
    }

    if ($imgsrc == '' && isset($params['default'])) {
        $imgsrc = $params['default'];
    }

    if ($imgsrc == '') {
        if ($optional) {
            $view->trigger_error(__f("%s: Image '%s' not found", array('img', DataUtil::formatForDisplay($params['src']))));
            if ($nostoponerror == true) {
                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))) {
            $view->trigger_error(__f("%s: Image '%s' is not a valid image file", array('pnimg', DataUtil::formatForDisplay($params['src']))));
            if ($nostoponerror == true) {
                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;

    unset($params['modname']);
    $assign = null;
    if (isset($params['assign'])) {
        $assign = $params['assign'];
        unset($params['assign']);
    }
    unset($params['retval']);
    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];
    } else if (!empty($assign)) {
        $params['imgtag'] = $imgtag;
        $view->assign($assign, $params);
    } else {
        return $imgtag;
    }
}
Example #14
0
 /**
  * Bind domain.
  *
  * @param string $domain Gettext domain.
  * @param string $path   Domain path.
  *
  * @return boolean
  */
 public static function bindDomain($domain, $path)
 {
     $_this = self::getInstance();
     $locale = $_this->getLocale();
     if (!$locale) {
         // fallback solution to be replaced by proper routing
         $defaultLocale = System::getVar('language_i18n', 'en');
         if (System::getVar('shorturls')) {
             // we need to extract the language code from current url, since it is not ensured
             // that System::queryStringDecode() has been executed already
             $customentrypoint = System::getVar('entrypoint');
             $expectEntrypoint = !System::getVar('shorturlsstripentrypoint');
             $root = empty($customentrypoint) ? 'index.php' : $customentrypoint;
             // get base path to work out our current url
             $parsedURL = parse_url(System::getCurrentUri());
             $tobestripped = array(System::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);
             }
             if (isset($args[0]) && self::isLangParam($args[0]) && in_array($args[0], self::getInstalledLanguages())) {
                 $defaultLocale = $args[0];
             }
         }
         $_this->setLocale($defaultLocale);
         $locale = $_this->getLocale();
     }
     // exit if the language system hasnt yet fully initialised
     if (!$locale) {
         return false;
     }
     // prevent double loading
     if (array_key_exists($domain, $_this->domainCache[$locale])) {
         return true;
     }
     ZGettext::getInstance()->bindTextDomain($domain, $path);
     ZGettext::getInstance()->bindTextDomainCodeset($domain, $_this->encoding);
     $_this->domainCache[$locale][$domain] = true;
     return $_this->domainCache[$locale][$domain];
 }
Example #15
0
    /**
     * Constructor.
     *
     * @param Zikula_ServiceManager $serviceManager ServiceManager.
     * @param string                $moduleName     Module name ("zikula" for system plugins).
     * @param integer|null          $caching        Whether or not to cache (Zikula_View::CACHE_*) or use config variable (null).
     */
    public function __construct(Zikula_ServiceManager $serviceManager, $moduleName = '', $caching = null)
    {
        $this->serviceManager = $serviceManager;
        $this->eventManager = $this->serviceManager->getService('zikula.eventmanager');
        $this->request = $this->serviceManager->getService('request');

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        $this->add_core_data();

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

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

        $event = new Zikula_Event('view.init', $this);
        $this->eventManager->notify($event);
    }
Example #16
0
 /**
  * {@inheritdoc}
  */
 public function start()
 {
     $path = System::getBaseUri();
     if (empty($path)) {
         $path = '/';
     } elseif (substr($path, -1, 1) != '/') {
         $path .= '/';
     }
     $host = System::serverGetVar('HTTP_HOST');
     if (($pos = strpos($host, ':')) !== false) {
         $host = substr($host, 0, $pos);
     }
     // PHP configuration variables
     ini_set('session.use_trans_sid', 0);
     // Stop adding SID to URLs
     @ini_set('url_rewriter.tags', '');
     // some environments dont allow this value to be set causing an error that prevents installation
     ini_set('session.serialize_handler', 'php');
     // How to store data
     ini_set('session.use_cookies', 1);
     // Use cookie to store the session ID
     ini_set('session.auto_start', 1);
     // Auto-start session
     ini_set('session.name', SessionUtil::getCookieName());
     // Name of our cookie
     // Set lifetime of session cookie
     $seclevel = System::getVar('seclevel');
     switch ($seclevel) {
         case 'High':
             // Session lasts duration of browser
             $lifetime = 0;
             // Referer check
             // ini_set('session.referer_check', $host.$path);
             ini_set('session.referer_check', $host);
             break;
         case 'Medium':
             // Session lasts set number of days
             $lifetime = System::getVar('secmeddays') * 86400;
             break;
         case 'Low':
         default:
             // Session lasts unlimited number of days (well, lots, anyway)
             // (Currently set to 25 years)
             $lifetime = 788940000;
             break;
     }
     ini_set('session.cookie_lifetime', $lifetime);
     // domain and path settings for session cookie
     // if (System::getVar('intranet') == false) {
     // Cookie path
     ini_set('session.cookie_path', $path);
     // Garbage collection
     ini_set('session.gc_probability', System::getVar('gc_probability'));
     ini_set('session.gc_divisor', 10000);
     ini_set('session.gc_maxlifetime', System::getVar('secinactivemins') * 60);
     // Inactivity timeout for user sessions
     ini_set('session.hash_function', 1);
     // Set custom session handlers
     ini_set('session.save_handler', 'user');
     if (System::getVar('sessionstoretofile')) {
         ini_set('session.save_path', System::getVar('sessionsavepath'));
     }
     session_set_save_handler(array($this, 'open'), array($this, 'close'), array($this, 'read'), array($this, 'write'), array($this, 'destroy'), array($this, 'gc'));
     // create IP finger print
     $current_ipaddr = '';
     $_REMOTE_ADDR = System::serverGetVar('REMOTE_ADDR');
     $_HTTP_X_FORWARDED_FOR = System::serverGetVar('HTTP_X_FORWARDED_FOR');
     if (System::getVar('sessionipcheck')) {
         // feature for future release
     }
     // create the ip fingerprint
     $current_ipaddr = md5($_REMOTE_ADDR . $_HTTP_X_FORWARDED_FOR);
     // start session check expiry and ip fingerprint if required
     if (session_start() && isset($GLOBALS['_ZSession']['obj']) && $GLOBALS['_ZSession']['obj']) {
         // check if session has expired or not
         $now = time();
         $inactive = $now - (int) (System::getVar('secinactivemins') * 60);
         $daysold = $now - (int) (System::getVar('secmeddays') * 86400);
         $lastused = strtotime($GLOBALS['_ZSession']['obj']['lastused']);
         $rememberme = SessionUtil::getVar('rememberme');
         $uid = $GLOBALS['_ZSession']['obj']['uid'];
         $ipaddr = $GLOBALS['_ZSession']['obj']['ipaddr'];
         // IP check
         if (System::getVar('sessionipcheck', false)) {
             if ($ipaddr !== $current_ipaddr) {
                 session_destroy();
                 return false;
             }
         }
         switch (System::getVar('seclevel')) {
             case 'Low':
                 // Low security - users stay logged in permanently
                 //                no special check necessary
                 break;
             case 'Medium':
                 // Medium security - delete session info if session cookie has
                 // expired or user decided not to remember themself and inactivity timeout
                 // OR max number of days have elapsed without logging back in
                 if (!$rememberme && $lastused < $inactive || $lastused < $daysold || $uid == '0' && $lastused < $inactive) {
                     $this->expire();
                 }
                 break;
             case 'High':
             default:
                 // High security - delete session info if user is inactive
                 //if ($rememberme && ($lastused < $inactive)) { // see #427
                 if ($lastused < $inactive) {
                     $this->expire();
                 }
                 break;
         }
     } else {
         // *must* regenerate new session otherwise the default sessid will be
         // taken from any session cookie that was submitted (bad bad bad)
         $this->regenerate(true);
         SessionUtil::_createNew(session_id(), $current_ipaddr);
     }
     if (isset($_SESSION['_ZSession']['obj'])) {
         unset($_SESSION['_ZSession']['obj']);
     }
     return true;
 }
 protected function getIconThumbnailByFileExtension(AbstractFileEntity $entity, $width, $height, $format = 'html', $mode = 'outbound', $optimize = true, $forceExtension = false)
 {
     return false;
     // @todo Re-enable?
     if (!in_array($mode, ['inset', 'outbound'])) {
         throw new \InvalidArgumentException('Invalid mode requested.');
     }
     $mode = 'inset';
     $availableSizes = [16, 32, 48, 512];
     foreach ($availableSizes as $size) {
         if ($width <= $size && $height <= $size) {
             break;
         }
     }
     $extension = $forceExtension ? $forceExtension : pathinfo($entity->getFileName(), PATHINFO_EXTENSION);
     $icon = '@CmfcmfMediaModule/Resources/public/images/file-icons/' . $size . 'px/' . $extension . '.png';
     try {
         $path = $this->getPathToFile($icon);
     } catch (\InvalidArgumentException $e) {
         $icon = '@CmfcmfMediaModule/Resources/public/images/file-icons/' . $size . 'px/_blank.png';
         $path = $this->getPathToFile($icon);
     }
     $this->imagineManager->setPreset($this->getPreset($entity, $path, $width, $height, $mode, $optimize));
     $path = $this->imagineManager->getThumb($path, $entity->getImagineId());
     $url = \System::getBaseUri() . '/' . $path;
     switch ($format) {
         case 'url':
             return $url;
         case 'html':
             return '<img src="' . $url . '" />';
         case 'path':
             return $path;
     }
     throw new \LogicException();
 }
Example #18
0
 /**
  * Initialise scribite for requested areas.
  *
  * @param array $args Text area: 'area', Module name: 'modulename'.
  *
  * @return string
  */
 public static function loader($args)
 {
     $dom = ZLanguage::getModuleDomain('Scribite');
     // Argument checks
     if (!isset($args['areas'])) {
         return LogUtil::registerError(__('Error! Scribite_Api_User::loader() "area" argument was empty.', $dom));
     }
     if (!isset($args['modulename'])) {
         $args['modulename'] = ModUtil::getName();
     }
     $module = $args['modulename'];
     // Security check if user has COMMENT permission for scribite and module
     if (!SecurityUtil::checkPermission('Scribite::', "{$module}::", ACCESS_COMMENT)) {
         return;
     }
     // check for editor argument, if none given the default editor will be used
     if (!isset($args['editor']) || empty($args['editor'])) {
         // get default editor from config
         $defaulteditor = ModUtil::getVar('Scribite', 'DefaultEditor');
         if ($defaulteditor == '-') {
             return;
             // return if no default is set and no arg is given
             // id given editor doesn't exist use default editor
         } else {
             $args['editor'] = $defaulteditor;
         }
     }
     // check if editor argument exists, load default if not given
     if (ModUtil::apiFunc('Scribite', 'user', 'getEditors', array('editorname' => $args['editor']))) {
         // set some general parameters
         $zBaseUrl = rtrim(System::getBaseUrl(), '/');
         $zikulaThemeBaseURL = "{$zBaseUrl}/themes/" . DataUtil::formatForOS(UserUtil::getTheme());
         $zikulaBaseURI = rtrim(System::getBaseUri(), '/');
         $zikulaBaseURI = ltrim($zikulaBaseURI, '/');
         $zikulaRoot = rtrim($_SERVER['DOCUMENT_ROOT'], '/');
         // prepare view instance
         $view = Zikula_View::getInstance('Scribite');
         $view->setCaching(false);
         $view->assign(ModUtil::getVar('Scribite'));
         $view->assign('modname', $args['modulename']);
         $view->assign('zBaseUrl', $zBaseUrl);
         $view->assign('zikulaBaseURI', $zikulaBaseURI);
         $view->assign('zikulaRoot', $zikulaRoot);
         $view->assign('editor_dir', $args['editor']);
         $view->assign('zlang', ZLanguage::getLanguageCode());
         // check for modules installed providing plugins and load specific javascripts
         if (ModUtil::available('photoshare')) {
             PageUtil::AddVar('javascript', 'modules/photoshare/javascript/findimage.js');
         }
         if (ModUtil::available('mediashare')) {
             PageUtil::AddVar('javascript', 'modules/mediashare/javascript/finditem.js');
         }
         if (ModUtil::available('pagesetter')) {
             PageUtil::AddVar('javascript', 'modules/pagesetter/javascript/findpub.js');
         }
         if (ModUtil::available('folder')) {
             PageUtil::AddVar('javascript', 'modules/folder/javascript/selector.js');
         }
         if (ModUtil::available('MediaAttach')) {
             PageUtil::AddVar('javascript', 'modules/MediaAttach/javascript/finditem.js');
         }
         if (ModUtil::available('Files')) {
             PageUtil::AddVar('javascript', 'modules/Files/javascript/getFiles.js');
         }
         // main switch for choosen editor
         switch ($args['editor']) {
             case 'xinha':
                 // get xinha config if editor is active
                 // get plugins for xinha
                 $xinha_listplugins = ModUtil::getVar('Scribite', 'xinha_activeplugins');
                 if ($xinha_listplugins != '') {
                     $xinha_listplugins = unserialize($xinha_listplugins);
                     /* if (in_array('ExtendedFileManager', $xinha_listplugins)) {
                        $view->assign('EFMConfig', true);
                        } else { */
                     $view->assign('EFMConfig', false);
                     //}
                     $xinha_listplugins = '\'' . DataUtil::formatForDisplay(implode('\', \'', $xinha_listplugins)) . '\'';
                 }
                 // prepare areas for xinha
                 if ($args['areas'][0] == "all") {
                     $modareas = 'all';
                 } elseif ($args['areas'][0] == "PagEd") {
                     $modareas = 'PagEd';
                 } else {
                     $modareas = '\'' . DataUtil::formatForDisplay(implode('\', \'', $args['areas'])) . '\'';
                 }
                 // load Prototype
                 PageUtil::AddVar('javascript', 'prototype');
                 // set parameters
                 $view->assign('modareas', $modareas);
                 $view->assign('xinha_listplugins', $xinha_listplugins);
                 // end xinha
                 break;
                 // openwysiwyg deprecated @4.3.0
                 //                case 'openwysiwyg':
                 //                    // get openwysiwyg config if editor is active
                 //                    // prepare areas for openwysiwyg
                 //                    if ($args['areas'][0] == "all") {
                 //                        $modareas = 'all';
                 //                    } else {
                 //                        $modareas = $args['areas'];
                 //                    }
                 //
                 //                    // set parameters
                 //                    $view->assign('modareas', $modareas);
                 //
                 //                    // end openwysiwyg
                 //                    break;
             // openwysiwyg deprecated @4.3.0
             //                case 'openwysiwyg':
             //                    // get openwysiwyg config if editor is active
             //                    // prepare areas for openwysiwyg
             //                    if ($args['areas'][0] == "all") {
             //                        $modareas = 'all';
             //                    } else {
             //                        $modareas = $args['areas'];
             //                    }
             //
             //                    // set parameters
             //                    $view->assign('modareas', $modareas);
             //
             //                    // end openwysiwyg
             //                    break;
             case 'nicedit':
                 // get nicEditor config if editor is active
                 // prepare areas for nicEditor
                 if ($args['areas'][0] == "all") {
                     $modareas = 'all';
                 } else {
                     $modareas = $args['areas'];
                 }
                 // set parameters
                 $view->assign('modareas', $modareas);
                 // end nicEditor
                 break;
             case 'yui':
                 // set body class for YUI Editor
                 PageUtil::SetVar('body', 'class="yui-skin-sam"');
                 // get YUI mode from config
                 $yui_type = ModUtil::getVar('Scribite', 'yui_type');
                 // type switch
                 if ($yui_type == 'Simple') {
                     // load scripts for YUI simple mode
                     PageUtil::AddVar('stylesheet', 'http://yui.yahooapis.com/2.9.0/build/assets/skins/sam/skin.css');
                     PageUtil::AddVar('javascript', 'http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js');
                     PageUtil::AddVar('javascript', 'http://yui.yahooapis.com/2.9.0/build/element/element-min.js');
                     PageUtil::AddVar('javascript', 'http://yui.yahooapis.com/2.9.0/build/container/container_core-min.js');
                     PageUtil::AddVar('javascript', 'http://yui.yahooapis.com/2.9.0/build/editor/simpleeditor-min.js');
                 } else {
                     // load scripts for YUI Editor full mode
                     PageUtil::AddVar('stylesheet', 'http://yui.yahooapis.com/2.9.0/build/assets/skins/sam/skin.css');
                     PageUtil::AddVar('javascript', 'http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js');
                     PageUtil::AddVar('javascript', 'http://yui.yahooapis.com/2.9.0/build/element/element-min.js');
                     PageUtil::AddVar('javascript', 'http://yui.yahooapis.com/2.9.0/build/container/container_core-min.js');
                     PageUtil::AddVar('javascript', 'http://yui.yahooapis.com/2.9.0/build/menu/menu-min.js');
                     PageUtil::AddVar('javascript', 'http://yui.yahooapis.com/2.9.0/build/button/button-min.js');
                     PageUtil::AddVar('javascript', 'http://yui.yahooapis.com/2.9.0/build/editor/editor-min.js');
                 }
                 // prepare areas for YUI
                 if ($args['areas'][0] == "all") {
                     $modareas = 'all';
                 } else {
                     $modareas = $args['areas'];
                 }
                 // set parameters
                 $view->assign('modareas', $modareas);
                 // end yui
                 break;
             case 'ckeditor':
                 // get CKEditor config if editor is active
                 // prepare areas
                 if ($args['areas'][0] == "all") {
                     $modareas = 'all';
                 } else {
                     $modareas = $args['areas'];
                 }
                 // check for allowed html
                 $AllowableHTML = System::getVar('AllowableHTML');
                 $disallowedhtml = array();
                 while (list($key, $access) = each($AllowableHTML)) {
                     if ($access == 0) {
                         $disallowedhtml[] = DataUtil::formatForDisplay($key);
                     }
                 }
                 // load Prototype
                 PageUtil::AddVar('javascript', 'javascript/ajax/prototype.js');
                 // set parameters
                 $view->assign('modareas', $modareas);
                 $view->assign('disallowedhtml', $disallowedhtml);
                 // end ckeditor
                 break;
             case 'markitup':
                 // get markitup config if editor is active
                 // prepare areas
                 if ($args['areas'][0] == "all") {
                     $modareas = 'all';
                 } else {
                     $modareas = $args['areas'];
                 }
                 // check for allowed html
                 $AllowableHTML = System::getVar('AllowableHTML');
                 $disallowedhtml = array();
                 while (list($key, $access) = each($AllowableHTML)) {
                     if ($access == 0) {
                         $disallowedhtml[] = DataUtil::formatForDisplay($key);
                     }
                 }
                 // set parameters
                 $view->assign('modareas', $modareas);
                 $view->assign('disallowedhtml', $disallowedhtml);
                 // end markitup
                 break;
             case 'tiny_mce':
                 // get TinyMCE config if editor is active
                 // get plugins for tiny_mce
                 $tinymce_listplugins = ModUtil::getVar('Scribite', 'tinymce_activeplugins');
                 if ($tinymce_listplugins != '') {
                     $tinymce_listplugins = unserialize($tinymce_listplugins);
                     $tinymce_listplugins = DataUtil::formatForDisplay(implode(',', $tinymce_listplugins));
                 }
                 // prepare areas for tiny_mce
                 if ($args['areas'][0] == "all") {
                     $modareas = 'all';
                 } elseif ($args['areas'][0] == "PagEd") {
                     $modareas = 'PagEd';
                 } else {
                     $modareas = DataUtil::formatForDisplay(implode(',', $args['areas']));
                 }
                 // check for allowed html
                 $AllowableHTML = System::getVar('AllowableHTML');
                 $disallowedhtml = array();
                 while (list($key, $access) = each($AllowableHTML)) {
                     if ($access == 0) {
                         $disallowedhtml[] = DataUtil::formatForDisplay($key);
                     }
                 }
                 // pass disallowed html
                 $disallowedhtml = implode(',', $disallowedhtml);
                 // set parameters
                 $view->assign('modareas', $modareas);
                 $view->assign('tinymce_listplugins', $tinymce_listplugins);
                 $view->assign('disallowedhtml', $disallowedhtml);
                 // end tiny_mce
                 break;
         }
         // view output
         // 1. check if special template is required (from direct module call)
         if (isset($args['tpl']) && $view->template_exists($args['tpl'])) {
             $templatefile = $args['tpl'];
             // 2. check if a module specific template exists
         } elseif ($view->template_exists('editorheaders/' . $args['editor'] . '_' . $args['modulename'] . '.tpl')) {
             $templatefile = 'editorheaders/' . $args['editor'] . '_' . $args['modulename'] . '.tpl';
             // 3. if none of the above load default template
         } else {
             $templatefile = 'editorheaders/' . $args['editor'] . '.tpl';
         }
         $output = $view->fetch($templatefile);
         // end main switch
         return $output;
     }
 }
Example #19
0
 /**
  * Normalizes the current page parameters.
  *
  * Used on the page cache_id and the pageassignments keys.
  *
  * @return string Custom arguments string.
  */
 private function _get_customargs()
 {
     static $customargs;
     if (isset($customargs)) {
         return $customargs;
     }
     // parse the query string into individual arguments discarding common arguments
     // common arguments are ones that we don't want affecting our url matching or ones that are
     // already considered; These are same args defined as reserved by the MDG.
     $customargs = '';
     if ($this->pagetype != 'admin' && System::getVar('shorturls')) {
         // remove the base URI and the entrypoint from the request URI
         $customargs = str_replace(System::getBaseUri(), '', $this->requesturi);
         $entrypoint = System::getVar('entrypoint');
         $customargs = str_replace("/{$entrypoint}/", '/', $customargs);
         $customargs = $customargs == '/' ? '' : $customargs;
     } else {
         $queryparts = explode('&', $this->qstring);
         foreach ($queryparts as $querypart) {
             if (!stristr($querypart, 'module=') && !stristr($querypart, 'type=') && !stristr($querypart, 'func=') && !stristr($querypart, 'theme=') && !stristr($querypart, 'authid=') && !stristr($querypart, 'csrftoken=')) {
                 $customargs .= '/' . $querypart;
             }
         }
     }
     return $customargs;
 }
Example #20
0
/**
 * Install controller.
 *
 * @return void
 */
function install(Core $core)
{
    define('_ZINSTALLVER', Core::VERSION_NUM);
    $serviceManager = $core->getContainer();
    $eventManager = $core->getDispatcher();
    // Lazy load DB connection to avoid testing DSNs that are not yet valid (e.g. no DB created yet)
    $dbEvent = new GenericEvent(null, array('lazy' => true));
    $eventManager->dispatch('doctrine.init_connection', $dbEvent);
    $core->init(Core::STAGE_ALL & ~Core::STAGE_THEME & ~Core::STAGE_MODS & ~Core::STAGE_LANGS & ~Core::STAGE_DECODEURLS & ~Core::STAGE_SESSIONS);
    // Power users might have moved the temp folder out of the root and changed the config.php
    // accordingly. Make sure we respect this security related settings
    $tempDir = isset($GLOBALS['ZConfig']['System']['temp']) ? $GLOBALS['ZConfig']['System']['temp'] : 'ztemp';
    // define our smarty object
    $smarty = new Smarty();
    $smarty->caching = false;
    $smarty->compile_check = true;
    $smarty->left_delimiter = '{';
    $smarty->right_delimiter = '}';
    $smarty->compile_dir = $tempDir . '/view_compiled';
    $smarty->template_dir = 'install/templates';
    $smarty->plugins_dir = array('plugins', 'install/templates/plugins');
    $smarty->clear_compiled_tpl();
    file_put_contents("{$tempDir}/view_compiled/index.html", '');
    $lang = FormUtil::getPassedValue('lang', '', 'GETPOST');
    $dbhost = FormUtil::getPassedValue('dbhost', '', 'GETPOST');
    $dbusername = FormUtil::getPassedValue('dbusername', '', 'GETPOST');
    $dbpassword = FormUtil::getPassedValue('dbpassword', '', 'GETPOST');
    $dbname = FormUtil::getPassedValue('dbname', '', 'GETPOST');
    $dbprefix = '';
    $dbdriver = FormUtil::getPassedValue('dbdriver', '', 'GETPOST');
    $dbtabletype = FormUtil::getPassedValue('dbtabletype', '', 'GETPOST');
    $username = FormUtil::getPassedValue('username', '', 'POST');
    $password = FormUtil::getPassedValue('password', '', 'POST');
    $repeatpassword = FormUtil::getPassedValue('repeatpassword', '', 'POST');
    $email = FormUtil::getPassedValue('email', '', 'GETPOST');
    $action = FormUtil::getPassedValue('action', '', 'GETPOST');
    $notinstalled = isset($_GET['notinstalled']);
    $installedState = isset($GLOBALS['ZConfig']['System']['installed']) ? $GLOBALS['ZConfig']['System']['installed'] : 0;
    // If somehow we are browsing the not installed page but installed, redirect back to homepage
    if ($installedState && $notinstalled) {
        $response = new RedirectResponse(System::getHomepageUrl());
        return $response->send();
    }
    // see if the language was already selected
    $languageAlreadySelected = $lang ? true : false;
    if (!$notinstalled && $languageAlreadySelected && empty($action)) {
        $response = new RedirectResponse(System::getBaseUri() . "/install.php?action=requirements&lang={$lang}");
        return $response->send();
    }
    // see if the language was already selected
    $languageAlreadySelected = $lang ? true : false;
    if (!$notinstalled && $languageAlreadySelected && empty($action)) {
        $response = new RedirectResponse(System::getBaseUri() . "/install.php?action=requirements&lang={$lang}");
        return $response->send();
    }
    // load the installer language files
    if (empty($lang)) {
        if (is_readable('config/installer.ini')) {
            $test = parse_ini_file('config/installer.ini');
            $lang = isset($test['language']) ? $test['language'] : 'en';
        } else {
            $available = ZLanguage::getInstalledLanguages();
            $detector = new ZLanguageBrowser($available);
            $lang = $detector->discover();
        }
        $lang = DataUtil::formatForDisplay($lang);
    }
    // setup multilingual
    $GLOBALS['ZConfig']['System']['language_i18n'] = $lang;
    $GLOBALS['ZConfig']['System']['multilingual'] = true;
    $GLOBALS['ZConfig']['System']['languageurl'] = true;
    $GLOBALS['ZConfig']['System']['language_detect'] = false;
    $serviceManager->loadArguments($GLOBALS['ZConfig']['System']);
    $_lang = ZLanguage::getInstance();
    $_lang->setup();
    $lang = ZLanguage::getLanguageCode();
    $installbySQL = file_exists("install/sql/custom-{$lang}.sql") ? "install/sql/custom-{$lang}.sql" : false;
    $smarty->assign('lang', $lang);
    $smarty->assign('installbySQL', $installbySQL);
    $smarty->assign('langdirection', ZLanguage::getDirection());
    $smarty->assign('charset', ZLanguage::getEncoding());
    // show not installed case
    if ($notinstalled) {
        header('HTTP/1.1 503 Service Unavailable');
        $smarty->display('notinstalled.tpl');
        $smarty->clear_compiled_tpl();
        file_put_contents("{$tempDir}/view_compiled/index.html", '');
        exit;
    }
    // assign the values from config.php
    $smarty->assign($GLOBALS['ZConfig']['System']);
    // if the system is already installed, halt.
    if ($GLOBALS['ZConfig']['System']['installed']) {
        _installer_alreadyinstalled($smarty);
    }
    // check for an empty action - if so then show the first installer page
    if (empty($action)) {
        $action = 'lang';
    }
    // perform tasks based on our action
    switch ($action) {
        case 'processBDInfo':
            $dbname = trim($dbname);
            $dbusername = trim($dbusername);
            if (empty($dbname) || empty($dbusername)) {
                $action = 'dbinformation';
                $smarty->assign('dbconnectmissing', true);
            } elseif (!preg_match('/^[\\w-]*$/', $dbname) || strlen($dbname) > 64) {
                $action = 'dbinformation';
                $smarty->assign('dbinvalidname', true);
            } else {
                update_config_php($dbhost, $dbusername, $dbpassword, $dbname, $dbdriver, $dbtabletype);
                update_installed_status(0);
                try {
                    $dbh = new PDO("{$dbdriver}:host={$dbhost};dbname={$dbname}", $dbusername, $dbpassword);
                } catch (PDOException $e) {
                    $action = 'dbinformation';
                    $smarty->assign('reason', $e->getMessage());
                    $smarty->assign('dbconnectfailed', true);
                }
            }
            if ($action != 'dbinformation') {
                $action = 'createadmin';
            }
            break;
        case 'finish':
            if (!$username || preg_match('/[^\\p{L}\\p{N}_\\.\\-]/u', $username)) {
                $action = 'createadmin';
                $smarty->assign('uservalidatefailed', true);
                $smarty->assign(array('username' => $username, 'password' => $password, 'repeatpassword' => $repeatpassword, 'email' => $email));
            } elseif (mb_strlen($password) < 7) {
                $action = 'createadmin';
                $smarty->assign('badpassword', true);
                $smarty->assign(array('username' => $username, 'password' => $password, 'repeatpassword' => $repeatpassword, 'email' => $email));
            } elseif ($password !== $repeatpassword) {
                $action = 'createadmin';
                $smarty->assign('passwordcomparefailed', true);
                $smarty->assign(array('username' => $username, 'password' => $password, 'repeatpassword' => $repeatpassword, 'email' => $email));
            } elseif (!validateMail($email)) {
                $action = 'createadmin';
                $smarty->assign('emailvalidatefailed', true);
                $smarty->assign(array('username' => $username, 'password' => $password, 'repeatpassword' => $repeatpassword, 'email' => $email));
            } else {
                $installedOk = false;
                // if it is the distribution and the process have not failed in a previous step
                if ($installbySQL) {
                    // checks if exists a previous installation with the same prefix
                    $proceed = true;
                    $dbnameConfig = $GLOBALS['ZConfig']['DBInfo']['databases']['default']['dbname'];
                    $exec = $dbdriver == 'mysql' || $dbdriver == 'mysqli' ? "SHOW TABLES FROM `{$dbnameConfig}` LIKE '%'" : "SHOW TABLES FROM {$dbnameConfig} LIKE '%'";
                    $tables = DBUtil::executeSQL($exec);
                    if ($tables->rowCount() > 0) {
                        $proceed = false;
                        $action = 'dbinformation';
                        $smarty->assign('dbexists', true);
                    }
                    if ($proceed) {
                        // checks if file exists
                        if (!file_exists($installbySQL)) {
                            $action = 'dbinformation';
                            $smarty->assign('dbdumpfailed', true);
                        } else {
                            // execute the SQL dump
                            $lines = file($installbySQL);
                            $exec = '';
                            foreach ($lines as $line_num => $line) {
                                $line = trim($line);
                                if (empty($line) || strpos($line, '--') === 0) {
                                    continue;
                                }
                                $exec .= $line;
                                if (strrpos($line, ';') === strlen($line) - 1) {
                                    if (!DBUtil::executeSQL($exec)) {
                                        $action = 'dbinformation';
                                        $smarty->assign('dbdumpfailed', true);
                                        break;
                                    }
                                    $exec = '';
                                }
                            }
                            ModUtil::dbInfoLoad('Users', 'Users');
                            ModUtil::dbInfoLoad('Extensions', 'Extensions');
                            ModUtil::initCoreVars(true);
                            createuser($username, $password, $email);
                            $installedOk = true;
                        }
                    }
                } else {
                    installmodules($lang);
                    createuser($username, $password, $email);
                    $installedOk = true;
                }
                if ($installedOk) {
                    // create our new site admin
                    // TODO: Email username/password to administrator email address.  Cannot use ModUtil::apiFunc for this.
                    $serviceManager->get('session')->start();
                    $authenticationInfo = array('login_id' => $username, 'pass' => $password);
                    $authenticationMethod = array('modname' => 'Users', 'method' => 'uname');
                    UserUtil::loginUsing($authenticationMethod, $authenticationInfo);
                    // add admin email as site email
                    System::setVar('adminmail', $email);
                    if (!$installbySQL) {
                        Theme_Util::regenerate();
                    }
                    // set site status as installed and protect config.php file
                    update_installed_status(1);
                    @chmod('config/config.php', 0400);
                    if (!is_readable('config/config.php')) {
                        @chmod('config/config.php', 0440);
                        if (!is_readable('config/config.php')) {
                            @chmod('config/config.php', 0444);
                        }
                    }
                    // install all plugins
                    $systemPlugins = PluginUtil::loadAllSystemPlugins();
                    foreach ($systemPlugins as $plugin) {
                        PluginUtil::install($plugin);
                    }
                    LogUtil::registerStatus(__('Congratulations! Zikula has been successfullly installed.'));
                    $response = new RedirectResponse(ModUtil::url('Admin', 'admin', 'adminpanel'));
                    $response->send();
                    exit;
                }
            }
            break;
        case 'requirements':
            $checks = _check_requirements();
            $ok = true;
            foreach ($checks as $check) {
                if (!$check) {
                    $ok = false;
                    break;
                }
            }
            foreach ($checks['files'] as $check) {
                if (!$check['writable']) {
                    $ok = false;
                    break;
                }
            }
            if ($ok) {
                $response = new RedirectResponse(System::getBaseUri() . "/install.php?action=dbinformation&lang={$lang}");
                $response->send();
                exit;
            }
            $smarty->assign('checks', $checks);
            break;
    }
    // check our action template exists
    $action = DataUtil::formatForOS($action);
    if ($smarty->template_exists("installer_{$action}.tpl")) {
        $smarty->assign('action', $action);
        $templateName = "installer_{$action}.tpl";
    } else {
        $smarty->assign('action', 'error');
        $templateName = 'installer_error.tpl';
    }
    $smarty->assign('maincontent', $smarty->fetch($templateName));
    $smarty->display('installer_page.tpl');
    $smarty->clear_compiled_tpl();
    file_put_contents("{$tempDir}/view_compiled/index.html", '');
}
Example #21
0
    /**
     * Returns the HTML code for this debug toolbar.
     * 
     * @return string
     */
    public function asHTML()
    {
        $links         = array();
        $panelContents = array();

        // generate HTML Code for all panels
        foreach ($this->_panels as $name => $panel) {
            $title = $panel->getTitle();

            // ignore panels without a title
            if ($title) {
                $content = $panel->getPanelContent();

                if ($content) {
                    // show title with a link to the content
                    $id = 'DebugToolbarPanel'.$name.'Content';
                    $links[]         = '<li title="'.$panel->getPanelTitle().'" class="'.$name.'"><a href="#" onclick="defaultZikulaDebugToolbar.toggleContentForPanel(\''.$id.'\');return false;">'.$title.'</a></li>';
                    $panelContents[] = '<div id="'.$id.'" class="DebugToolbarPanel" style="display:none;"><h1>'.$panel->getPanelTitle().'</h1>'.$panel->getPanelContent().'</div>';
                } else {
                    // show title without a link
                    $links[] = '<li title="'.$panel->getPanelTitle().'" class="'.$name.'">'.$title.'</li>';
                }
            }
        }

        // generate final html code
        return '<div id="DebugToolbarContainer">
                    <div id="DebugToolbar">
                        <a href="#" onclick="defaultZikulaDebugToolbar.toggleBar(); return false;"><img src="'.System::getBaseUri().'/images/logo_small.png" alt="Debug toolbar" /></a>

                        <ul id="DebugToolbarLinks">
                            '.implode(' ', $links).'
                            <li class="last">
                                <a href="#" onclick="$(\'DebugToolbarContainer\').hide(); return false;">X</a>
                            </li>
                        </ul>
                    </div>

                    '.implode(' ', $panelContents).'
                </div>';
    }
Example #22
0
 /**
  * Constructor.
  *
  * @param array $config Config array.
  */
 public function __construct(array $config = array())
 {
     $this->config = array('objid' => 'id', 'customJSClass' => '', 'nestedSet' => false, 'renderRoot' => true, 'id' => 'zikulatree', 'treeClass' => 'tree', 'nodePrefix' => 'node_', 'nullParent' => 0, 'sortable' => false, 'withWraper' => true, 'wraperClass' => 'treewraper', 'cssFile' => System::getBaseUri() . '/javascript/helpers/Tree/Tree.css', 'item' => 'filenew.png', 'toggler' => 'z-tree-toggle', 'icon' => 'z-tree-icon', 'nodeUnactive' => 'z-tree-unactive', 'nodeSingle' => 'z-tree-single', 'nodeFirst' => 'z-tree-first', 'nodeLast' => 'z-tree-last', 'nodeParent' => 'z-tree-parent', 'nodeLeaf' => 'z-tree-leaf', 'fixedParent' => 'z-tree-fixedparent', 'imagesDir' => System::getBaseUri() . '/javascript/helpers/Tree/', 'plus' => 'plus.gif', 'minus' => 'minus.gif', 'parent' => 'folder.png', 'parentOpen' => 'folder_open.png');
     $this->setOptionArray($config);
 }
Example #23
0
 /**
  * Get the base directory for a module.
  *
  * Example: If the webroot is located at
  * /var/www/html
  * and the module name is Template and is found
  * in the modules directory then this function
  * would return /var/www/html/modules/Template
  *
  * If the Template module was located in the system
  * directory then this function would return
  * /var/www/html/system/Template
  *
  * This allows you to say:
  * include(ModUtil::getBaseDir() . '/includes/private_functions.php');.
  *
  * @param string $modname Name of module to that you want the base directory of.
  *
  * @return string The path from the root directory to the specified module.
  */
 public static function getBaseDir($modname = '')
 {
     if (empty($modname)) {
         $modname = self::getName();
     }
     $path = System::getBaseUri();
     $directory = 'system/' . $modname;
     if ($path != '') {
         $path .= '/';
     }
     $url = $path . $directory;
     if (!is_dir($url)) {
         $directory = 'modules/' . $modname;
         $url = $path . $directory;
     }
     return $url;
 }
Example #24
0
/**
 * get base URI for Zikula
 *
 * @deprecated Deprecated since version 1.3.0.
 * @see System::getBaseUri()
 *
 * @return string base URI for Zikula
 */
function pnGetBaseURI()
{
    LogUtil::log(__f('Warning! Function %1$s is deprecated. Please use %2$s instead.', array(__FUNCTION__, 'System::getBaseUri')), E_USER_DEPRECATED);
    return System::getBaseUri();
}
Example #25
0
 /**
  * Filter the Response to add page assets and vars and return.
  * @param Response $response
  * @return Response
  */
 private function filter(Response $response)
 {
     // @todo START legacy block - remove at Core-2.0
     $baseUri = \System::getBaseUri();
     $jsAssets = [];
     $javascripts = \JCSSUtil::prepareJavascripts(\PageUtil::getVar('javascript'));
     $i = 60;
     $legacyAjaxScripts = 0;
     foreach ($javascripts as $javascript) {
         $javascript = !empty($baseUri) && false === strpos($javascript, $baseUri) ? "{$baseUri}/{$javascript}" : "{$javascript}";
         $javascript = $javascript[0] == '/' ? $javascript : "/{$javascript}";
         // add slash to start if not present.
         // Add legacy ajax scripts (like prototype/scriptaculous) at the lightest weight (0) and in order from there.
         // Add others after core default assets (like jQuery) but before pageAddAsset default weight (100) and in order from there.
         $jsAssets[$javascript] = false !== strpos($javascript, 'javascript/ajax/') ? $legacyAjaxScripts++ : $i++;
     }
     $cssAssets = [];
     $stylesheets = \PageUtil::getVar('stylesheet');
     $i = 60;
     foreach ($stylesheets as $stylesheet) {
         $stylesheet = $baseUri . '/' . $stylesheet;
         $cssAssets[$stylesheet] = $i++;
         // add before pageAddAsset default weight (100)
     }
     // @todo END legacy block - remove at Core-2.0
     $filteredContent = $this->filterService->filter($response->getContent(), $jsAssets, $cssAssets);
     $response->setContent($filteredContent);
     return $response;
 }
Example #26
0
 /**
  * Constructor.
  *
  * @param Zikula_ServiceManager $serviceManager ServiceManager.
  * @param string                $moduleName     Module name ("zikula" for system plugins).
  * @param integer|null          $caching        Whether or not to cache (Zikula_View::CACHE_*) or use config variable (null).
  */
 public function __construct(Zikula_ServiceManager $serviceManager, $moduleName = '', $caching = null)
 {
     $this->serviceManager = $serviceManager;
     $this->eventManager = $this->serviceManager->get('event_dispatcher');
     $this->request = \ServiceUtil::get('request');
     // set the error reporting level
     $this->error_reporting = isset($GLOBALS['ZConfig']['Debug']['error_reporting']) ? $GLOBALS['ZConfig']['Debug']['error_reporting'] : E_ALL;
     $this->error_reporting &= ~E_USER_DEPRECATED;
     $this->allow_php_tag = true;
     // get variables from input
     $module = FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $type = FormUtil::getPassedValue('type', 'user', 'GETPOST', FILTER_SANITIZE_STRING);
     $func = FormUtil::getPassedValue('func', 'main', 'GETPOST', FILTER_SANITIZE_STRING);
     // set vars based on the module structures
     $this->homepage = PageUtil::isHomepage();
     $this->type = strtolower(!$this->homepage ? $type : System::getVar('starttype'));
     $this->func = strtolower(!$this->homepage ? $func : System::getVar('startfunc'));
     // Initialize the module property with the name of
     // the topmost module. For Hooks, Blocks, API Functions and others
     // you need to set this property to the name of the respective module!
     $this->toplevelmodule = ModUtil::getName();
     if (!$moduleName) {
         $moduleName = $this->toplevelmodule;
     }
     $this->modinfo = ModUtil::getInfoFromName($moduleName);
     $this->module = array($moduleName => $this->modinfo);
     // initialise environment vars
     $this->language = ZLanguage::getLanguageCode();
     $this->baseurl = System::getBaseUrl();
     $this->baseuri = System::getBaseUri();
     // system info
     $this->themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));
     $this->theme = $theme = $this->themeinfo['directory'];
     $themeBundle = ThemeUtil::getTheme($this->themeinfo['name']);
     //---- Plugins handling -----------------------------------------------
     // add plugin paths
     switch ($this->modinfo['type']) {
         case ModUtil::TYPE_MODULE:
             $mpluginPathNew = "modules/" . $this->modinfo['directory'] . "/Resources/views/plugins";
             $mpluginPath = "modules/" . $this->modinfo['directory'] . "/templates/plugins";
             break;
         case ModUtil::TYPE_SYSTEM:
             $mpluginPathNew = "system/" . $this->modinfo['directory'] . "/Resources/views/plugins";
             $mpluginPath = "system/" . $this->modinfo['directory'] . "/templates/plugins";
             break;
         default:
             $mpluginPathNew = "system/" . $this->modinfo['directory'] . "/Resources/views/plugins";
             $mpluginPath = "system/" . $this->modinfo['directory'] . "/templates/plugins";
     }
     // add standard plugin search path
     $this->plugins_dir = array();
     $this->addPluginDir('config/plugins');
     // Official override
     $this->addPluginDir('lib/legacy/viewplugins');
     // Core plugins
     $this->addPluginDir(isset($themeBundle) ? $themeBundle->getRelativePath() . '/plugins' : "themes/{$theme}/plugins");
     // Theme plugins
     $this->addPluginDir('plugins');
     // Smarty core plugins
     $this->addPluginDir($mpluginPathNew);
     // Plugins for current module
     $this->addPluginDir($mpluginPath);
     // Plugins for current module
     // check if the 'type' parameter in the URL is admin or adminplugin
     $legacyControllerType = FormUtil::getPassedValue('lct', 'user', 'GETPOST', FILTER_SANITIZE_STRING);
     if ($type === 'admin' || $type === 'adminplugin' || $legacyControllerType === 'admin') {
         // include plugins of the Admin module to the plugins_dir array
         if (!$this instanceof Zikula_View_Theme) {
             $this->addPluginDir('system/AdminModule/Resources/views/plugins');
         } else {
             $this->load_filter('output', 'admintitle');
         }
     }
     // theme plugins module overrides
     $themePluginsPath = isset($themeBundle) ? $themeBundle->getRelativePath() . '/modules/$moduleName/plugins' : "themes/{$theme}/templates/modules/{$moduleName}/plugins";
     $this->addPluginDir($themePluginsPath);
     //---- Cache handling -------------------------------------------------
     if ($caching && in_array((int) $caching, array(0, 1, 2))) {
         $this->caching = (int) $caching;
     } else {
         $this->caching = (int) ModUtil::getVar('ZikulaThemeModule', 'render_cache');
     }
     $this->compile_id = '';
     $this->cache_id = '';
     // template compilation
     $this->compile_dir = CacheUtil::getLocalDir('view_compiled');
     $this->compile_check = ModUtil::getVar('ZikulaThemeModule', 'render_compile_check');
     $this->force_compile = ModUtil::getVar('ZikulaThemeModule', 'render_force_compile');
     // template caching
     $this->cache_dir = CacheUtil::getLocalDir('view_cache');
     $this->cache_lifetime = ModUtil::getVar('ZikulaThemeModule', 'render_lifetime');
     $this->expose_template = ModUtil::getVar('ZikulaThemeModule', 'render_expose_template') == true ? true : false;
     // register resource type 'z' this defines the way templates are searched
     // during {include file='my_template.tpl'} this enables us to store selected module
     // templates in the theme while others can be kept in the module itself.
     $this->register_resource('z', array('Zikula_View_Resource', 'z_get_template', 'z_get_timestamp', 'z_get_secure', 'z_get_trusted'));
     // set 'z' as default resource type
     $this->default_resource_type = 'z';
     // process some plugins specially when Render cache is enabled
     if (!$this instanceof Zikula_View_Theme && $this->caching) {
         $this->register_nocache_plugins();
     }
     // register the 'nocache' block to allow dynamic zones caching templates
     $this->register_block('nocache', array('Zikula_View_Resource', 'block_nocache'), false);
     // For ajax requests we use the short urls filter to 'fix' relative paths
     if ($this->serviceManager->get('zikula')->getStage() & Zikula_Core::STAGE_AJAX && System::getVar('shorturls')) {
         $this->load_filter('output', 'shorturls');
     }
     // register prefilters
     $this->register_prefilter('z_prefilter_add_literal');
     $this->register_prefilter('z_prefilter_gettext_params');
     //$this->register_prefilter('z_prefilter_notifyfilters');
     // assign some useful settings
     $this->assign('homepage', $this->homepage)->assign('modinfo', $this->modinfo)->assign('module', $moduleName)->assign('toplevelmodule', $this->toplevelmodule)->assign('type', $this->type)->assign('func', $this->func)->assign('lang', $this->language)->assign('themeinfo', $this->themeinfo)->assign('themepath', isset($themeBundle) ? $themeBundle->getRelativePath() : $this->baseurl . 'themes/' . $theme)->assign('baseurl', $this->baseurl)->assign('baseuri', $this->baseuri)->assign('moduleBundle', ModUtil::getModule($moduleName))->assign('themeBundle', $themeBundle);
     if (isset($themeBundle)) {
         $stylePath = $themeBundle->getRelativePath() . "/Resources/public/css";
         $javascriptPath = $themeBundle->getRelativePath() . "/Resources/public/js";
         $imagePath = $themeBundle->getRelativePath() . "/Resources/public/images";
         $imageLangPath = $themeBundle->getRelativePath() . "/Resources/public/images/" . $this->language;
     } else {
         $stylePath = $this->baseurl . "themes/{$theme}/style";
         $javascriptPath = $this->baseurl . "themes/{$theme}/javascript";
         $imagePath = $this->baseurl . "themes/{$theme}/images";
         $imageLangPath = $this->baseurl . "themes/{$theme}/images/" . $this->language;
     }
     $this->assign('stylepath', $stylePath)->assign('scriptpath', $javascriptPath)->assign('imagepath', $imagePath)->assign('imagelangpath', $imageLangPath);
     // for {gt} template plugin to detect gettext domain
     if ($this->modinfo['type'] == ModUtil::TYPE_MODULE) {
         $this->domain = ZLanguage::getModuleDomain($this->modinfo['name']);
     }
     // make render object available to modifiers
     parent::assign('zikula_view', $this);
     // add ServiceManager, EventManager and others to all templates
     parent::assign('serviceManager', $this->serviceManager);
     parent::assign('eventManager', $this->eventManager);
     parent::assign('zikula_core', $this->serviceManager->get('zikula'));
     parent::assign('request', $this->request);
     $modvars = ModUtil::getModvars();
     // Get all modvars from any modules that have accessed their modvars at least once.
     // provide compatibility 'alias' array keys
     // @todo remove after v1.4.0
     if (isset($modvars['ZikulaAdminModule'])) {
         $modvars['Admin'] = $modvars['ZikulaAdminModule'];
     }
     if (isset($modvars['ZikulaBlocksModule'])) {
         $modvars['Blocks'] = $modvars['ZikulaBlocksModule'];
     }
     if (isset($modvars['ZikulaCategoriesModule'])) {
         $modvars['Categories'] = $modvars['ZikulaCategoriesModule'];
     }
     if (isset($modvars['ZikulaExtensionsModule'])) {
         $modvars['Extensions'] = $modvars['ZikulaExtensionsModule'];
     }
     if (isset($modvars['ZikulaGroupsModule'])) {
         $modvars['Groups'] = $modvars['ZikulaGroupsModule'];
     }
     if (isset($modvars['ZikulaMailerModule'])) {
         $modvars['Mailer'] = $modvars['ZikulaMailerModule'];
     }
     if (isset($modvars['ZikulaPageLockModule'])) {
         $modvars['PageLock'] = $modvars['ZikulaPageLockModule'];
     }
     if (isset($modvars['ZikulaPermissionsModule'])) {
         $modvars['Permissions'] = $modvars['ZikulaPermissionsModule'];
     }
     if (isset($modvars['ZikulaSearchModule'])) {
         $modvars['Search'] = $modvars['ZikulaSearchModule'];
     }
     if (isset($modvars['ZikulaSecurityCenterModule'])) {
         $modvars['SecurityCenter'] = $modvars['ZikulaSecurityCenterModule'];
     }
     if (isset($modvars['ZikulaSettingsModule'])) {
         $modvars['Settings'] = $modvars['ZikulaSettingsModule'];
     }
     if (isset($modvars['ZikulaThemeModule'])) {
         $modvars['Theme'] = $modvars['ZikulaThemeModule'];
     }
     if (isset($modvars['ZikulaUsersModule'])) {
         $modvars['Users'] = $modvars['ZikulaUsersModule'];
     }
     // end compatibility aliases
     parent::assign('modvars', $modvars);
     $this->add_core_data();
     // metadata for SEO
     if (!$this->serviceManager->hasParameter('zikula_view.metatags')) {
         $this->serviceManager->setParameter('zikula_view.metatags', new ArrayObject(array()));
     }
     parent::assign('metatags', $this->serviceManager->getParameter('zikula_view.metatags'));
     if (isset($themeBundle) && $themeBundle->isTwigBased()) {
         // correct asset urls when smarty output is wrapped by twig theme
         $this->load_filter('output', 'asseturls');
     }
     $event = new \Zikula\Core\Event\GenericEvent($this);
     $this->eventManager->dispatch('view.init', $event);
 }
Example #27
0
 /**
  * display block
  *
  * @param        array       $blockinfo     a blockinfo structure
  * @return       output      the rendered bock
  */
 public function display($blockinfo)
 {
     // security check
     if (!SecurityUtil::checkPermission('ExtendedMenublock::', $blockinfo['bid'] . '::', ACCESS_READ)) {
         return;
     }
     // Break out options from our content field
     $vars = BlockUtil::varsFromContent($blockinfo['content']);
     // template to use
     if (empty($vars['template'])) {
         $vars['template'] = 'blocks_block_extmenu.tpl';
     }
     // stylesheet to use
     if (empty($vars['stylesheet'])) {
         $vars['stylesheet'] = 'extmenu.css';
     }
     // add the stylesheet to the header
     PageUtil::addVar('stylesheet', ThemeUtil::getModuleStylesheet('Blocks', $vars['stylesheet']));
     // if cache is enabled, checks for a cached output
     if ($this->view->getCaching()) {
         // set the cache id
         $this->view->setCacheId($blockinfo['bkey'] . '/bid' . $blockinfo['bid'] . '/' . UserUtil::getGidCacheString());
         // check out if the contents are cached
         if ($this->view->is_cached($vars['template'])) {
             $blockinfo['content'] = $this->view->fetch($vars['template']);
             return BlockUtil::themeBlock($blockinfo);
         }
     }
     // create default block variables
     if (!isset($vars['blocktitles'])) {
         $vars['blocktitles'] = array();
     }
     if (!isset($vars['links'])) {
         $vars['links'] = array();
     }
     if (!isset($vars['stylesheet'])) {
         $vars['stylesheet'] = '';
     }
     if (!isset($vars['menuid'])) {
         $vars['menuid'] = 0;
     }
     // get language and default to en
     $thislang = ZLanguage::getLanguageCode();
     if (!array_key_exists($thislang, $vars['links'])) {
         $thislang = 'en';
     }
     // if specific blocktitle for selected language exists, use it
     if (array_key_exists($thislang, $vars['blocktitles']) && !empty($vars['blocktitles'][$thislang])) {
         $blockinfo['title'] = $vars['blocktitles'][$thislang];
     }
     // Content
     $menuitems = array();
     if (!empty($vars['links'][$thislang])) {
         $blocked = array();
         foreach ($vars['links'][$thislang] as $linkid => $link) {
             $link['parentid'] = isset($link['parentid']) ? $link['parentid'] : null;
             $denied = !SecurityUtil::checkPermission('ExtendedMenublock::', $blockinfo['bid'] . ':' . $linkid . ':', ACCESS_READ);
             if ($denied || !is_null($link['parentid']) && in_array($link['parentid'], $blocked)) {
                 $blocked[] = $linkid;
             } elseif (!isset($link['active']) || $link['active'] != '1') {
                 $blocked[] = $linkid;
             } else {
                 // pre zk1.2 check
                 if (!isset($link['id'])) {
                     $link['id'] = $linkid;
                 }
                 $link['url'] = ModUtil::apiFunc('Blocks', 'user', 'encodebracketurl', $link['url']);
                 // check for multiple options in image
                 $this->checkImage($link);
                 $menuitems[] = $link;
             }
         }
     }
     // Modules
     if (!empty($vars['displaymodules'])) {
         $newmods = ModUtil::getUserMods();
         $mods = array();
         foreach ($newmods as $module) {
             if (!preg_match('#(?:error|blocks)#', strtolower($module['name']))) {
                 $mods[] = $module;
             }
         }
         // Separate from current content, if any
         if (count($menuitems) > 0) {
             $menuitems[] = array('name' => '&nbsp;', 'url' => '', 'title' => '', 'level' => 0, 'parentid' => null, 'image' => '');
             if (SecurityUtil::checkPermission('ExtendedMenublock::', $blockinfo['bid'] . '::', ACCESS_ADMIN)) {
                 $menuitems[] = array('name' => $this->__('--Installed modules--'), 'url' => ModUtil::url('Blocks', 'admin', 'modify', array('bid' => $blockinfo['bid'])), 'title' => '', 'level' => 0, 'parentid' => null, 'image' => '');
             }
         }
         foreach ($mods as $mod) {
             // prepare image
             if (SecurityUtil::checkPermission("{$mod['name']}::", '::', ACCESS_OVERVIEW)) {
                 $menuitems[] = array('name' => $mod['displayname'], 'url' => ModUtil::url($mod['name'], 'user', 'main'), 'title' => $mod['description'], 'level' => 0, 'parentid' => null, 'image' => '');
             }
         }
     }
     // check for any empty result set
     if (empty($menuitems)) {
         return;
     }
     $currenturi = urlencode(str_replace(System::getBaseUri() . '/', '', System::getCurrentUri()));
     // assign the items
     $this->view->assign('menuitems', $menuitems)->assign('blockinfo', $blockinfo)->assign('currenturi', $currenturi)->assign('access_edit', Securityutil::checkPermission('ExtendedMenublock::', $blockinfo['bid'] . '::', ACCESS_EDIT));
     // get the block content
     $blockinfo['content'] = $this->view->fetch($vars['template']);
     // pass the block array back to the theme for display
     return BlockUtil::themeBlock($blockinfo);
 }
Example #28
0
 /**
  * Constructor.
  *
  * @param ContainerBuilder $container ServiceManager.
  * @param string           $moduleName     Module name ("zikula" for system plugins).
  * @param integer|null     $caching        Whether or not to cache (Zikula_View::CACHE_*) or use config variable (null).
  */
 public function __construct(ContainerBuilder $container, $moduleName = '', $caching = null)
 {
     $this->container = $container;
     $this->dispatcher = $this->container->get('event_dispatcher');
     $this->request = $this->container->get('request');
     // set the error reporting level
     $this->error_reporting = isset($container['error_reporting']) ? $container['error_reporting'] : E_ALL;
     $this->allow_php_tag = true;
     // get variables from input
     $module = $this->request->attributes->get('_module', null);
     $type = $this->request->attributes->get('_controller', 'user');
     $func = $this->request->attributes->get('_action', 'index');
     // set vars based on the module structures
     $this->homepage = empty($module) ? true : false;
     $this->type = strtolower(!$this->homepage ? $type : System::getVar('starttype'));
     $this->func = strtolower(!$this->homepage ? $func : System::getVar('startfunc'));
     // Initialize the module property with the name of
     // the topmost module. For Hooks, Blocks, API Functions and others
     // you need to set this property to the name of the respective module!
     $this->toplevelmodule = ModUtil::getName();
     if (!$moduleName) {
         $moduleName = $this->toplevelmodule;
     }
     $this->modinfo = ModUtil::getInfoFromName($moduleName);
     $this->module = array($moduleName => $this->modinfo);
     // initialise environment vars
     $this->language = ZLanguage::getLanguageCode();
     $this->baseurl = System::getBaseUrl();
     $this->baseuri = System::getBaseUri();
     // system info
     $this->themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));
     $this->theme = $this->themeinfo['directory'];
     //---- Plugins handling -----------------------------------------------
     // add plugin paths
     switch ($this->modinfo['type']) {
         case ModUtil::TYPE_MODULE:
             $mpluginPath = "modules/" . $this->modinfo['directory'] . "/Resources/views/plugins";
             break;
         case ModUtil::TYPE_SYSTEM:
             $mpluginPath = "system/" . $this->modinfo['directory'] . "/Rsources/views/plugins";
             break;
         default:
             $mpluginPath = "system/" . $this->modinfo['directory'] . "/Rsources/views/plugins";
     }
     // add standard plugin search path
     $this->plugins_dir = array();
     $this->addPluginDir('config/Resources/plugins');
     // Official override
     $this->addPluginDir('config/plugins');
     // Official override
     $this->addPluginDir(ZIKULA_ROOT . '/../src/legacy/viewplugins');
     // Core plugins
     $this->addPluginDir("themes/{$this->theme}/Resources/views/plugins");
     // Theme plugins
     $this->addPluginDir(SMARTY_DIR . 'plugins');
     // Smarty core plugins
     $this->addPluginDir($mpluginPath);
     // Plugins for current module
     // check if the 'type' parameter in the URL is admin and if yes,
     // include system/Admin/templates/plugins to the plugins_dir array
     if ($type === 'admin') {
         if (!$this instanceof Zikula_View_Theme) {
             $this->addPluginDir('system/AdminModule/Resources/views/plugins');
         } else {
             $this->load_filter('output', 'admintitle');
         }
     }
     //---- Cache handling -------------------------------------------------
     if ($caching && in_array((int) $caching, array(0, 1, 2))) {
         $this->caching = (int) $caching;
     } else {
         $this->caching = (int) ModUtil::getVar('Theme', 'render_cache');
     }
     $this->compile_id = '';
     $this->cache_id = '';
     // template compilation
     $this->compile_dir = CacheUtil::getLocalDir('view_compiled');
     $this->compile_check = ModUtil::getVar('Theme', 'render_compile_check');
     $this->force_compile = ModUtil::getVar('Theme', 'render_force_compile');
     // template caching
     $this->cache_dir = CacheUtil::getLocalDir('view_cache');
     $this->cache_lifetime = ModUtil::getVar('Theme', 'render_lifetime');
     $this->expose_template = ModUtil::getVar('Theme', 'render_expose_template') == true ? true : false;
     // register resource type 'z' this defines the way templates are searched
     // during {include file='my_template.tpl'} this enables us to store selected module
     // templates in the theme while others can be kept in the module itself.
     $this->register_resource('z', array('Zikula_View_Resource', 'z_get_template', 'z_get_timestamp', 'z_get_secure', 'z_get_trusted'));
     // set 'z' as default resource type
     $this->default_resource_type = 'z';
     // process some plugins specially when Render cache is enabled
     if (!$this instanceof Zikula_View_Theme && $this->caching) {
         $this->register_nocache_plugins();
     }
     // register the 'nocache' block to allow dynamic zones caching templates
     $this->register_block('nocache', array('Zikula_View_Resource', 'block_nocache'), false);
     // For ajax requests we use the short urls filter to 'fix' relative paths
     if ($this->container->get('zikula')->getStage() & \Zikula\Core\Core::STAGE_AJAX && System::getVar('shorturls')) {
         $this->load_filter('output', 'shorturls');
     }
     // register prefilters
     $this->register_prefilter('z_prefilter_add_literal');
     $this->register_prefilter('z_prefilter_gettext_params');
     // assign some useful settings
     $this->assign('homepage', $this->homepage)->assign('modinfo', $this->modinfo)->assign('module', $moduleName)->assign('toplevelmodule', $this->toplevelmodule)->assign('type', $this->type)->assign('func', $this->func)->assign('lang', $this->language)->assign('themeinfo', $this->themeinfo)->assign('themepath', $this->baseurl . 'themes/' . $this->theme)->assign('baseurl', $this->baseurl)->assign('baseuri', $this->baseuri);
     // for {gt} template plugin to detect gettext domain
     if ($this->modinfo['type'] == ModUtil::TYPE_MODULE) {
         $this->domain = ZLanguage::getModuleDomain($this->modinfo['name']);
     }
     // make render object available to modifiers
     parent::assign('zikula_view', $this);
     // add ServiceManager, EventManager and others to all templates
     parent::assign('container', $this->container);
     parent::assign('dispatcher', $this->dispatcher);
     parent::assign('zikula_core', $this->container->get('zikula'));
     parent::assign('request', $this->request);
     parent::assign('modvars', ModUtil::getModvars());
     // Get all modvars from any modules that have accessed their modvars at least once.
     $this->add_core_data();
     // metadata for SEO
     if (!isset($this->container['zikula_view.metatags'])) {
         $this->container['zikula_view.metatags'] = new ArrayObject(array());
     }
     parent::assign('metatags', $this->container['zikula_view.metatags']);
     $event = new GenericEvent($this);
     $this->dispatcher->dispatch('view.init', $event);
 }
Example #29
0
 /**
  * Returns HTML-Code for an image representing the error type.
  *
  * @param int $type Error type form Zikula_AbstractErrorHandler.
  *
  * @return string HTML
  */
 protected function getImageForErrorType($type)
 {
     switch ($type) {
         case Zikula_AbstractErrorHandler::EMERG:
             return '<img src="' . System::getBaseUri() . '/images/icons/extrasmall/exit.png" alt="" />';
         case Zikula_AbstractErrorHandler::ALERT:
             return '<img src="' . System::getBaseUri() . '/images/icons/extrasmall/error.png" alt="" />';
         case Zikula_AbstractErrorHandler::CRIT:
             return '<img src="' . System::getBaseUri() . '/images/icons/extrasmall/error.png" alt="" />';
         case Zikula_AbstractErrorHandler::ERR:
             return '<img src="' . System::getBaseUri() . '/images/icons/extrasmall/error.png" alt="" />';
         case Zikula_AbstractErrorHandler::WARN:
             return '<img src="' . System::getBaseUri() . '/images/icons/extrasmall/redled.png" alt="" />';
         case Zikula_AbstractErrorHandler::NOTICE:
             return '<img src="' . System::getBaseUri() . '/images/icons/extrasmall/info.png" alt="" />';
         case Zikula_AbstractErrorHandler::INFO:
             return '<img src="' . System::getBaseUri() . '/images/icons/extrasmall/info.png" alt="" />';
         case Zikula_AbstractErrorHandler::DEBUG:
             return '<img src="' . System::getBaseUri() . '/images/icons/extrasmall/text_block.png" alt="" />';
         default:
             return __('Unknown');
     }
 }
Example #30
0
/**
 * 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:
 *   - type:          The type of image to render (example: save)
 *   - size:           The size of the image (extrasmall - small - large - default:extrasmall)
 *   - width, height: If set, they will be passed. If none is set, they are obtained from the 'size' parameter
 *   - alt:           If not set, an empty string is being assigned
 *   - title:         If not set, an empty string is being assigned
 *   - 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)
 *   - all remaining parameters are passed to the image tag
 *
 * Example: {icon type="save" size="extrasmall" __alt="Save"}
 * Output:  <img src="images/icons/extrasmall/save.png" alt="Save" />
 *
 * Example: {icon type="save" width="100" border="1" alt="foobar" }
 * Output:  <img src="images/icons/extrasmall/save.png" width="100" border="1" alt="foobar" />
 *
 * 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:
 * {icon src="heading.png" assign="myvar"}
 * {$myvar.src}
 * {$myvar.width}
 * {$myvar.imgtag}
 *
 * Output:
 * modules/Example/images/eng/heading.png
 * <img src="modules/Example/images/eng/heading.png" 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 The img tag.
 */
function smarty_function_icon($params, Zikula_View $view)
{
    if (!isset($params['type'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('smarty_function_icon', 'type')));
        return false;
    }
    // default for the optional flag
    $optional = isset($params['optional']) ? $params['optional'] : true;
    // always provide an alt attribute.
    // if none is set, assign an empty one.
    $params['alt'] = isset($params['alt']) ? $params['alt'] : '';
    $params['title'] = isset($params['title']) ? $params['title'] : $params['alt'];
    $size = isset($params['size']) ? $params['size'] : 'extrasmall';
    $iconpath = 'images/icons/';
    static $icons;
    // Include icon config file
    if (!isset($icons) && file_exists("{$iconpath}/config.php")) {
        include_once "{$iconpath}/config.php";
    }
    $size = DataUtil::formatForOS($size);
    $imgsrc = '';
    if (isset($icons[$params['type']])) {
        $imgpath = $iconpath . $size . '/' . $icons[$params['type']];
        if (is_readable($imgpath)) {
            $imgsrc = $imgpath;
        }
    }
    if ($imgsrc == '' && isset($params['default'])) {
        $imgsrc = $params['default'];
    }
    if ($imgsrc == '') {
        if (!isset($optional)) {
            $view->trigger_error(__f("%s: Image '%s' not found", array('icon', DataUtil::formatForDisplay($params['type']))));
        }
        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))) {
            $view->trigger_error(__f("%s: Image '%s' is not a valid image file", array('icon', DataUtil::formatForDisplay($params['type']))));
            return false;
        }
        $params['width'] = $_image_data[0];
        $params['height'] = $_image_data[1];
    }
    // unset all parameters which are no html argument from $params
    unset($params['type']);
    $assign = null;
    if (isset($params['assign'])) {
        $assign = $params['assign'];
        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['size']);
    $imgtag = '<img src="' . System::getBaseUri() . '/' . $imgsrc . '" ';
    foreach ($params as $key => $value) {
        $imgtag .= $key . '="' . $value . '" ';
    }
    $imgtag .= ' />';
    if (isset($assign)) {
        $params['src'] = $imgsrc;
        $params['imgtag'] = $imgtag;
        $view->assign($assign, $params);
    } else {
        return $imgtag;
    }
}