/**
 * Smarty function to return first image src from given HTML content.
 *
 * Examples
 *  {getImage htmlcontent=$item.body}
 *  {getImage htmlcontent=$item.body putbaseurl=true}
 *  {getImage htmlcontent=$item.body putbaseurl=true assign='imagesrc'}
 *
 * @return string
 */
function smarty_function_getImage($params, Zikula_View $view)
{
    $result = $params['htmlcontent'];
    if (isset($params['htmlcontent']) && $params['htmlcontent']) {
        if (strpos($params['htmlcontent'], '<img ') === false) {
            // image is not found in content
        } else {
            // get image src
            $posstart = strpos($params['htmlcontent'], ' src="', $posstart) + 6;
            $posend = strpos($params['htmlcontent'], '"', $posstart);
            $result = substr($params['htmlcontent'], $posstart, $posend - $posstart);
            if (isset($params['putbaseurl']) && $params['putbaseurl']) {
                // put base url, if not
                if (substr($result, 0, 7) != 'http://' || substr($result, 0, 8) != 'https://') {
                    $result = System::getBaseUrl() . ltrim($result, DIRECTORY_SEPARATOR);
                }
            }
        }
    }
    if (isset($params['assign'])) {
        $view->assign($params['assign'], $result);
    } else {
        return $result;
    }
}
Example #2
0
 /**
  * transform text to images
  * 
  * @param string $args['text']
  */
 function transform($args)
 {
     $text = $args['text'];
     // check the user agent - if it is a bot, return immediately
     $robotslist = array("ia_archiver", "googlebot", "mediapartners-google", "yahoo!", "msnbot", "jeeves", "lycos");
     $useragent = System::serverGetVar('HTTP_USER_AGENT');
     for ($cnt = 0; $cnt < count($robotslist); $cnt++) {
         if (strpos(strtolower($useragent), $robotslist[$cnt]) !== false) {
             return $text;
         }
     }
     $smilies = $this->getVar('smilie_array');
     $remove_inactive = $this->getVar('remove_inactive');
     if (is_array($smilies) && count($smilies) > 0) {
         // sort smilies, see http://code.zikula.org/BBSmile/ticket/1
         uasort($smilies, array($this, 'cmp_smiliesort'));
         $imagepath = System::getBaseUrl() . DataUtil::formatForOS($this->getVar('smiliepath'));
         $imagepath_auto = System::getBaseUrl() . DataUtil::formatForOS($this->getVar('smiliepath_auto'));
         $auto_active = $this->getVar('activate_auto');
         // pad it with a space so we can distinguish between FALSE and matching the 1st char (index 0).
         // This is important!
         $text = ' ' . $text;
         foreach ($smilies as $smilie) {
             // check if smilie is active
             if ($smilie['active'] == 1) {
                 // check if alt is a define
                 $smilie['alt'] = defined($smilie['alt']) ? constant($smilie['alt']) : $smilie['alt'];
                 if ($smilie['type'] == 0) {
                     $text = str_replace($smilie['short'], ' <img src="' . $imagepath . '/' . $smilie['imgsrc'] . '" alt="' . $smilie['alt'] . '" /> ', $text);
                 } else {
                     if ($auto_active == 1) {
                         $text = str_replace($smilie['short'], ' <img src="' . $imagepath_auto . '/' . $smilie['imgsrc'] . '" alt="' . $smilie['alt'] . '" /> ', $text);
                     }
                 }
                 if (!empty($smilie['alias'])) {
                     $aliases = explode(",", trim($smilie['alias']));
                     if (is_array($aliases) && count($aliases) > 0) {
                         foreach ($aliases as $alias) {
                             if ($smilie['type'] == 0) {
                                 $text = str_replace($alias, ' <img src="' . $imagepath . '/' . $smilie['imgsrc'] . '" alt="' . $smilie['alt'] . '" /> ', $text);
                             } else {
                                 if ($auto_active == 1) {
                                     $text = str_replace($alias, ' <img src="' . $imagepath_auto . '/' . $smilie['imgsrc'] . '" alt="' . $smilie['alt'] . '" /> ', $text);
                                 }
                             }
                         }
                     }
                 }
             } else {
                 // End of if smilie is active
                 $text = str_replace($smilie['short'], '', $text);
             }
         }
         // foreach
         // Remove our padding from the string..
         $text = substr($text, 1);
     }
     // End of if smilies is array and not empty
     return $text;
 }
Example #3
0
/**
 * Smarty function to display footnotes caculated by earlier modifier
 *
 * Example
 *   {footnotes}
 *
 * @param       array       $params      All attributes passed to this function from the template
 * @param       object      $smarty     Reference to the Smarty object
 */
function smarty_function_footnotes($params, $smarty)
{
    // globalise the links array
    global $link_arr;
    $text = '';
    if (is_array($link_arr) && !empty($link_arr)) {
        $text .= '<ol>';
        $link_arr = array_unique($link_arr);
        foreach ($link_arr as $key => $link) {
            // check for an e-mail address
            if (preg_match("/^([a-z0-9_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,4}\$/i", $link)) {
                $linktext = $link;
                $link = 'mailto:' . $link;
                // append base URL for local links (not web links)
            } elseif (!preg_match("/^http:\\/\\//i", $link)) {
                $link = System::getBaseUrl() . $link;
                $linktext = $link;
            } else {
                $linktext = $link;
            }
            $linktext = DataUtil::formatForDisplay($linktext);
            $link = DataUtil::formatForDisplay($link);
            // output link
            $text .= '<li><a class="print-normal" href="' . $link . '">' . $linktext . '</a></li>' . "\n";
        }
        $text .= '</ol>';
    }
    if (isset($params['assign'])) {
        $smarty->assign($params['assign'], $text);
    } else {
        return $text;
    }
}
Example #4
0
 function getPluginData($filtAfterDate = null)
 {
     if (!$this->pluginAvailable()) {
         return array();
     }
     if (!SecurityUtil::checkPermission('ZphpBB2::', '::', ACCESS_READ, $this->userNewsletter)) {
         return array();
     }
     //ModUtil::load('ZphpBB2');
     $table_prefix = ModUtil::getVar('ZphpBB2', 'table_prefix', 'phpbb_');
     $TOPICS_TABLE = $table_prefix . "topics";
     $POSTS_TABLE = $table_prefix . "posts";
     $POSTS_TEXT_TABLE = $table_prefix . "posts_text";
     $FORUMS_TABLE = $table_prefix . "forums";
     $connection = Doctrine_Manager::getInstance()->getCurrentConnection();
     $sql = "SELECT forum_id, forum_name FROM {$FORUMS_TABLE} WHERE auth_view <= 0 AND auth_read <= 0";
     $stmt = $connection->prepare($sql);
     try {
         $stmt->execute();
     } catch (Exception $e) {
         return LogUtil::registerError(__('Error in plugin') . ' ZphpBB2: ' . $e->getMessage());
     }
     $userforums = $stmt->fetchAll(Doctrine_Core::FETCH_ASSOC);
     $allowedforums = array();
     foreach (array_keys($userforums) as $k) {
         if (SecurityUtil::checkPermission('ZphpBB2::', ":" . $userforums[$k]['forum_id'] . ":", ACCESS_READ, $this->userNewsletter)) {
             $allowedforums[] = $userforums[$k]['forum_id'];
         }
     }
     if (count($allowedforums) == 0) {
         // user is not allowed to read any forum at all
         return array();
     }
     $sql = "SELECT {$TOPICS_TABLE}.topic_title, {$TOPICS_TABLE}.topic_replies, {$TOPICS_TABLE}.topic_views, {$TOPICS_TABLE}.topic_id, \n                     {$POSTS_TABLE}.post_id, {$POSTS_TABLE}.poster_id, {$POSTS_TABLE}.post_time, \n                     {$POSTS_TEXT_TABLE}.post_subject, {$POSTS_TEXT_TABLE}.post_text, \n                     {$FORUMS_TABLE}.forum_name \n                     FROM {$TOPICS_TABLE} \n                     INNER JOIN {$POSTS_TABLE} ON {$POSTS_TABLE}.topic_id = {$TOPICS_TABLE}.topic_id \n                     INNER JOIN {$POSTS_TEXT_TABLE} ON {$POSTS_TEXT_TABLE}.post_id = {$POSTS_TABLE}.post_id \n                     INNER JOIN {$FORUMS_TABLE} ON {$FORUMS_TABLE}.forum_id = {$TOPICS_TABLE}.forum_id";
     $sql .= " WHERE {$TOPICS_TABLE}.forum_id IN (" . implode(',', $allowedforums) . ")";
     if ($filtAfterDate) {
         $sql .= " AND FROM_UNIXTIME(post_time)>='" . $filtAfterDate . "'";
     }
     $sql .= " ORDER BY post_time DESC LIMIT " . $this->nItems;
     $stmt = $connection->prepare($sql);
     try {
         $stmt->execute();
     } catch (Exception $e) {
         return LogUtil::registerError(__('Error in plugin') . ' ZphpBB2: ' . $e->getMessage());
     }
     $items = $stmt->fetchAll(Doctrine_Core::FETCH_BOTH);
     foreach (array_keys($items) as $k) {
         $items[$k]['topicurl'] = ModUtil::url('ZphpBB2', 'user', 'viewtopic', array('t' => $items[$k]['topic_id']));
         $items[$k]['posturl'] = ModUtil::url('ZphpBB2', 'user', 'viewtopic', array('p' => $items[$k]['post_id'] . '#' . $items[$k]['post_id']));
         $items[$k]['postdate'] = DateUtil::getDatetime($items[$k]['post_time']);
         $items[$k]['username'] = UserUtil::getVar('uname', $items[$k]['poster_id']);
         $items[$k]['nl_title'] = $items[$k]['topic_title'];
         $items[$k]['nl_url_title'] = System::getBaseUrl() . $items[$k]['posturl'];
         $items[$k]['nl_content'] = $items[$k]['forum_name'] . ', ' . $items[$k]['username'] . "<br />\n" . $items[$k]['post_text'];
         $items[$k]['nl_url_readmore'] = $items[$k]['nl_url_title'];
     }
     return $items;
 }
/**
 * Zikula_View function to display the avatar of a user
 *
 * Available parameters:
 *   - uid            User uid
 *   - width, height  Width and heigt of the image (optional)
 *   - assign         The results are assigned to the corresponding variable instead of printed out (optional).
 * Gravatar parameters
 *   - size           Size of the gravtar (optional)
 *   - rating         Gravatar allows users to self-rate their images so that they can indicate if an image is appropriate for a certain audience.
 *                    [g|pg|r|x] see: http://en.gravatar.com/site/implement/images/ (optional)
 *
 * Examples:
 * {useravatar uid="2"}
 * {useravatar uid="2" width=80 height=80}
 * {useravatar uid="2" size=80 rating=g}
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return string A formatted string containing the avatar image.
 */
function smarty_function_useravatar($params, Zikula_View $view)
{
    if (!isset($params['uid'])) {
        $view->trigger_error("Error! Missing 'uid' attribute for useravatar.");
        return false;
    }
    $email = UserUtil::getVar('email', $params['uid']);
    $avatar = UserUtil::getVar('avatar', $params['uid']);
    $uname = UserUtil::getVar('uname', $params['uid']);
    $avatarpath = ModUtil::getVar(UsersConstant::MODNAME, UsersConstant::MODVAR_AVATAR_IMAGE_PATH, UsersConstant::DEFAULT_AVATAR_IMAGE_PATH);
    $allowgravatars = ModUtil::getVar(UsersConstant::MODNAME, UsersConstant::MODVAR_GRAVATARS_ENABLED, UsersConstant::DEFAULT_GRAVATARS_ENABLED);
    $gravatarimage = ModUtil::getVar(UsersConstant::MODNAME, UsersConstant::MODVAR_GRAVATAR_IMAGE, UsersConstant::DEFAULT_GRAVATAR_IMAGE);
    if (isset($avatar) && !empty($avatar) && $avatar != $gravatarimage && $avatar != 'blank.gif') {
        $avatarURL = System::getBaseUrl() . $avatarpath . '/' . $avatar;
    } elseif ($avatar == $gravatarimage && $allowgravatars == 1) {
        if (!isset($params['rating'])) {
            $params['rating'] = false;
        }
        if (!isset($params['size'])) {
            if (isset($params['width'])) {
                $params['size'] = $params['width'];
            }
            $params['size'] = 80;
        }
        $params['width'] = $params['size'];
        $params['height'] = $params['size'];
        $avatarURL = 'http://www.gravatar.com/avatar.php?gravatar_id=' . md5($email);
        if (isset($params['rating']) && !empty($params['rating'])) {
            $avatarURL .= "&rating=" . $params['rating'];
        }
        if (isset($params['size']) && !empty($params['size'])) {
            $avatarURL .= "&size=" . $params['size'];
        }
        $avatarURL .= "&default=" . urlencode(System::getBaseUrl() . $avatarpath . '/' . $gravatarimage);
    } else {
        // e.g. blank.gif or empty avatars
        return false;
    }
    $classString = '';
    if (isset($params['class'])) {
        $classString = "class=\"{$params['class']}\" ";
    }
    $html = '<img ' . $classString . ' src="' . DataUtil::formatForDisplay($avatarURL) . '" title="' . DataUtil::formatForDisplay($uname) . '" alt="' . DataUtil::formatForDisplay($uname);
    if (isset($params['width'])) {
        $html .= ' width="' . $params['width'] . '"';
    }
    if (isset($params['height'])) {
        $html .= ' height="' . $params['height'] . '"';
    }
    $html .= '" />';
    if (isset($params['assign'])) {
        $view->assign($params['assign'], $avatarURL);
    } else {
        return $html;
    }
}
/**
 * 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_getbaseurl($params, Zikula_View $view)
{
    LogUtil::log(__f('Warning! Template plugin {%1$s} is deprecated, please use {%2$s} instead.', array('getbaseurl', '$baseurl')), E_USER_DEPRECATED);
    $assign = isset($params['assign']) ? $params['assign'] : null;
    $result = htmlspecialchars(System::getBaseUrl());
    if ($assign) {
        $view->assign($assign, $result);
    } else {
        return $result;
    }
}
Example #7
0
/**
 * Smarty function to generate a valid atom ID for the feed
 *
 * Example
 *
 *   <id>{id}</id>
 *
 * @return       string the atom ID
 */
function smarty_function_id($params, &$smarty)
{
    $baseurl = System::getBaseUrl();
    $parts = parse_url($baseurl);
    $starttimestamp = strtotime(System::getVar('startdate'));
    $startdate = strftime('%Y-%m-%d', $starttimestamp);
    $sitename = System::getVar('sitename');
    $sitename = preg_replace('/[^a-zA-Z0-9-\\s]/', '', $sitename);
    $sitename = DataUtil::formatForURL($sitename);
    return "tag:{$parts['host']},{$startdate}:{$sitename}";
}
/**
 * The reviewsObjectState modifier displays the name of a given object's workflow state.
 * Examples:
 *    {$item.workflowState|reviewsObjectState}       {* with visual feedback *}
 *    {$item.workflowState|reviewsObjectState:false} {* no ui feedback *}
 *
 * @param string  $state      Name of given workflow state.
 * @param boolean $uiFeedback Whether the output should include some visual feedback about the state.
 *
 * @return string Enriched and translated workflow state ready for display.
 */
function smarty_modifier_reviewsObjectState($state = 'initial', $uiFeedback = true)
{
    $serviceManager = ServiceUtil::getManager();
    $workflowHelper = new Reviews_Util_Workflow($serviceManager);
    $stateInfo = $workflowHelper->getStateInfo($state);
    $result = $stateInfo['text'];
    if ($uiFeedback === true) {
        $result = '<img src="' . System::getBaseUrl() . 'images/icons/extrasmall/' . $stateInfo['ui'] . 'led.png" width="16" height="16" alt="' . $result . '" />&nbsp;&nbsp;' . $result;
    }
    return $result;
}
/**
 * Zikula_View short urls outputfilter plugin.
 *
 * File:      outputfilter.shorturls.php
 * Type:      outputfilter
 * Name:      shorturls
 *
 * @param string      $source Output source.
 * @param Zikula_View $view   Reference to Zikula_View instance.
 *
 * @return string
 */
function smarty_outputfilter_shorturls($source, $view)
{
    // If you control the server, it is preferable for better performance to put rewrite rules
    // from the htaccess file into main configuration file, httpd.conf.
    $baseurl = System::getBaseUrl();
    $prefix = '[(<[^>]*?)[\'"](?:' . $baseurl . '|' . $baseurl . ')?(?:[./]{0,2})';
    // Match local URLs in HTML tags, removes / and ./
    $in = array('[<([^>]+)\\s(src|href|background|action)\\s*=\\s*((["\'])?)(?!http)(?!skype)(?!xmpp)(?!icq)(?!mailto)(?!javascript:)(?![/"\'\\s#]+)]Ui');
    $out = array('<$1 $2=$3' . $baseurl);
    // perform the replacement
    $source = preg_replace($in, $out, $source);
    // return the modified source
    return $source;
}
Example #10
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;
 }
/**
 * CoType
 *
 * @copyright (C) 2007, Jorn Wildt
 * @link http://www.elfisk.dk
 * @version $Id$
 * @license See license.txt
 */
function smarty_function_cotypeEditor($params, &$render)
{
    $inputId = $params['inputId'];
    $documentId = (int) $params['documentId'];
    static $firstTime = true;
    if ($firstTime) {
        PageUtil::AddVar('javascript', 'javascript/ajax/prototype.js');
        $moduleStylesheet = '../../../../' . ThemeUtil::getModuleStylesheet('cotype', 'editor.css');
        $url = System::getBaseUrl();
        $head = "<script type=\"text/javascript\">\nCoTypeStylesheet = '{$moduleStylesheet}';\nCoTypeDocumentId = {$documentId};\n</script>";
        PageUtil::AddVar('header', $head);
    }
    $firstTime = false;
    $html = "";
    return $html;
}
/**
 * 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 #13
0
    /**
     * Show the month calendar into a bloc
     * @autor:	Albert Pérez Monfort
     * @autor:	Toni Ginard Lladó
     * param:	The month and the year to show
     * return:	The calendar content
     */
    public function display($blockinfo) {

        // Security check
        if (!SecurityUtil::checkPermission("IWusers:welcomeblock:", $blockinfo['title'] . "::", ACCESS_READ)) {
            return;
        }
        $baseURL = System::getBaseUrl();
        $baseURL .= 'index.php';
        if ('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] != $baseURL) {
            return;
        }
        // Check if the module is available
        if (!ModUtil::available('IWusers')) {
            return;
        }
        $user = (UserUtil::isLoggedIn()) ? UserUtil::getVar('uid') : '-1';
        // Only for loggedin users
        if ($user == '-1') {
            return;
        }
        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
        $userName = ModUtil::func('IWmain', 'user', 'getUserInfo', array('sv' => $sv,
                    'uid' => $user,
                    'info' => 'n'));
        $values = explode('---', $blockinfo['url']);
        $hello = (!empty($values[0])) ? $values[0] : $this->__('Hi');
        $welcome = (!empty($values[0])) ? $values[1] : $this->__('welcome to the intranet');
        $date = (isset($values[2])) ? $values[2] : '';

        $s = $this->view->assign('userName', $userName)
                        ->assign('hello', $hello)
                        ->assign('welcome', $welcome)
                        ->assign('date', $date)
                        ->assign('dateText', date('d/m/Y', time()))
                        ->assign('timeText', date('H.i', time()))
                        ->fetch('IWusers_block_welcome.htm');
        // Populate block info and pass to theme
        $blockinfo['content'] = $s;
        return BlockUtil::themesideblock($blockinfo);
    }
Example #14
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(), 'uid' => (int) UserUtil::getVar('uid'));
     $polyfill_features = PageUtil::getVar('polyfill_features');
     // merge in features added via twig
     $featuresFromTwig = ServiceUtil::get('zikula_core.common.theme.pagevars')->get('polyfill_features', []);
     $polyfill_features = array_unique(array_merge($polyfill_features, $featuresFromTwig));
     if (!empty($polyfill_features)) {
         $config['polyfillFeatures'] = implode(' ', $polyfill_features);
     }
     $config = DataUtil::formatForDisplay($config);
     $return .= "<script type=\"text/javascript\">/* <![CDATA[ */ \n";
     if (System::isLegacyMode()) {
         $return .= 'document.location.entrypoint="' . $config['entrypoint'] . '";';
         $return .= 'document.location.pnbaseURL="' . $config['baseURL'] . '"; ';
         $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;
 }
Example #15
0
/**
 * Generate the upgrade module page.
 *
 * This function upgrade available module to an upgrade
 *
 * @param string $username Username of the admin user.
 * @param string $password Password of the admin user.
 *
 * @return void
 */
function _upg_upgrademodules($username, $password)
{
    _upg_header();
    $modvars = DBUtil::selectObjectArray('module_vars');
    foreach ($modvars as $modvar) {
        if ($modvar['value'] == '0' || $modvar['value'] == '1') {
            $modvar['value'] = serialize($modvar['value']);
            DBUtil::updateObject($modvar, 'module_vars');
        }
    }
    // force load the modules admin API
    ModUtil::loadApi('Extensions', 'admin', true);
    echo '<h2>' . __('Starting upgrade') . '</h2>' . "\n";
    echo '<ul id="upgradelist" class="check">' . "\n";
    // reset for User module
    //$GLOBALS['_ZikulaUpgrader']['_ZikulaUpgradeFrom12x'] = false;
    $results = ModUtil::apiFunc('Extensions', 'admin', 'upgradeall');
    if ($results) {
        foreach ($results as $modname => $result) {
            if ($result) {
                echo '<li class="passed">' . DataUtil::formatForDisplay($modname) . ' ' . __('upgraded') . '</li>' . "\n";
            } else {
                echo '<li class="failed">' . DataUtil::formatForDisplay($modname) . ' ' . __('not upgraded') . '</li>' . "\n";
            }
        }
    }
    echo '</ul>' . "\n";
    if (!$results) {
        echo '<ul class="check"><li class="passed">' . __('No modules required upgrading') . '</li></ul>';
    }
    // wipe out the deprecated modules from Modules list.
    $modTable = 'modules';
    $sql = "DELETE FROM {$modTable} WHERE name = 'Header_Footer' OR name = 'AuthPN' OR name = 'pnForm' OR name = 'Workflow' OR name = 'pnRender' OR name = 'Admin_Messages'";
    DBUtil::executeSQL($sql);
    // store localized displayname and description for Extensions module
    $extensionsDisplayname = __('Extensions');
    $extensionsDescription = __('Manage your modules and plugins.');
    $sql = "UPDATE modules SET name = 'Extensions', displayname = '{$extensionsDisplayname}', description = '{$extensionsDescription}' WHERE modules.name = 'Extensions'";
    DBUtil::executeSQL($sql);
    // regenerate the themes list
    ModUtil::apiFunc('Theme', 'admin', 'regenerate');
    // store the recent version in a config var for later usage. This enables us to determine the version we are upgrading from
    System::setVar('Version_Num', Zikula_Core::VERSION_NUM);
    System::setVar('language_i18n', ZLanguage::getLanguageCode());
    // Relogin the admin user to give a proper admin link
    SessionUtil::requireSession();
    echo '<p class="z-statusmsg">' . __('Finished upgrade') . " - \n";
    $authenticationInfo = array('login_id' => $username, 'pass' => $password);
    $authenticationMethod = array('modname' => 'Users', 'method' => 'uname');
    if (!UserUtil::loginUsing($authenticationMethod, $authenticationInfo)) {
        $url = sprintf('<a href="%s">%s</a>', DataUtil::formatForDisplay(System::getBaseUrl()), DataUtil::formatForDisplay(System::getVar('sitename')));
        echo __f('Go to the startpage for %s', $url);
    } else {
        upgrade_clear_caches();
        $url = sprintf('<a href="%s">%s</a>', ModUtil::url('Admin', 'admin', 'adminpanel'), DataUtil::formatForDisplay(System::getVar('sitename')));
        echo __f('Go to the admin panel for %s', $url);
    }
    echo "</p>\n";
    _upg_footer();
}
Example #16
0
 /**
  * Post-Process the data after the entity has been constructed by the entity manager.
  * The event happens after the entity has been loaded from database or after a refresh call.
  *
  * Restrictions:
  *     - no access to entity manager or unit of work apis
  *     - no access to associations (not initialised yet)
  *
  * @see MUVideo_Entity_Movie::postLoadCallback()
  * @return boolean true if completed successfully else false.
  */
 protected function performPostLoadCallback()
 {
     // echo 'loaded a record ...';
     $currentFunc = FormUtil::getPassedValue('func', 'main', 'GETPOST', FILTER_SANITIZE_STRING);
     $usesCsvOutput = FormUtil::getPassedValue('usecsvext', false, 'GETPOST', FILTER_VALIDATE_BOOLEAN);
     // initialise the upload handler
     $uploadManager = new MUVideo_UploadHandler();
     $serviceManager = ServiceUtil::getManager();
     $controllerHelper = new MUVideo_Util_Controller($serviceManager);
     $this['id'] = (int) (isset($this['id']) && !empty($this['id']) ? DataUtil::formatForDisplay($this['id']) : 0);
     $this->formatTextualField('workflowState', $currentFunc, $usesCsvOutput, true);
     $this->formatTextualField('title', $currentFunc, $usesCsvOutput);
     $this->formatTextualField('description', $currentFunc, $usesCsvOutput);
     if (!empty($this['uploadOfMovie'])) {
         try {
             $basePath = $controllerHelper->getFileBaseFolder('movie', 'uploadOfMovie');
         } catch (\Exception $e) {
             return LogUtil::registerError($e->getMessage());
         }
         $fullPath = $basePath . $this['uploadOfMovie'];
         $this['uploadOfMovieFullPath'] = $fullPath;
         $this['uploadOfMovieFullPathURL'] = System::getBaseUrl() . $fullPath;
         // just some backwards compatibility stuff
         /*if (!isset($this['uploadOfMovieMeta']) || !is_array($this['uploadOfMovieMeta']) || !count($this['uploadOfMovieMeta'])) {
               // assign new meta data
               $this['uploadOfMovieMeta'] = $uploadManager->readMetaDataForFile($this['uploadOfMovie'], $fullPath);
           }*/
     }
     $this['urlOfYoutube'] = isset($this['urlOfYoutube']) && !empty($this['urlOfYoutube']) ? DataUtil::formatForDisplay($this['urlOfYoutube']) : '';
     if (!empty($this['poster'])) {
         try {
             $basePath = $controllerHelper->getFileBaseFolder('movie', 'poster');
         } catch (\Exception $e) {
             return LogUtil::registerError($e->getMessage());
         }
         $fullPath = $basePath . $this['poster'];
         $this['posterFullPath'] = $fullPath;
         $this['posterFullPathURL'] = System::getBaseUrl() . $fullPath;
         // just some backwards compatibility stuff
         /*if (!isset($this['posterMeta']) || !is_array($this['posterMeta']) || !count($this['posterMeta'])) {
               // assign new meta data
               $this['posterMeta'] = $uploadManager->readMetaDataForFile($this['poster'], $fullPath);
           }*/
     }
     $this['widthOfMovie'] = (int) (isset($this['widthOfMovie']) && !empty($this['widthOfMovie']) ? DataUtil::formatForDisplay($this['widthOfMovie']) : 0);
     $this['heightOfMovie'] = (int) (isset($this['heightOfMovie']) && !empty($this['heightOfMovie']) ? DataUtil::formatForDisplay($this['heightOfMovie']) : 0);
     $this->prepareItemActions();
     return true;
 }
Example #17
0
 function getImage()
 {
     return System::getBaseUrl() . '/modules/Content/images/layouttype/column3_502525_header.png';
 }
Example #18
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;
    }
}
Example #19
0
 /**
  * modify block settings
  *
  * @param        array       $blockinfo     a blockinfo structure
  * @return       output      the bock form
  */
 public function modify($blockinfo)
 {
     // Break out options from our content field
     $vars = BlockUtil::varsFromContent($blockinfo['content']);
     $blockinfo['content'] = '';
     // Defaults
     if (empty($vars['displaymodules'])) {
         $vars['displaymodules'] = 0;
     }
     // template to use
     if (empty($vars['template'])) {
         $vars['template'] = 'blocks_block_extmenu.tpl';
     }
     // 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;
     }
     $languages = ZLanguage::getInstalledLanguages();
     $userlanguage = ZLanguage::getLanguageCode();
     // filter out invalid languages
     foreach ($vars['blocktitles'] as $k => $v) {
         if (!in_array($k, $languages)) {
             unset($vars['blocktitles'][$k]);
             unset($vars['links'][$k]);
         }
     }
     // check if the users wants to add a new link via the "Add current url" link in the block
     $addurl = FormUtil::getPassedValue('addurl', 0, 'GET');
     // or if we come from the normal "edit this block" link
     $fromblock = FormUtil::getPassedValue('fromblock', null, 'GET');
     $redirect = '';
     if ($addurl == 1) {
         // set a marker for redirection later on
         $newurl = System::serverGetVar('HTTP_REFERER');
         $redirect = urlencode($newurl);
         $newurl = str_replace(System::getBaseUrl(), '', $newurl);
         if (empty($newurl)) {
             $newurl = System::getHomepageUrl();
         }
         foreach ($languages as $singlelanguage) {
             $vars['links'][$singlelanguage][] = array('name' => $this->__('--New link--'), 'url' => $newurl, 'title' => $this->__('--New link--'), 'level' => 0, 'parentid' => null, 'image' => '', 'active' => 1);
         }
     } elseif (isset($fromblock)) {
         $redirect = urlencode(System::serverGetVar('HTTP_REFERER'));
     }
     // add new languages to the blocktitles and link arrays
     // we need to know which language has the most links, this language will be the "master"
     // for new languages to be added. this ensures that all links for the new language
     // are prepared.
     $link_master = array();
     foreach ($languages as $lang) {
         if (isset($vars['links'][$lang]) && count($link_master) < count($vars['links'][$lang])) {
             $link_master = $vars['links'][$lang];
         }
     }
     foreach ($languages as $lang) {
         // create an empty blocktitle string
         if (!array_key_exists($lang, $vars['blocktitles'])) {
             $vars['blocktitles'][$lang] = '';
         }
         if (!array_key_exists($lang, $vars['links'])) {
             $vars['links'][$lang] = $link_master;
         }
     }
     // menuitems are sorted by language per default for easier
     // access when showing them (which is more often necessary than
     // editing them), but for editing them we need them sorted by id
     $menuitems = array();
     foreach ($vars['links'] as $lang => $langlinks) {
         // langlinks now contains an array of links for a certain language
         // sorted by key=id
         foreach ($langlinks as $linkid => $link) {
             // pre zk1.2 check
             if (!isset($link['id'])) {
                 $link['id'] = $linkid;
             }
             $link['errors'] = array();
             $this->checkImage($link);
             $menuitems[$linkid][$lang] = $link;
         }
     }
     $vars['links'] = $menuitems;
     $this->view->setCaching(Zikula_View::CACHE_DISABLED);
     // assign the vars
     $this->view->assign($vars)->assign('languages', $languages)->assign('userlanguage', $userlanguage)->assign('redirect', $redirect)->assign('blockinfo', $blockinfo);
     // return the output
     return $this->view->fetch('blocks_block_extmenu_modify.tpl');
 }
Example #20
0
 /**
  * Initialise Zikula.
  *
  * Carries out a number of initialisation tasks to get Zikula up and
  * running.
  *
  * @param integer $stage Stage to load.
  *
  * @return boolean True initialisation successful false otherwise.
  */
 public function init($stage = self::STAGE_ALL)
 {
     $coreInitEvent = new Zikula_Event('core.init', $this);
     // store the load stages in a global so other API's can check whats loaded
     $this->stage = $this->stage | $stage;
     if ($stage & self::STAGE_PRE && $this->stage & ~self::STAGE_PRE) {
         ModUtil::flushCache();
         System::flushCache();
         $this->eventManager->notify(new Zikula_Event('core.preinit', $this));
     }
     // Initialise and load configuration
     if ($stage & self::STAGE_CONFIG) {
         if (System::isLegacyMode()) {
             require_once 'lib/legacy/Compat.php';
         }
         // error reporting
         if (!System::isInstalling()) {
             // this is here because it depends on the config.php loading.
             $event = new Zikula_Event('setup.errorreporting', null, array('stage' => $stage));
             $this->eventManager->notify($event);
         }
         // initialise custom event listeners from config.php settings
         $coreInitEvent->setArg('stage', self::STAGE_CONFIG);
         $this->eventManager->notify($coreInitEvent);
     }
     // Check that Zikula is installed before continuing
     if (System::getVar('installed') == 0 && !System::isInstalling()) {
         System::redirect(System::getBaseUrl() . 'install.php?notinstalled');
         System::shutDown();
     }
     if ($stage & self::STAGE_DB) {
         try {
             $dbEvent = new Zikula_Event('core.init', $this, array('stage' => self::STAGE_DB));
             $this->eventManager->notify($dbEvent);
         } catch (PDOException $e) {
             if (!System::isInstalling()) {
                 header('HTTP/1.1 503 Service Unavailable');
                 require_once System::getSystemErrorTemplate('dbconnectionerror.tpl');
                 System::shutDown();
             } else {
                 return false;
             }
         }
     }
     if ($stage & self::STAGE_TABLES) {
         // Initialise dbtables
         ModUtil::dbInfoLoad('Extensions', 'Extensions');
         ModUtil::initCoreVars();
         ModUtil::dbInfoLoad('Settings', 'Settings');
         ModUtil::dbInfoLoad('Theme', 'Theme');
         ModUtil::dbInfoLoad('Users', 'Users');
         ModUtil::dbInfoLoad('Groups', 'Groups');
         ModUtil::dbInfoLoad('Permissions', 'Permissions');
         ModUtil::dbInfoLoad('Categories', 'Categories');
         if (!System::isInstalling()) {
             ModUtil::registerAutoloaders();
         }
         $coreInitEvent->setArg('stage', self::STAGE_TABLES);
         $this->eventManager->notify($coreInitEvent);
     }
     if ($stage & self::STAGE_SESSIONS) {
         SessionUtil::requireSession();
         $coreInitEvent->setArg('stage', self::STAGE_SESSIONS);
         $this->eventManager->notify($coreInitEvent);
     }
     // Have to load in this order specifically since we cant setup the languages until we've decoded the URL if required (drak)
     // start block
     if ($stage & self::STAGE_LANGS) {
         $lang = ZLanguage::getInstance();
     }
     if ($stage & self::STAGE_DECODEURLS) {
         System::queryStringDecode();
         $coreInitEvent->setArg('stage', self::STAGE_DECODEURLS);
         $this->eventManager->notify($coreInitEvent);
     }
     if ($stage & self::STAGE_LANGS) {
         $lang->setup();
         $coreInitEvent->setArg('stage', self::STAGE_LANGS);
         $this->eventManager->notify($coreInitEvent);
     }
     // end block
     if ($stage & self::STAGE_MODS) {
         // Set compression on if desired
         if (System::getVar('UseCompression') == 1) {
             //ob_start("ob_gzhandler");
         }
         ModUtil::load('SecurityCenter');
         $coreInitEvent->setArg('stage', self::STAGE_MODS);
         $this->eventManager->notify($coreInitEvent);
     }
     if ($stage & self::STAGE_THEME) {
         // register default page vars
         PageUtil::registerVar('title');
         PageUtil::setVar('title', System::getVar('defaultpagetitle'));
         PageUtil::registerVar('keywords', true);
         PageUtil::registerVar('stylesheet', true);
         PageUtil::registerVar('javascript', true);
         PageUtil::registerVar('jsgettext', true);
         PageUtil::registerVar('body', true);
         PageUtil::registerVar('header', true);
         PageUtil::registerVar('footer', true);
         $theme = Zikula_View_Theme::getInstance();
         // set some defaults
         // Metadata for SEO
         $this->serviceManager['zikula_view.metatags']['description'] = System::getVar('defaultmetadescription');
         $this->serviceManager['zikula_view.metatags']['keywords'] = System::getVar('metakeywords');
         $coreInitEvent->setArg('stage', self::STAGE_THEME);
         $this->eventManager->notify($coreInitEvent);
     }
     // check the users status, if not 1 then log him out
     if (UserUtil::isLoggedIn()) {
         $userstatus = UserUtil::getVar('activated');
         if ($userstatus != Users_Constant::ACTIVATED_ACTIVE) {
             UserUtil::logout();
             // TODO - When getting logged out this way, the existing session is destroyed and
             //        then a new one is created on the reentry into index.php. The message
             //        set by the registerStatus call below gets lost.
             LogUtil::registerStatus(__('You have been logged out.'));
             System::redirect(ModUtil::url('Users', 'user', 'login'));
         }
     }
     if ($stage & self::STAGE_POST && $this->stage & ~self::STAGE_POST) {
         $this->eventManager->notify(new Zikula_Event('core.postinit', $this, array('stages' => $stage)));
     }
 }
/**
 * Category selector.
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return string
 */
function smarty_function_selector_category($params, Zikula_View $view)
{
    $categoryRegistryModule = isset($params['categoryRegistryModule']) ? $params['categoryRegistryModule'] : '';
    $categoryRegistryTable = isset($params['categoryRegistryTable']) ? $params['categoryRegistryTable'] : '';
    $categoryRegistryProperty = isset($params['categoryRegistryProperty']) ? $params['categoryRegistryProperty'] : '';
    $category = isset($params['category']) ? $params['category'] : 0;
    $path = isset($params['path']) ? $params['path'] : '';
    $pathfield = isset($params['pathfield']) ? $params['pathfield'] : 'path';
    $field = isset($params['field']) ? $params['field'] : 'id';
    $fieldIsAttribute = isset($params['fieldIsAttribute']) ? $params['fieldIsAttribute'] : null;
    $selectedValue = isset($params['selectedValue']) ? $params['selectedValue'] : 0;
    $defaultValue = isset($params['defaultValue']) ? $params['defaultValue'] : 0;
    $defaultText = isset($params['defaultText']) ? $params['defaultText'] : '';
    $allValue = isset($params['allValue']) ? $params['allValue'] : 0;
    $allText = isset($params['allText']) ? $params['allText'] : '';
    $name = isset($params['name']) ? $params['name'] : 'defaultselectorname';
    $submit = isset($params['submit']) ? $params['submit'] : false;
    $recurse = isset($params['recurse']) ? $params['recurse'] : true;
    $relative = isset($params['relative']) ? $params['relative'] : true;
    $includeRoot = isset($params['includeRoot']) ? $params['includeRoot'] : false;
    $includeLeaf = isset($params['includeLeaf']) ? $params['includeLeaf'] : true;
    $all = isset($params['all']) ? $params['all'] : false;
    $displayPath = isset($params['displayPath']) ? $params['displayPath'] : false;
    $attributes = isset($params['attributes']) ? $params['attributes'] : null;
    $assign = isset($params['assign']) ? $params['assign'] : null;
    $editLink = isset($params['editLink']) ? $params['editLink'] : true;
    $multipleSize = isset($params['multipleSize']) ? $params['multipleSize'] : 1;
    $sortField = isset($params['sortField']) ? $params['sortField'] : 'sort_value';
    $doReplaceRootCat = isset($params['doReplaceRootCat']) ? $params['doReplaceRootCat'] : null;
    $cssClass = isset($params['cssClass']) ? $params['cssClass'] : '';
    if (isset($params['lang'])) {
        $lang = $params['lang'];
        $oldLocale = ZLanguage::getLocale();
        ZLanguage::setLocale($lang);
    } else {
        $lang = ZLanguage::getLanguageCode();
    }
    if (!$category && !$path && $categoryRegistryModule && $categoryRegistryTable && $categoryRegistryProperty) {
        $category = CategoryRegistryUtil::getRegisteredModuleCategory($categoryRegistryModule, $categoryRegistryTable, $categoryRegistryProperty);
    }
    // if we don't have a category-id we see if we can get a category by path
    if (!$category && $path) {
        $category = CategoryUtil::getCategoryByPath($path, $pathfield);
    } elseif (is_numeric($category)) {
        // check if we have a numeric category
        $category = CategoryUtil::getCategoryByID($category);
    } elseif (is_string($category) && strpos($category, '/') === 0) {
        // check if we have a string/path category
        $category = CategoryUtil::getCategoryByPath($category, $pathfield);
    }
    static $catCache;
    if (!$catCache) {
        $catCache = array();
    }
    $cacheKey = "{$category['id']}||{$recurse}|{$relative}|{$includeRoot}|{$includeLeaf}|{$all}|||{$attributes}|{$sortField}";
    if (!isset($catCache[$cacheKey])) {
        $catCache[$cacheKey] = CategoryUtil::getSubCategoriesForCategory($category, $recurse, $relative, $includeRoot, $includeLeaf, $all, '', '', $attributes, $sortField);
    }
    $html = CategoryUtil::getSelector_Categories($catCache[$cacheKey], $field, $selectedValue, $name, $defaultValue, $defaultText, $allValue, $allText, $submit, $displayPath, $doReplaceRootCat, $multipleSize, $fieldIsAttribute, $cssClass, $lang);
    if ($editLink && !empty($category) && SecurityUtil::checkPermission('ZikulaCategoriesModule::', "{$category['id']}::", ACCESS_EDIT)) {
        $url = DataUtil::formatForDisplay(ModUtil::url('ZikulaCategoriesModule', 'user', 'edit', array('dr' => $category['id'])));
        $html .= "&nbsp;&nbsp;<a href=\"{$url}\"><img src=\"" . System::getBaseUrl() . "images/icons/extrasmall/xedit.png\" title=\"" . __('Edit sub-category') . '" alt="' . __('Edit sub-category') . '" /></a>';
    }
    if (isset($params['lang'])) {
        // Reset language again.
        ZLanguage::setLocale($oldLocale);
    }
    if ($assign) {
        $view->assign($assign, $html);
    } else {
        return $html;
    }
}
/**
 * Smarty function to display edit and delete links for a news article
 *
 * Example
 * <!--[articleadminlinks sid='1' start='[' and=']' seperator='|' class='z-sub']-->
 *
 * @author       Mark West
 * @since        20/10/03
 * @see          function.articleadminlinks.php::smarty_function_articleadminlinks()
 * @param        array       $params      All attributes passed to this function from the template
 * @param        object      &$smarty     Reference to the Smarty object
 * @param        integer     $sid         article id
 * @param        string      $start       start string
 * @param        string      $end         end string
 * @param        string      $seperator   link seperator
 * @param        string      $class       CSS class
 * @return       string      the results of the module function
 */
function smarty_function_articleadminlinks($params, &$smarty)
{
    $dom = ZLanguage::getModuleDomain('News');

    // get the info template var
    $info = $smarty->get_template_vars('info');

    if (!isset($params['sid'])) {
        $params['sid'] = $info['sid'];
    }
    if (!isset($params['page'])) {
        $params['page'] = $smarty->get_template_vars('page');
    }

    // set some defaults
    if (!isset($params['start'])) {
        $params['start'] = '[';
    }
    if (!isset($params['end'])) {
        $params['end'] = ']';
    }
    if (!isset($params['seperator'])) {
        $params['seperator'] = '|';
    }
    if (!isset($params['class'])) {
        $params['class'] = 'z-sub';
    }
    if (isset($params['type']) && $params['type'] <> 'ajax') {
        $params['type'] = '';
    }

/*
    // Check for the current user to enable users to edit their own articles
    if (UserUtil::isLoggedIn()) {
        $uid = UserUtil::getVar('uid');
    } else {
        $uid = 0;
    }
*/
    $articlelinks = '';
    if (SecurityUtil::checkPermission('News::', "$info[cr_uid]:$info[cattitle]:$info[sid]", ACCESS_EDIT) /*|| ($uid != 0 && $info['cr_uid'] == $uid)*/) {
        // load our ajax files into the header
        if (isset($params['type']) && $params['type'] == 'ajax') {
            // load our ajax files into the header
            require_once $smarty->_get_plugin_filepath('function', 'ajaxheader');
            smarty_function_ajaxheader(array('modname' => 'News', 'filename' => 'news.js'), $smarty);
            smarty_function_ajaxheader(array('modname' => 'News', 'filename' => 'sizecheck.js'), $smarty);
            smarty_function_ajaxheader(array('modname' => 'News', 'filename' => 'prototype-base-extensions.js'), $smarty);
            smarty_function_ajaxheader(array('modname' => 'News', 'filename' => 'prototype-date-extensions.js'), $smarty);
            smarty_function_ajaxheader(array('modname' => 'News', 'filename' => 'datepicker.js'), $smarty);
            smarty_function_ajaxheader(array('modname' => 'News', 'filename' => 'datepicker-locale.js'), $smarty);
            if (ModUtil::getVar('News', 'enableattribution')) {
                PageUtil::addVar('javascript', 'javascript/helpers/Zikula.itemlist.js');
            }
            PageUtil::addVar('stylesheet', 'modules/News/style/datepicker.css');
            $articlelinks .= '<img id="news_loadnews" src="'.System::getBaseUrl().'images/ajax/circle-ball-dark-antialiased.gif" alt="" /><span class="' . $params['class'] . '"> ' . $params['start'] . ' <a onclick="editnews(' . $params['sid'] . ',' . $params['page'] . ')" href="javascript:void(0);">' . __('Quick edit', $dom) . '</a> ' . $params['end'] . "</span>\n";
        } else {
            $articlelinks .= '<span class="' . $params['class'] . '"> ' . $params['start'] . ' <a href="' . DataUtil::formatForDisplayHTML(ModUtil::url('News', 'admin', 'modify', array('sid' => $params['sid']))) . '">' . __('Edit', $dom) . '</a>';
            if (SecurityUtil::checkPermission('News::', "$info[cr_uid]:$info[cattitle]:$info[sid]", ACCESS_DELETE)) {
                $articlelinks .= ' ' . $params['seperator'] . ' <a href="' . DataUtil::formatForDisplay(ModUtil::url('News', 'admin', 'delete', array('sid' => $params['sid']))) . '">' . __('Delete', $dom) . '</a>';
            }
            $articlelinks .= ' ' . $params['end'] . "</span>\n";
        }
    }

    return $articlelinks;
}
Example #23
0
    /**
     * Gets user news
     *
     * @author	Albert Pérez Monfort (aperezm@xtec.cat)
     * @return	The user news block
     */
    public function display($row) {
        // Security check
        if (!SecurityUtil::checkPermission('IWmain:newsBlock:', $row['title'] . "::", ACCESS_READ) || !UserUtil::isLoggedIn()) {
            return false;
        }

        if (ModUtil::getVar('IWmain', 'URLBase') != System::getBaseUrl()) {
            ModUtil::setVar('IWmain', 'URLBase', System::getBaseUrl());
        }

        $uid = UserUtil::getVar('uid');

        //get the headlines saved in the user vars. It is renovate every 10 minutes
        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
        $exists = ModUtil::apiFunc('IWmain', 'user', 'userVarExists', array('name' => 'news',
                    'module' => 'IWmain_block_news',
                    'uid' => $uid,
                    'sv' => $sv));

        if ($exists) {
            $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
            $have_news = ModUtil::func('IWmain', 'user', 'userGetVar', array('uid' => $uid,
                        'name' => 'have_news',
                        'module' => 'IWmain_block_news',
                        'sv' => $sv));
            if ($have_news != '0') {
                ModUtil::func('IWmain', 'user', 'news', array('where' => $have_news));
                $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
                ModUtil::func('IWmain', 'user', 'userSetVar', array('uid' => $uid,
                    'name' => 'have_news',
                    'module' => 'IWmain_block_news',
                    'sv' => $sv,
                    'value' => '0'));
            }

            $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
            $have_flags = ModUtil::func('IWmain', 'user', 'userGetVar', array('uid' => UserUtil::getVar('uid'),
                        'name' => 'have_flags',
                        'module' => 'IWmain_block_flagged',
                        'sv' => $sv));

            if ($have_flags != '0') {
                ModUtil::func('IWmain', 'user', 'flagged', array('where' => $have_flags,
                    'chars' => 15));


                $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
                ModUtil::func('IWmain', 'user', 'userSetVar', array('uid' => UserUtil::getVar('uid'),
                    'name' => 'have_flags',
                    'module' => 'IWmain_block_flagged',
                    'sv' => $sv,
                    'value' => '0'));
            }
        } else {
            ModUtil::func('IWmain', 'user', 'news');
        }

        //get the flagged items
        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
        if (!$exists = ModUtil::apiFunc('IWmain', 'user', 'userVarExists', array('name' => 'flagged',
                    'module' => 'IWmain_block_flagged',
                    'uid' => $uid,
                    'sv' => $sv))) {
            ModUtil::func('IWmain', 'user', 'flagged', array('where' => '',
                'chars' => 15));
        }

        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
        $news = ModUtil::func('IWmain', 'user', 'userGetVar', array('uid' => $uid,
                    'name' => 'news',
                    'module' => 'IWmain_block_news',
                    'sv' => $sv,
                    'nult' => true));

        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
        $flags = ModUtil::func('IWmain', 'user', 'userGetVar', array('uid' => UserUtil::getVar('uid'),
                    'name' => 'flagged',
                    'module' => 'IWmain_block_flagged',
                    'sv' => $sv,
                    'nult' => true));

        $this->view->assign('news', $news)
                ->assign('flags', $flags);

        $s = $this->view->fetch('IWmain_block_IWnews.tpl');

        $row['content'] = $s;
        return BlockUtil::themesideblock($row);
    }
Example #24
0
/**
 * Rewritten by Nathan Codding - Feb 6, 2001.
 * - Goes through the given string, and replaces xxxx://yyyy with an HTML <a> tag linking
 * 	to that URL
 * - Goes through the given string, and replaces www.xxxx.yyyy[zzzz] with an HTML <a> tag linking
 * 	to http://www.xxxx.yyyy[/zzzz]
 * - Goes through the given string, and replaces xxxx@yyyy with an HTML mailto: tag linking
 *		to that email address
 * - Only matches these 2 patterns either after a space, or at the beginning of a line
 *
 * Notes: the email one might get annoying - it's easy to make it more restrictive, though.. maybe
 * have it require something like xxxx@yyyy.zzzz or such. We'll see.
 */
function make_clickable($text)
{
    // Begin PNphpBB2 Module
    global $board_config;
    // End PNphpBB2 Module
    $text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1&#058;", $text);
    // pad it with a space so we can match things at the start of the 1st line.
    $ret = ' ' . $text;
    // Begin PNphpBB2 Module
    if ($board_config['pnphpbb2_shorturls'] == 0) {
        // Below is the original phpBB code for making clickable links
        // matches an "xxxx://yyyy" URL at the start of a line, or after a space.
        // xxxx can only be alpha characters.
        // yyyy is anything up to the first space, newline, comma, double quote or <
        $ret = preg_replace("#(^|[\n ])([\\w]+?://[\\w\\#\$%&~/.\\-;:=,?@\\[\\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
        // matches a "www|ftp.xxxx.yyyy[/zzzz]" kinda lazy URL thing
        // Must contain at least 2 dots. xxxx contains either alphanum, or "-"
        // zzzz is optional.. will contain everything up to the first space, newline,
        // comma, double quote or <.
        $ret = preg_replace("#(^|[\n ])((www|ftp)\\.[\\w\\#\$%&~/.\\-;:=,?@\\[\\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret);
        // matches an email@domain type address at the start of a line, or after a space.
        // Note: Only the followed chars are valid; alphanums, "-", "_" and or ".".
        $ret = preg_replace("#(^|[\n ])([a-z0-9&\\-_.]+?)@([\\w\\-]+\\.([\\w\\-\\.]+\\.)*[\\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);
    } else {
        // This code was barrowed from phpBB2 2.1 CVS
        $match = array();
        $replace = array();
        // relative urls for this board
        $match[] = '#' . System::getBaseUrl() . preg_replace('/^\\/?(.*?)(\\/)?$/', '\\1', trim($config['script_path'])) . '/([^ \\t\\n\\r <"\']+)#i';
        $replace[] = '<!-- l --><a href="\\1" target="_blank">\\1</a><!-- l -->';
        // matches a xxxx://aaaaa.bbb.cccc. ...
        $match[] = '#(^|[\\n ])([\\w]+?://.*?[^ \\t\\n\\r<"]*)#ie';
        $replace[] = "'\\1<!-- m --><a href=\"\\2\" target=\"_blank\">' . ((strlen('\\2') > 55) ? substr('\\2', 0, 39) . ' ... ' . substr('\\2', -10) : '\\2') . '</a><!-- m -->'";
        // matches a "www.xxxx.yyyy[/zzzz]" kinda lazy URL thing
        $match[] = '#(^|[\\n ])(www\\.[\\w\\-]+\\.[\\w\\-.\\~]+(?:/[^ \\t\\n\\r<"]*)?)#ie';
        $replace[] = "'\\1<!-- w --><a href=\"http://\\2\" target=\"_blank\">' . ((strlen('\\2') > 55) ? substr(str_replace(' ', '%20', '\\2'), 0, 39) . ' ... ' . substr('\\2', -10) : '\\2') . '</a><!-- w -->'";
        // matches an email@domain type address at the start of a line, or after a space.
        $match[] = '#(^|[\\n ])([a-z0-9&\\-_.]+?@[\\w\\-]+\\.([\\w\\-\\.]+\\.)?[\\w]+)#ie';
        $replace[] = "'\\1<!-- e --><a href=\"mailto:\\2\">' . ((strlen('\\2') > 55) ? substr('\\2', 0, 39) . ' ... ' . substr('\\2', -10) : '\\2') . '</a><!-- e -->'";
        $ret = preg_replace($match, $replace, $ret);
    }
    // End PNphpBB2 Module
    // Remove our padding..
    $ret = substr($ret, 1);
    return $ret;
}
Example #25
0
<?php

global $post_id;
include $phpbb_root_path . 'extension.inc';
include $phpbb_root_path . 'common.' . $phpEx;
include $phpbb_root_path . 'includes/functions_post.' . $phpEx;
$topic = isset($_POST['topic']) ? $_POST['topic'] : $_GET['topic'];
$friendname = $_POST['friendname'];
$message = $_POST['message'];
// Begin PNphpBB2 Module
$link = System::getBaseUrl() . append_sid("viewtopic") . "&" . $_GET['link'];
// End PNphpBB2 Module
$PHP_SELF = $_SERVER['PHP_SELF'];
$userdata = session_pagestart($user_ip, PAGE_INDEX);
init_userprefs($userdata);
if (!$userdata['session_logged_in']) {
    // ZphpBB2 - use Zikula login and redirect
    //redirect(append_sid("login.$phpEx?redirect=tellafriend.$phpEx&topic=$topic_title&link=" . POST_TOPIC_URL . "=$topic_id", true));
    System::redirect(ModUtil::url('Users', 'user', 'login', array('returnpage' => urlencode(System::getCurrentUri()))));
    // <= ZphpBB2
}
$mail_body = str_replace("{TOPIC}", trim(stripslashes($topic)), $lang['Tell_Friend_Body']);
$mail_body = str_replace("{LINK}", $link, $mail_body);
$mail_body = str_replace("{SITENAME}", $board_config['sitename'], $mail_body);
$template->assign_vars(array('L_TELL_FRIEND_TITLE' => $lang['Tell_Friend_Title'], 'L_TELL_FRIEND_EMAIL_MESSAGE' => $lang['Tell_Friend_Email_Message'], 'L_TELL_FRIEND_SENDER_USER' => $lang['Tell_Friend'], 'L_TELL_FRIEND_SENDER_USER' => $lang['Tell_Friend_Sender_User'], 'L_TELL_FRIEND_SENDER_EMAIL' => $lang['Tell_Friend_Sender_Email'], 'L_TELL_FRIEND_RECIEVER_USER' => $lang['Tell_Friend_Reciever_User'], 'L_TELL_FRIEND_RECIEVER_EMAIL' => $lang['Tell_Friend_Reciever_Email'], 'L_TELL_FRIEND_MSG' => $lang['Tell_Friend_Msg'], 'L_TELL_FRIEND_BODY' => $mail_body, 'SUBMIT_ACTION' => append_sid("tellafriend"), 'L_SUBMIT' => $lang['Send_email'], 'SITENAME' => $board_config['sitename'], 'TOPIC' => trim(stripslashes($topic)), 'LINK' => $link, 'SENDER_NAME' => DataUtil::formatForDisplay($userdata['username']), 'SENDER_MAIL' => $userdata['user_email']));
if (isset($_POST['submit'])) {
    $error = FALSE;
    if (!empty($_POST['friendemail']) && strpos($_POST['friendemail'], "@") > 0) {
        $friendemail = trim(stripslashes($_POST['friendemail']));
        if (!$_POST['friendname']) {
            $friendname = substr($friendemail, 0, strpos($_POST['friendemail'], "@"));
Example #26
0
    /**
     * Update the IWmain module
     * @author Albert Pérez Monfort (aperezm@xtec.cat)
     * @author Jaume Fernàndez Valiente (jfern343@xtec.cat)
     * @return bool true if successful, false otherwise
     */
    public function upgrade($oldversion) {
	switch ($oldversion) {
	    case ($oldversion < '3.0.0'):
        	// create new needed tables and index
        	if (!DBUtil::createTable('IWmain_logs'))
            	    return false;

        	$table = DBUtil::getTables();
        	$c = $table['IWmain_logs_column'];
        	if (!DBUtil::createIndex($c['moduleName'], 'IWmain_logs', 'moduleName'))
            	    return false;
        	if (!DBUtil::createIndex($c['visible'], 'IWmain_logs', 'visible'))
            	    return false;

            	//Array de noms
        	$oldVarsNames = DBUtil::selectFieldArray("module_vars", 'name', "`modname` = 'IWmain'", '', false, '');

        	$newVarsNames = Array('url', 'email', 'documentRoot', 'extensions', 'maxsize', 'usersvarslife',
            	    'cronHeaderText', 'cronFooterText', 'showHideFiles', 'URLBase');

        	$newVars = Array('url' => 'https://github.com/intraweb-modules13/IWmain',
            	    'email' => '*****@*****.**',
            	    'documentRoot' => 'data',
            	    'extensions' => 'odt|ods|odp|zip|pdf|doc|jpg|gif|txt',
            	    'maxsize', '1000000',
            	    'usersvarslife' => '60',
            	    'cronHeaderText' => $this->__('Header text of the cron automatic emails with the new things to see'),
            	    'cronFooterText' => $this->__('Footer text of the email'),
            	    'showHideFiles' => '0',
            	    'captchaPrivateCode' => '',
            	    'captchaPublicCode' => '',
            	    'URLBase' => System::getBaseUrl());

        	// Delete unneeded vars
        	$del = array_diff($oldVarsNames, $newVarsNames);
        	foreach ($del as $i) {
            	    $this->delVar($i);
        	}

        	// Add new vars
        	$add = array_diff($newVarsNames, $oldVarsNames);
        	foreach ($add as $i) {
            	    $this->setVar($i, $newVars[$i]);
        	}
	    case '3.0.0':
		// Clean upgrade. Only fix iwcron problems and table definitions to run with IWusers 3.1.0
	    case '3.0.1':
			// Add new vars
			$this->setVar('cronPasswordActive', false)
                            ->setVar('cronPasswrodString','')
                            ->delVar('showHideFiles')
                            ->setVar('cronSubjectText', $this->__('User Reports'))
                            ->setVar('crAc_UserReports', false)
                            ->setVar('crAc_UR_IWforums', false)
                            ->setVar('crAc_UR_IWmessages', false)
                            ->setVar('crAc_UR_IWforms', false)
                            ->setVar('crAc_UR_IWnoteboard', false)
                            ->setVar('crAc_UR_IWforums_hd', '')
                            ->setVar('crAc_UR_IWmessages_hd', '')
                            ->setVar('crAc_UR_IWforms_hd', '')
                            ->setVar('crAc_UR_IWnoteboard_hd', '')
                            ->setVar('everybodySubscribed', true)
                            ->setVar('cronURfreq', '0');
	}
        return true;
    }
Example #27
0
/**
 * Zikula_View function to display menulinks in an unordered list
 *
 * Example
 * {modulelinks data=$links id='listid' class='navbar navbar-default' itemclass='z-ml-item' first='z-ml-first' last='z-ml-last'}
 *
 * Available parameters:
 *  links     Array with menulinks (text, url, title, id, class, disabled) (optional)
 *  modname   Module name to display links for (optional)
 *  type      Function type where the getLinks-function is located (optional)
 *  menuid    ID for the unordered list (optional)
 *  menuclass Class for the unordered list (optional)
 *  itemclass Array with menulinks (text, url, title, class, disabled) (optional)
 *  first     Class for the first element (optional)
 *  last      Class for the last element (optional)
 *  seperator Link seperator (optional)
 *  class     CSS class (optional).
 *  returnAsArray     return results as array, not as formatted html - MUST set assign
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return string A formatted string containing navigation for the module admin panel.
 */
function smarty_function_modulelinks($params, Zikula_View $view)
{
    $menuLinks = isset($params['links']) ? $params['links'] : '';
    $menuId = isset($params['menuid']) ? $params['menuid'] : '';
    $menuClass = isset($params['menuclass']) ? $params['menuclass'] : 'navbar navbar-default navbar-modulelinks navbar-modulelinks-main';
    $menuItemClass = isset($params['itemclass']) ? $params['itemclass'] : '';
    $menuItemFirst = isset($params['first']) ? $params['first'] : '';
    $menuItemLast = isset($params['last']) ? $params['last'] : '';
    $returnAsArray = isset($params['returnAsArray']) ? (bool) $params['returnAsArray'] : false;
    if (empty($menuLinks)) {
        if (!isset($params['modname']) || !ModUtil::available($params['modname'])) {
            $params['modname'] = ModUtil::getName();
        }
        // check our module name
        if (!ModUtil::available($params['modname'])) {
            $view->trigger_error('modulelinks: ' . __f("Error! The '%s' module is not available.", DataUtil::formatForDisplay($params['modname'])));
            return false;
        }
        $params['type'] = isset($params['type']) ? $params['type'] : 'admin';
        // get the menu links
        // try the Core-2.0 way first, then try the legacy way.
        $menuLinks = $view->getContainer()->get('zikula.link_container_collector')->getLinks($params['modname'], $params['type']);
        if (empty($menuLinks)) {
            $menuLinks = ModUtil::apiFunc($params['modname'], $params['type'], 'getLinks', $params);
        }
    }
    // return if there are no links to print or template has requested to returnAsArray
    if (!$menuLinks || $returnAsArray && isset($params['assign'])) {
        if (isset($params['assign'])) {
            $view->assign($params['assign'], $menuLinks);
        }
        return '';
    }
    $html = '';
    if (!empty($menuLinks)) {
        $html = '<ul';
        $html .= !empty($menuId) ? ' id="' . $menuId . '"' : '';
        $html .= !empty($menuClass) ? ' class="' . $menuClass . '"' : '';
        $html .= '>';
        $i = 1;
        $size = count($menuLinks);
        foreach ($menuLinks as $menuitem) {
            $class = array();
            $class[] = $size == 1 ? 'z-ml-single' : '';
            $class[] = $i == 1 && $size > 1 ? $menuItemFirst : '';
            $class[] = $i == $size && $size > 1 ? $menuItemLast : '';
            $class[] = !empty($menuItemClass) ? $menuItemClass : '';
            $class[] = isset($menuitem['disabled']) && $menuitem['disabled'] == true ? 'z-ml-disabled' : '';
            $class = trim(implode(' ', $class));
            $i++;
            if (System::isLegacyMode() && !empty($class) && isset($menuitem['class'])) {
                if ($menuitem['class'] == 'z-icon-es-add') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'plus';
                } elseif ($menuitem['class'] == 'z-icon-es-back') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'arrow-left';
                } elseif ($menuitem['class'] == 'z-icon-es-cancel') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'times';
                } elseif ($menuitem['class'] == 'z-icon-es-config') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'wrench';
                } elseif ($menuitem['class'] == 'z-icon-es-copy') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'files-o';
                } elseif ($menuitem['class'] == 'z-icon-es-cubes') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'th';
                } elseif ($menuitem['class'] == 'z-icon-es-cut') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'scissors';
                } elseif ($menuitem['class'] == 'z-icon-es-delete') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'trash-o';
                } elseif ($menuitem['class'] == 'z-icon-es-display') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'eye';
                } elseif ($menuitem['class'] == 'z-icon-es-edit') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'pencil-square-o';
                } elseif ($menuitem['class'] == 'z-icon-es-error') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'exclamation-triangle';
                } elseif ($menuitem['class'] == 'z-icon-es-export') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'upload';
                } elseif ($menuitem['class'] == 'z-icon-es-gears') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'gears';
                } elseif ($menuitem['class'] == 'z-icon-es-filter') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'filter';
                } elseif ($menuitem['class'] == 'z-icon-es-group') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'users';
                } elseif ($menuitem['class'] == 'z-icon-es-help') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'info';
                } elseif ($menuitem['class'] == 'z-icon-es-home') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'home';
                } elseif ($menuitem['class'] == 'z-icon-es-hook') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'paperclip';
                } elseif ($menuitem['class'] == 'z-icon-es-import') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'download';
                } elseif ($menuitem['class'] == 'z-icon-es-info') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'info';
                } elseif ($menuitem['class'] == 'z-icon-es-locale') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'globe';
                } elseif ($menuitem['class'] == 'z-icon-es-locked') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'lock';
                } elseif ($menuitem['class'] == 'z-icon-es-log') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'archive';
                } elseif ($menuitem['class'] == 'z-icon-es-mail') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'inbox';
                } elseif ($menuitem['class'] == 'z-icon-es-new') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'file-o';
                } elseif ($menuitem['class'] == 'z-icon-es-ok') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'check';
                } elseif ($menuitem['class'] == 'z-icon-es-options') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'th-list';
                } elseif ($menuitem['class'] == 'z-icon-es-preview') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'cog';
                } elseif ($menuitem['class'] == 'z-icon-es-print') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'print';
                } elseif ($menuitem['class'] == 'z-icon-es-profile') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'user';
                } elseif ($menuitem['class'] == 'z-icon-es-regenerate') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'refresh';
                } elseif ($menuitem['class'] == 'z-icon-es-remove') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'times';
                } elseif ($menuitem['class'] == 'z-icon-es-save') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'floppy-o';
                } elseif ($menuitem['class'] == 'z-icon-es-saveas') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'floppy-o';
                } elseif ($menuitem['class'] == 'z-icon-es-search') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'search';
                } elseif ($menuitem['class'] == 'z-icon-es-url') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'globe';
                } elseif ($menuitem['class'] == 'z-icon-es-user') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'user';
                } elseif ($menuitem['class'] == 'z-icon-es-view') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'eye';
                } elseif ($menuitem['class'] == 'z-icon-es-warning') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'exclamation-triangle';
                } elseif ($menuitem['class'] == 'z-icon-es-rss') {
                    $menuitem['class'] = null;
                    $menuitem['icon'] = 'rss-square';
                }
            }
            $active = '';
            if (!empty($menuitem['url']) && System::getBaseUrl() . $menuitem['url'] === System::getCurrentUrl()) {
                $active = 'active ';
            }
            $dropdown = '';
            if (isset($menuitem['links'])) {
                $dropdown = 'dropdown';
            }
            $html .= '<li';
            $html .= !empty($menuitem['id']) ? ' id="' . $menuitem['id'] . '"' : '';
            $html .= ' class="' . $active . $dropdown;
            $html .= !empty($class) ? $class : '';
            $html .= '">';
            $attr = !empty($menuitem['title']) ? ' title="' . $menuitem['title'] . '"' : '';
            $attr .= !empty($menuitem['class']) ? ' class="' . $menuitem['class'] . '"' : '';
            if (isset($menuitem['disabled']) && $menuitem['disabled'] == true) {
                $html .= '<a ' . $attr . '>' . $menuitem['text'] . '</a>';
            } elseif (!empty($menuitem['url'])) {
                $icon = '';
                if (!empty($menuitem['icon'])) {
                    $icon = '<span class="fa fa-' . $menuitem['icon'] . '"></span> ';
                }
                $html .= '<a href="' . DataUtil::formatForDisplay($menuitem['url']) . '"' . $attr . ' style="display: inline-block;">' . $icon . $menuitem['text'] . '</a>';
                if (isset($menuitem['links'])) {
                    $html .= '<a href="#" class="dropdown-toggle" data-toggle="dropdown" style="text-decoration: none;">&nbsp;<b class="caret"></b></a>';
                }
            } else {
                $html .= '<span' . $attr . '>' . $menuitem['text'] . '</span>';
            }
            if (isset($menuitem['links'])) {
                $html .= '<ul class="dropdown-menu">';
                foreach ($menuitem['links'] as $submenuitem) {
                    $html .= '<li>';
                    if (isset($submenuitem['url'])) {
                        $html .= '<a href="' . DataUtil::formatForDisplay($submenuitem['url']) . '">' . $submenuitem['text'] . '</a>';
                    } else {
                        $html .= $submenuitem['text'];
                    }
                    $html .= '</li>';
                }
                $html .= '</ul>';
            }
            $html .= '</li>';
        }
        $html .= '</ul>';
    }
    if (isset($params['assign'])) {
        $view->assign($params['assign'], $html);
    } else {
        return $html;
    }
}
Example #28
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;
    }
}
/**
 * Display a calendar input control.
 *
 * Display a calendar input control consisting of a calendar image, an optional
 * hidden input field, and associated javascript to render a pop-up calendar.
 * This function displays a javascript (jscalendar) calendar control.
 *
 * Available attributes:
 *   - objectname       (string)    The name of the object the field will be placed in
 *   - htmlname:        (string)    The html fieldname under which the date value will be submitted
 *   - dateformat:      (string)    The dateformat to use for displaying the chosen date
 *   - ifformat:        (string)    Format of the date field sent in the form (optional - defaults to dateformat)
 *   - defaultstring    (string)    The String to display before a value has been selected
 *   - defaultdate:     (string)    The Date the calendar should to default to (format: Y/m/d)
 *   - hidden:          (bool)      If set, a hidden input field will be generated to hold the selected date
 *   - display:         (bool)      If set, a <span> is generated to display the selected date (when date is added in a hidden field)
 *   - class:           (string)    The class to apply to the html elements
 *   - time:            (bool)      If set, show time selection
 *
 * Example:
 *
 * <samp>{calendarinput objectname='myobject' htmlname='from' dateformat='%Y-%m-%d' defaultdate='2005/12/31'}</samp>
 *
 * @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 The HTML and Javascript code to display a calendar control.
 */
function smarty_function_calendarinput($params, Zikula_View $view)
{
    if (!isset($params['objectname'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('pncalendarinput', 'objectname')));
        return false;
    }
    if (!isset($params['htmlname'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('pncalendarinput', 'htmlname')));
        return false;
    }
    if (!isset($params['dateformat'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('pncalendarinput', 'dateformat')));
        return false;
    }
    $ifformat = isset($params['ifformat']) ? $params['ifformat'] : $params['dateformat'];
    $inctime = isset($params['time']) ? (bool) $params['time'] : false;
    $validformats = array('%Y-%m-%d', '%Y-%m-%d %H:%M');
    if (!in_array($ifformat, $validformats)) {
        $ifformat = $inctime ? '%Y-%m-%d %H:%M' : '%Y-%m-%d';
    }
    // start of old pncalendarinit
    // pagevars make an extra pncalendarinit obsolete, they take care about the fact
    // that the styles/jsvascript do not get loaded multiple times
    static $firstTime = true;
    if ($firstTime) {
        $lang = ZLanguage::transformFS(ZLanguage::getLanguageCode());
        // map of the jscalendar supported languages
        $map = array('ca' => 'ca_ES', 'cz' => 'cs_CZ', 'da' => 'da_DK', 'de' => 'de_DE', 'el' => 'el_GR', 'en-us' => 'en_US', 'es' => 'es_ES', 'fi' => 'fi_FI', 'fr' => 'fr_FR', 'he' => 'he_IL', 'hr' => 'hr_HR', 'hu' => 'hu_HU', 'it' => 'it_IT', 'ja' => 'ja_JP', 'ko' => 'ko_KR', 'lt' => 'lt_LT', 'lv' => 'lv_LV', 'nl' => 'nl_NL', 'no' => 'no_NO', 'pl' => 'pl_PL', 'pt' => 'pt_BR', 'ro' => 'ro_RO', 'ru' => 'ru_RU', 'si' => 'si_SL', 'sk' => 'sk_SK', 'sv' => 'sv_SE', 'tr' => 'tr_TR');
        if (isset($map[$lang])) {
            $lang = $map[$lang];
        }
        $headers[] = 'javascript/jscalendar/calendar.js';
        if (file_exists("javascript/jscalendar/lang/calendar-{$lang}.utf8.js")) {
            $headers[] = "javascript/jscalendar/lang/calendar-{$lang}.utf8.js";
        }
        $headers[] = 'javascript/jscalendar/calendar-setup.js';
        PageUtil::addVar('stylesheet', 'javascript/jscalendar/calendar-win2k-cold-2.css');
        PageUtil::addVar('javascript', $headers);
    }
    $firstTime = false;
    // end of old pncalendarinit
    if (!isset($params['defaultstring'])) {
        $params['defaultstring'] = null;
    }
    if (!isset($params['defaultdate'])) {
        $params['defaultdate'] = null;
    }
    $html = '';
    $fieldKey = $params['htmlname'];
    if ($params['objectname']) {
        $fieldKey = $params['objectname'] . '[' . $params['htmlname'] . ']';
    }
    $triggerName = 'trigger_' . $params['htmlname'];
    $displayName = 'display_' . $params['htmlname'];
    if (isset($params['class']) && !empty($params['class'])) {
        $params['class'] = ' class="' . DataUtil::formatForDisplay($params['class']) . '"';
    } else {
        $params['class'] = '';
    }
    if (isset($params['display']) && $params['display']) {
        $html .= '<span id="' . $displayName . '"' . $params['class'] . '>' . $params['defaultstring'] . '</span>&nbsp;';
    }
    if (isset($params['hidden']) && $params['hidden']) {
        $html .= '<input type="hidden" name="' . $fieldKey . '" id="' . $params['htmlname'] . '" value="' . $params['defaultdate'] . '" />';
    }
    $html .= '<img class="z-calendarimg" src="' . System::getBaseUrl() . 'javascript/jscalendar/img.gif" id="' . $triggerName . '" style="cursor: pointer;" title="' . DataUtil::formatForDisplay(__('Date selector')) . '"  alt="' . DataUtil::formatForDisplay(__('Date selector')) . '" />';
    $i18n = ZI18n::getInstance();
    $html .= "<script type=\"text/javascript\">\n              // <![CDATA[\n              Calendar.setup(\n              {";
    //$html .= 'ifFormat    : "%Y-%m-%d %H:%M:00",'; // universal format, don't change this!
    $html .= 'ifFormat    : "' . $ifformat . '",';
    $html .= 'inputField  : "' . $params['htmlname'] . '",';
    $html .= 'displayArea : "' . $displayName . '",';
    $html .= 'daFormat    : "' . $params['dateformat'] . '",';
    $html .= 'button      : "' . $triggerName . '",';
    $html .= 'defaultDate : "' . $params['defaultdate'] . '",';
    $html .= 'firstDay    : "' . $i18n->locale->getFirstweekday() . '",';
    $html .= 'align       : "Tl",';
    if (isset($params['defaultdate']) && $params['defaultdate']) {
        $d = strtotime($params['defaultdate']);
        $d = date('Y/m/d', $d);
        $html .= 'date : "' . $d . '",';
    }
    if ($inctime) {
        $html .= 'showsTime  : true,';
        $html .= 'timeFormat : "' . $i18n->locale->getTimeformat() . '",';
    }
    $html .= "singleClick : true });\n              // ]]>\n              </script>";
    return $html;
}
Example #30
0
    public function view($args) {
        $statsSaved = unserialize(SessionUtil::getVar('statsSaved'));

        $registered = (isset($statsSaved['registered'])) ? $statsSaved['registered'] : 0;
        $moduleId = (isset($statsSaved['moduleId'])) ? $statsSaved['moduleId'] : 0;
        $ip = (isset($statsSaved['ip'])) ? $statsSaved['ip'] : 0;

        $startnum = FormUtil::getPassedValue('startnum', isset($args['startnum']) ? $args['startnum'] : 1, 'GETPOST');
        $moduleId = FormUtil::getPassedValue('moduleId', isset($args['moduleId']) ? $args['moduleId'] : $moduleId, 'GETPOST');
        $uname = FormUtil::getPassedValue('uname', isset($args['uname']) ? $args['uname'] : $statsSaved['uname'], 'GETPOST');
        $ip = FormUtil::getPassedValue('ip', isset($args['ip']) ? $args['ip'] : $ip, 'GETPOST');
        $registered = FormUtil::getPassedValue('registered', isset($args['registered']) ? $args['registered'] : $registered, 'GETPOST');
        $reset = FormUtil::getPassedValue('reset', isset($args['reset']) ? $args['reset'] : 0, 'GET');
        $fromDate = FormUtil::getPassedValue('fromDate', isset($args['fromDate']) ? $args['fromDate'] : null, 'GETPOST');
        $toDate = FormUtil::getPassedValue('toDate', isset($args['toDate']) ? $args['toDate'] : null, 'GETPOST');

        SessionUtil::setVar('statsSaved', serialize(array('moduleId' => $moduleId,
                    'uname' => $uname,
                    'ip' => $ip,
                    'registered' => $registered,
                )));

        if ($reset == 1) {
            $ip = null;
            $uname = null;
            $registered = 0;
            $moduleId = 0;
            SessionUtil::delVar('statsSaved');
        }

        if (!SecurityUtil::checkPermission('IWstats::', '::', ACCESS_ADMIN)) {
            throw new Zikula_Exception_Forbidden();
        }

        $uid = 0;
        $rpp = 50;
        $lastDays = 10;

        if ($uname != null && $uname != '') {
            // get user id from uname
            $uid = UserUtil::getIdFromName($uname);
            if (!$uid) {
                LogUtil::registerError(__f('User \'%s\' not found', array($uname)));
                $uname = '';
            }
        }

        $time = time();

        if ($fromDate != null) {
            $fromDate = mktime(0, 0, 0, substr($fromDate, 3, 2), substr($fromDate, 0, 2), substr($fromDate, 6, 4));
            $fromDate = date('Y-m-d 00:00:00', $fromDate);
            $fromDate = DateUtil::makeTimestamp($fromDate);
            $fromDate = date('d-m-Y', $fromDate);
        } else {
            $fromDate = date('d-m-Y', $time - $lastDays * 24 * 60 * 60);
        }

        if ($toDate != null) {
            $toDate = mktime(0, 0, 0, substr($toDate, 3, 2), substr($toDate, 0, 2), substr($toDate, 6, 4));
            $toDate = date('Y-m-d 00:00:00', $toDate);
            $toDate = DateUtil::makeTimestamp($toDate);
            $toDate = date('d-m-Y', $toDate);
        } else {
            $toDate = date('d-m-Y', $time);
        }

        // get last records
        $records = ModUtil::apiFunc('IWstats', 'user', 'getAllRecords', array('rpp' => $rpp,
                    'init' => $startnum,
                    'moduleId' => $moduleId,
                    'uid' => $uid,
                    'ip' => $ip,
                    'registered' => $registered,
                    'fromDate' => $fromDate,
                    'toDate' => $toDate,
                ));

        // get last records
        $nRecords = ModUtil::apiFunc('IWstats', 'user', 'getAllRecords', array('onlyNumber' => 1,
                    'moduleId' => $moduleId,
                    'uid' => $uid,
                    'ip' => $ip,
                    'registered' => $registered,
                    'fromDate' => $fromDate,
                    'toDate' => $toDate,
                ));

        $usersList = '';
        foreach ($records as $record) {
            if ($record['params'] != '') {
                $valueArray = array();
                $paramsArray = explode('&', $record['params']);
                foreach ($paramsArray as $param) {
                    $value = explode('=', $param);
                    $valueArray[$value[0]] = $value[1];
                }
                if ($record['moduleid'] > 0) {
                    $records[$record['statsid']]['func'] = (isset($valueArray['func'])) ? $valueArray['func'] : 'main';
                    $records[$record['statsid']]['type'] = (isset($valueArray['type'])) ? $valueArray['type'] : 'user';
                } else {
                    $records[$record['statsid']]['func'] = '';
                    $records[$record['statsid']]['type'] = '';
                }

                $params = '';
                foreach ($valueArray as $key => $v) {
                    if ($key != 'module' && $key != 'func' && $key != 'type') {
                        $params .= $key . '=' . $v . '&';
                    }
                }
            } else {
                $params = '';
                if ($record['moduleid'] > 0) {
                    $records[$record['statsid']]['func'] = 'main';
                    $records[$record['statsid']]['type'] = 'user';
                } else {
                    $records[$record['statsid']]['func'] = '';
                    $records[$record['statsid']]['type'] = '';
                }
            }

            $params = str_replace('%3F', '?', $params);
            $params = str_replace('%3D', '=', $params);
            $params = str_replace('%2F', '/', $params);
            $params = str_replace('%26', '&', $params);
            $params = str_replace('%7E', '~', $params);

            $records[$record['statsid']]['params'] = substr($params, 0, -1);

            $usersList .= $record['uid'] . '$$';
        }

        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
        $users = ModUtil::func('IWmain', 'user', 'getAllUsersInfo', array('info' => 'ncc',
                    'sv' => $sv,
                    'list' => $usersList));

        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
        $usersMails = ModUtil::func('IWmain', 'user', 'getAllUsersInfo', array('info' => 'l',
                    'sv' => $sv,
                    'list' => $usersList));

        $users[0] = $this->__('Unregistered');

        // get all modules
        $modules = ModUtil::apiFunc('Extensions', 'admin', 'listmodules', array('state' => 0));

        $skippedModulesArray = unserialize(ModUtil::getVar('IWstats', 'modulesSkipped'));
        $modulesNames = array();
        $modulesArray = array();
        if (!is_array($skippedModulesArray))
            $skippedModulesArray = array();
        foreach ($modules as $module) {
            if (!in_array($module['id'], $skippedModulesArray)) {
                $modulesNames[$module['id']] = $module['name'];
                $modulesArray[] = array('id' => $module['id'],
                    'name' => $module['name']);
            }
        }

        // Create output object
        return $this->view->assign('records', $records)
                        ->assign('users', $users)
                        ->assign('usersMails', $usersMails)
                        ->assign('pager', array('numitems' => $nRecords, 'itemsperpage' => $rpp))
                        ->assign('modulesNames', $modulesNames)
                        ->assign('modulesArray', $modulesArray)
                        ->assign('moduleId', $moduleId)
                        ->assign('url', System::getBaseUrl())
                        ->assign('uname', $uname)
                        ->assign('registered', $registered)
                        ->assign('fromDate', $fromDate)
                        ->assign('toDate', $toDate)
                        ->assign('maxDate', date('Ymd', time()))
                        ->fetch('IWstats_admin_view.htm');
    }