Ejemplo n.º 1
0
 /**
  * Handles an error.
  *
  * @param integer $errno      Number of the error.
  * @param string  $errstr     Error message.
  * @param string  $errfile    Filename where the error occurred.
  * @param integer $errline    Line of the error.
  * @param string  $errcontext Context of the error.
  *
  * @return boolean
  */
 public function handler($errno, $errstr, $errfile = '', $errline = 0, $errcontext = null)
 {
     $this->setupHandler($errno, $errstr, $errfile, $errline, $errcontext);
     // Notify all loggers
     $this->eventManager->notify($this->event->setArgs(array('trace' => $this->trace, 'type' => $this->type, 'errno' => $this->errno, 'errstr' => $this->errstr, 'errfile' => $this->errfile, 'errline' => $this->errline, 'errcontext' => $this->errcontext)));
     if ($this->isPHPError() && System::isDevelopmentMode() && $this->showPHPErrorHandler()) {
         // allow PHP to return error
         $this->resetHandler();
         return false;
     }
     if (!$this->isDisplayErrorTemplate()) {
         // prevent PHP from handling the event after we return
         $this->resetHandler();
         return true;
     }
     // obey reporing level
     if (abs($this->getType()) > $this->serviceManager['log.display_level']) {
         return false;
     }
     // unless in development mode, exit.
     if (!$this->serviceManager['log.display_template']) {
         return false;
     }
     // if we get this far, display template
     echo ModUtil::func('Errors', 'user', 'system', array('type' => $this->errno, 'message' => $this->errstr, 'file' => $this->errfile, 'line' => $this->errline));
     Zikula_View_Theme::getInstance()->themefooter();
     System::shutDown();
 }
Ejemplo n.º 2
0
 /**
  * Inialise a Doctrine 1 connection.
  *
  * Listens for 'doctrine.init_connection' events.
  *
  * Event arguments are:
  * boolean 'lazy'  - lazy connect.
  * string 'name' - connection name.
  *
  * @param Zikula_Event $event Event.
  *
  * @return void
  */
 public function doctrineInit(Zikula_Event $event)
 {
     if (!$this->doctrineManager) {
         Doctrine_Core::debug(System::isDevelopmentMode());
         $this->doctrineManager = Doctrine_Manager::getInstance();
         $internalEvent = new Zikula_Event('doctrine.configure', $this->doctrineManager);
         $this->eventManager->notify($internalEvent);
         $internalEvent = new Zikula_Event('doctrine.cache', $this->doctrineManager);
         $this->eventManager->notify($internalEvent);
     }
     $lazyConnect = isset($event['lazy']) ? $event['lazy'] : false;
     $name = isset($event['name']) ? $event['name'] : 'default';
     $connectionInfo = $this->serviceManager['databases'][$name];
     // test the DB connection works or just set lazy
     try {
         if ($lazyConnect) {
             $dsn = "{$connectionInfo['dbdriver']}://{$connectionInfo['user']}:{$connectionInfo['password']}@{$connectionInfo['host']}/{$connectionInfo['dbname']}";
             $connection = Doctrine_Manager::connection($dsn, $name);
         } else {
             $dbh = new PDO("{$connectionInfo['dbdriver']}:host={$connectionInfo['host']};dbname={$connectionInfo['dbname']}", $connectionInfo['user'], $connectionInfo['password']);
             $connection = Doctrine_Manager::connection($dbh, $name);
             $connection->setOption('username', $connectionInfo['user']);
             $connection->setOption('password', $connectionInfo['password']);
         }
         $internalEvent = new Zikula_Event('doctrine.configure', $connection);
         $this->eventManager->notify($internalEvent);
     } catch (PDOException $e) {
         throw new PDOException(__('Connection failed to database') . ': ' . $e->getMessage());
     }
     // set mysql engine type
     if ($connectionInfo['dbdriver'] == 'mysql') {
         $connection->setAttribute(Doctrine_Core::ATTR_DEFAULT_TABLE_TYPE, $connectionInfo['dbtabletype']);
     }
     try {
         if (isset($connectionInfo['charset'])) {
             $connection->setCharset($connectionInfo['charset']);
         }
         if (isset($connectionInfo['collate'])) {
             $connection->setCollate($connectionInfo['collate']);
         }
     } catch (Exception $e) {
         //if (!System::isInstalling()) {
         //    throw new Exception(__('Error setting database characterset and collation.'));
         //}
     }
     if ($connectionInfo['dbdriver'] != 'oracle') {
         $connection->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_ALL ^ Doctrine_Core::PORTABILITY_EMPTY_TO_NULL);
     }
     if (isset($this->serviceManager['log.enabled']) && $this->serviceManager['log.enabled']) {
         // add listener that sends events for all sql queries
         $connection->setListener(new Zikula_Doctrine_Listener_Profiler());
     }
     $event->data = $connection;
 }
Ejemplo n.º 3
0
 /**
  * Upgrade the MUVideo application from an older version.
  *
  * If the upgrade fails at some point, it returns the last upgraded version.
  *
  * @param integer $oldVersion Version to upgrade from.
  *
  * @return boolean True on success, false otherwise.
  */
 public function upgrade($oldVersion)
 {
     // Upgrade dependent on old version number
     switch ($oldVersion) {
         case '1.0.0':
             // update the database schema
             try {
                 DoctrineHelper::updateSchema($this->entityManager, $this->listEntityClasses());
             } catch (\Exception $e) {
                 if (System::isDevelopmentMode()) {
                     return LogUtil::registerError($this->__('Doctrine Exception: ') . $e->getMessage());
                 }
                 return LogUtil::registerError($this->__f('An error was encountered while updating tables for the %s extension.', array($this->getName())));
             }
             $categoryRegistryIdsPerEntity = array();
             // add default entry for category registry (property named Main)
             include_once 'modules/MUVideo/lib/MUVideo/Api/Base/Category.php';
             include_once 'modules/MUVideo/lib/MUVideo/Api/Category.php';
             $categoryApi = new MUVideo_Api_Category($this->serviceManager);
             $categoryGlobal = CategoryUtil::getCategoryByPath('/__SYSTEM__/Modules/Global');
             $registryData = array();
             $registryData['modname'] = $this->name;
             $registryData['table'] = 'Collection';
             $registryData['property'] = $categoryApi->getPrimaryProperty(array('ot' => 'Collection'));
             $registryData['category_id'] = $categoryGlobal['id'];
             $registryData['id'] = false;
             if (!DBUtil::insertObject($registryData, 'categories_registry')) {
                 LogUtil::registerError($this->__f('Error! Could not create a category registry for the %s entity.', array('collection')));
             }
             $categoryRegistryIdsPerEntity['collection'] = $registryData['id'];
             $registryData = array();
             $registryData['modname'] = $this->name;
             $registryData['table'] = 'Movie';
             $registryData['property'] = $categoryApi->getPrimaryProperty(array('ot' => 'Movie'));
             $registryData['category_id'] = $categoryGlobal['id'];
             $registryData['id'] = false;
             if (!DBUtil::insertObject($registryData, 'categories_registry')) {
                 LogUtil::registerError($this->__f('Error! Could not create a category registry for the %s entity.', array('movie')));
             }
             $categoryRegistryIdsPerEntity['movie'] = $registryData['id'];
             // unregister persistent event handlers
             EventUtil::unregisterPersistentModuleHandlers($this->name);
             // register persistent event handlers
             $this->registerPersistentEventHandlers();
         case '1.1.0':
             // for later updates
     }
     // update successful
     return true;
 }
Ejemplo n.º 4
0
 /**
  * Display an error
  * This function displays a generic error form
  * The template used is based on the error type passed
  *
  * @param string $args['type'] error type '404' or 'module'
  * @param string $args['message'] custom error message
  *
  * @return string HTML string
  */
 public function main($args)
 {
     $type = FormUtil::getPassedValue('errtype', isset($args['type']) ? $args['type'] : LogUtil::getErrorType(), 'GET');
     $exception = isset($args['exception']) ? $args['exception'] : null;
     $message = isset($args['message']) ? $args['message'] : '';
     // perform any error specific tasks
     $protocol = System::serverGetVar('SERVER_PROTOCOL');
     switch ($type) {
         case 301:
             header("{$protocol} 301 Moved Permanently");
             break;
         case 403:
             header("{$protocol} 403 Access Denied");
             break;
         case 404:
             header("{$protocol} 404 Not Found");
             break;
         case 500:
             header("{$protocol} 500 Internal Server Error");
         default:
     }
     // load the stylesheet
     PageUtil::addVar('stylesheet', 'system/Errors/style/style.css');
     $this->view->setCaching(Zikula_View::CACHE_DISABLED);
     // assign the document info
     $this->view->assign('reportlevel', System::getVar('reportlevel'))->assign('currenturi', System::getCurrentUri())->assign('localreferer', System::localReferer())->assign('sitename', System::getVar('sitename'))->assign('reportlevel', System::getVar('reportlevel'))->assign('funtext', System::getVar('funtext'));
     $messages = LogUtil::getErrorMessages();
     // show the detailed error message for admins only
     if (System::isDevelopmentMode() || SecurityUtil::checkPermission('::', '::', ACCESS_ADMIN)) {
         $message ? $messages[] = $message : null;
     }
     $trace = array();
     if (System::isDevelopmentMode() && $exception instanceof Exception) {
         $line = $exception->getLine();
         $file = $exception->getFile();
         $trace = array(0 => '#0 ' . $this->__f('Exception thrown in %1$s, line %2$s.', array($file, $line)));
         $trace += explode("\n", $exception->getTraceAsString());
     }
     // assign the list of registered errors
     // and the trace (if development mode is enabled)
     $this->view->assign('messages', $messages)->assign('trace', $trace);
     // return the template output
     if ($this->view->template_exists($template = "errors_user_{$type}.tpl")) {
         return $this->view->fetch($template);
     } else {
         return $this->view->fetch('errors_user_main.tpl');
     }
 }
Ejemplo n.º 5
0
/**
 * Zikula_View function to display a Zikula specific debug Zikula.UI.Window
 *
 * This function shows a Zikula debug window if the user has sufficient access rights
 *
 * You need the following permission to see this:
 *   ModuleName::debug | .* | ACCESS_ADMIN
 *
 * This plugin is basing on the original debug plugin written by Monte Ohrt <*****@*****.**>
 *
 * Examples
 *   { zdebug }
 *   { zdebug width='400' }
 *
 * Parameters:
 *  width:      Width of the console UI.Window (default: 580)
 *  height:     Height of the console UI.Window (default: 600)
 *  checkpermission: If false, then a security check is not performed, allowing debug information to
 *              be displayed, for example, when there is no user logged in. Development mode
 *              must also be enabled. Defaults to true;
 *  template Specify different debug template, default zdebug.tpl,
 *              must be stored in system/Theme/templates.
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return string Debug output.
 */
function smarty_function_zdebug($params, Zikula_View $view)
{
    $zdebug = '';
    $thismodule = ModUtil::getName();
    $skipPermissionCheck = System::isDevelopmentMode() && isset($params['checkpermission']) && !$params['checkpermission'];

    if ($skipPermissionCheck || SecurityUtil::checkPermission($thismodule.'::debug', '::', ACCESS_ADMIN)) {
        // backup and modify the view attributes
        $_template_dir_orig = $view->template_dir;
        $_default_resource_type_orig = $view->default_resource_type;
        $_compile_id_orig   = $view->_compile_id;

        $view->template_dir = 'system/Theme/templates';
        $view->default_resource_type = 'file';
        $view->_plugins['outputfilter'] = null;
        $view->_compile_id  = null;

        $width  = isset($params['width']) && is_integer($params['width']) ? $params['width'] : 580;
        $height = isset($params['height']) && is_integer($params['height']) ? $params['height'] : 600;
        $popup  = isset($params['popup']) ? (bool)$params['popup'] : false;

        // figure out the template to use
        if (isset($params['template']) && !empty($params['template'])) {
            if (is_readable($view->template_dir . '/' . $params['template'])) {
                $view->debug_tpl = $params['template'];
            }
        } else {
            $view->debug_tpl = $popup ? 'zpopup.tpl' : 'zdebug.tpl';
        }

        // get the zdebug output
        $zdebug = $view->assign('zdebugwidth', $width)
                       ->assign('zdebugheight', $height)
                       ->assign('zdebugpopup', $popup)
                       ->_fetch($view->debug_tpl);

        // restore original values
        $view->_compile_id = $_compile_id_orig;
        $view->template_dir = $_template_dir_orig;
        $view->default_resource_type = $_default_resource_type_orig;
    }

    return $zdebug;
}
Ejemplo n.º 6
0
 /**
  * Set a session variable.
  *
  * @param string  $name                 Name of the session variable to set.
  * @param string  $value                Value to set the named session variable.
  * @param string  $path                 Path to traverse to reach the element we wish to return (optional) (default='/').
  * @param boolean $autocreate           Whether or not to autocreate the supplied path (optional) (default=true).
  * @param boolean $overwriteExistingVar Whether or not to overwrite existing/set variable entries which the given path requires to be arrays (optional) (default=false).
  *
  * @return boolean true upon success, false upon failure.
  */
 public static function setVar($name, $value, $path = '/', $autocreate = true, $overwriteExistingVar = false)
 {
     $session = ServiceUtil::getManager()->getService('session');
     if (($name == 'errormsg' || $name == 'statusmsg' || $name == '_ZErrorMsg' || $name == '_ZStatusMsg') && !is_array($value)) {
         if (System::isDevelopmentMode()) {
             LogUtil::log(__("Error! This use of 'SessionUtil::setVar()' is no longer valid. Please use the LogUtil API to manipulate status messages and error messages."));
         }
         if ($name == '_ZErrorMsg' || $name == 'errormsg') {
             return LogUtil::registerError($value);
         }
         if ($name == '_ZStatusMsg' || $name == 'statusmsg') {
             return LogUtil::registerStatus($value);
         }
     }
     if ($name == 'uid') {
         $session->regenerate();
     }
     return $session->set($name, $value, $path);
 }
Ejemplo n.º 7
0
 /**
  * Upgrade the MUBoard application from an older version.
  *
  * If the upgrade fails at some point, it returns the last upgraded version.
  *
  * @param integer $oldversion Version to upgrade from.
  *
  * @return boolean True on success, false otherwise.
  */
 public function upgrade($oldversion)
 {
     // Upgrade dependent on old version number
     switch ($oldversion) {
         case '1.0.0':
             // nothing to do
             // update the database schema
             try {
                 DoctrineHelper::updateSchema($this->entityManager, $this->listEntityClasses());
             } catch (Exception $e) {
                 if (System::isDevelopmentMode()) {
                     LogUtil::registerError($this->__('Doctrine Exception: ') . $e->getMessage());
                 }
                 return LogUtil::registerError($this->__f('An error was encountered while dropping the tables for the %s module.', array($this->getName())));
             }
             $this->setVar('showStatisticInDetails', true);
             $this->setVar('showStatisticOnBottom', false);
         case '1.1.0':
             // for later updates
     }
     // update successful
     return true;
 }
Ejemplo n.º 8
0
 /**
  * Load all plugins in path.
  *
  * @param string $path      Path.
  * @param string $namespace Namespace.
  *
  * @throws RuntimeException If file does not exist.
  * @return void
  */
 public static function loadPlugins($path, $namespace)
 {
     static $loaded;
     $path = realpath($path);
     if (isset($loaded[$path])) {
         return;
     }
     $it = FileUtil::getFiles($path, false, false, null, 'd');
     foreach ($it as $dir) {
         if (strrpos($dir, 'Doctrine')) {
             // todo consider removing this condition - drak
             die('Please delete plugins/Doctrine and plugins/DoctrineExtensions folders - they have been deprecated');
         }
         $file = $dir . DIRECTORY_SEPARATOR . 'Plugin.php';
         if (!file_exists($file)) {
             // silently ignore non-compliant folders
             if (!System::isDevelopmentMode()) {
                 break;
             }
             throw new RuntimeException(sprintf('%s must exist', $file));
         }
         include_once $file;
         $p = explode(DIRECTORY_SEPARATOR, $dir);
         $dir = end($p);
         prev($p);
         $module = prev($p);
         $className = "{$namespace}_{$dir}_Plugin";
         self::loadPlugin($className);
     }
     $loaded[$path] = true;
 }
Ejemplo n.º 9
0
    /**
     * Load a block.
     *
     * @param string $modname Module name.
     * @param string $block   Name of the block.
     *
     * @throws LogicException Uf OO-Block is not a Zikula_Controller_AbstractBlock object.
     * @return bool True on successful load, false otherwise.
     */
    public static function load($modname, $block)
    {
        $sm = ServiceUtil::getManager();
        $modinfo = ModUtil::getInfoFromName($modname);

        $serviceId = strtolower('block.' . $modinfo['name'] . '_' . 'Block_' . $block);
        if ($sm->hasService($serviceId)) {
            return $sm->getService($serviceId);
        }

        if ($modinfo['type'] == ModUtil::TYPE_MODULE) {
            ZLanguage::bindModuleDomain($modinfo['name']);
        }

        $basedir = ($modinfo['type'] == ModUtil::TYPE_SYSTEM) ? 'system' : 'modules';
        $moddir = DataUtil::formatForOS($modinfo['directory']);
        $blockdir = "$basedir/$moddir/lib/$moddir/Block";
        $ooblock = "$blockdir/" . ucwords($block) . '.php';
        ModUtil::load($modname);
        $isOO = ModUtil::isOO($modname);

        if (!$isOO) {
            $blockdirOld = $moddir . '/pnblocks';
            $incfile = DataUtil::formatForOS($block . '.php');

            if (file_exists("$basedir/$blockdirOld/$incfile")) {
                include_once "$basedir/$blockdirOld/$incfile";
            } else {
                return false;
            }
        }

        // get the block info
        if ($isOO) {
            $className = ucwords($modinfo['name']) . '_' . 'Block_' . ucwords($block);
            $r = new ReflectionClass($className);
            $blockInstance = $r->newInstanceArgs(array($sm));
            try {
                if (!$blockInstance instanceof Zikula_Controller_AbstractBlock) {
                    throw new LogicException(sprintf('Block %s must inherit from Zikula_Controller_AbstractBlock', $className));
                }
            } catch (LogicException $e) {
                if (System::isDevelopmentMode()) {
                    throw $e;
                } else {
                    LogUtil::registerError('A fatal error has occured which can be viewed only in development mode.', 500);
                    return false;
                }
            }

            $sm->attachService($serviceId, $blockInstance);
        }

        $result = ($isOO ? $blockInstance : true);

        if ($isOO) {
            $blocks_modules[$block] = call_user_func(array($blockInstance, 'info'));
        } else {
            $infofunc = "{$modname}_{$block}block_info";
            $blocks_modules[$block] = $infofunc();
        }

        // set the module and keys for the new block
        $blocks_modules[$block]['bkey'] = $block;
        $blocks_modules[$block]['module'] = $modname;
        $blocks_modules[$block]['mid'] = ModUtil::getIdFromName($modname);

        // merge the blockinfo in the global list of blocks
        if (!isset($GLOBALS['blocks_modules'])) {
            $GLOBALS['blocks_modules'] = array();
        }
        $GLOBALS['blocks_modules'][$blocks_modules[$block]['mid']][$block] = $blocks_modules[$block];

        // Initialise block if required (new-style)
        if ($isOO) {
            call_user_func(array($blockInstance, 'init'));
        } else {
            $initfunc = "{$modname}_{$block}block_init";
            $initfunc();
        }

        // add stylesheet to the page vars, this makes manual loading obsolete
        PageUtil::addVar('stylesheet', ThemeUtil::getModuleStylesheet($modname));

        return $result;
    }
Ejemplo n.º 10
0
 /**
  * An array with a list of core scripts.
  *
  * For each script can be defined:
  * - path: the true path to the file
  * - require: other scripts to be loaded along with the file (aliases for core, paths for other)
  * - aliases: aliases used for this script
  * - styles: information about additional files (styles) that should be loaded along with the script
  * - gettext: if script requires a translations
  *
  * When System::isDevelopmentMode precombined versions of scripts (prototype, livepipe and jquery)
  * are replaced by original, uncompressed files
  *
  * @return array List of core scripts
  */
 public static function scriptsMap()
 {
     $scripts = array('prototype' => array('path' => 'javascript/ajax/proto_scriptaculous.combined.min.js', 'require' => array('zikula'), 'aliases' => array('prototype', 'scriptaculous')), 'jquery' => array('path' => 'web/jquery/jquery.min.js', 'require' => array('noconflict', 'jquery-migrate')), 'jquery-ui' => array('path' => 'web/jquery-ui/jquery-ui.min.js', 'require' => array('jquery')), 'noconflict' => array('path' => 'javascript/jquery_config.js'), 'jquery-migrate' => array('path' => 'web/jquery/jquery-migrate.min.js'), 'livepipe' => array('path' => 'javascript/livepipe/livepipe.combined.min.js', 'require' => array('prototype')), 'zikula' => array('path' => 'javascript/helpers/Zikula.js', 'require' => array('prototype'), 'aliases' => array('javascript/ajax/ajax.js')), 'zikula.ui' => array('path' => 'javascript/helpers/Zikula.UI.js', 'require' => array('prototype', 'livepipe', 'zikula'), 'styles' => array('javascript/helpers/Zikula.UI.css'), 'gettext' => true), 'zikula.imageviewer' => array('path' => 'javascript/helpers/Zikula.ImageViewer.js', 'require' => array('prototype', 'zikula'), 'styles' => array('javascript/helpers/ImageViewer/ImageViewer.css'), 'aliases' => array('imageviewer', 'lightbox'), 'gettext' => true), 'zikula.itemlist' => array('path' => 'javascript/helpers/Zikula.itemlist.js', 'require' => array('prototype', 'zikula')), 'zikula.tree' => array('path' => 'javascript/helpers/Zikula.Tree.js', 'require' => array('prototype', 'zikula'), 'styles' => array('javascript/helpers/Tree/Tree.css')), 'validation' => array('path' => 'javascript/ajax/validation.min.js', 'require' => array('prototype')), 'polyfill' => array('path' => 'javascript/js-webshim/minified/polyfiller.js', 'require' => array('jquery', 'polyfill.init')), 'polyfill.init' => array('path' => 'javascript/js-webshim/minified/polyfiller.init.js'));
     if (System::isDevelopmentMode()) {
         $prototypeUncompressed = array('prototype' => array('path' => 'javascript/ajax/original_uncompressed/prototype.js', 'require' => array('zikula', 'builder', 'controls', 'dragdrop', 'effects', 'slider', 'sound'), 'aliases' => array('prototype', 'scriptaculous')), 'scriptaculous' => array('path' => 'javascript/ajax/original_uncompressed/prototype.js', 'require' => array('prototype')), 'effects' => array('path' => 'javascript/ajax/original_uncompressed/effects.js'), 'builder' => array('path' => 'javascript/ajax/original_uncompressed/builder.js'), 'controls' => array('path' => 'javascript/ajax/original_uncompressed/controls.js'), 'dragdrop' => array('path' => 'javascript/ajax/original_uncompressed/dragdrop.js'), 'slider' => array('path' => 'javascript/ajax/original_uncompressed/slider.js'), 'sound' => array('path' => 'javascript/ajax/original_uncompressed/sound.js'));
         $livepipeUncompressed = array('livepipe' => array('path' => 'javascript/livepipe/original_uncompressed/livepipe.js', 'require' => array('prototype', 'contextmenu', 'cookie', 'event_behavior', 'hotkey', 'progressbar', 'rating', 'resizable', 'scrollbar', 'selection', 'selectmultiple', 'tabs', 'textarea', 'window')), 'contextmenu' => array('path' => 'javascript/livepipe/original_uncompressed/contextmenu.js'), 'cookie' => array('path' => 'javascript/livepipe/original_uncompressed/cookie.js'), 'event_behavior' => array('path' => 'javascript/livepipe/original_uncompressed/event_behavior.js'), 'hotkey' => array('path' => 'javascript/livepipe/original_uncompressed/hotkey.js'), 'progressbar' => array('path' => 'javascript/livepipe/original_uncompressed/progressbar.js'), 'rating' => array('path' => 'javascript/livepipe/original_uncompressed/rating.js'), 'resizable' => array('path' => 'javascript/livepipe/original_uncompressed/resizable.js'), 'scrollbar' => array('path' => 'javascript/livepipe/original_uncompressed/scrollbar.js'), 'selection' => array('path' => 'javascript/livepipe/original_uncompressed/selection.js'), 'selectmultiple' => array('path' => 'javascript/livepipe/original_uncompressed/selectmultiple.js'), 'tabs' => array('path' => 'javascript/livepipe/original_uncompressed/tabs.js'), 'textarea' => array('path' => 'javascript/livepipe/original_uncompressed/textarea.js'), 'window' => array('path' => 'javascript/livepipe/original_uncompressed/window.js'));
         $jQueryUncompressed = array('jquery' => array('path' => 'web/jquery/jquery.js', 'require' => array('noconflict', 'jquery-migrate')), 'noconflict' => array('path' => 'javascript/jquery_config.js'), 'jquery-migrate' => array('path' => 'web/jquery/jquery-migrate.min.js'));
         $jQueryUiUncompressed = array('jquery-ui' => array('path' => 'web/jquery-ui/jquery-ui.js', 'require' => array('jquery')));
         $polyfillUncompressed = array('polyfill' => array('path' => 'javascript/js-webshim/dev/polyfiller.js', 'require' => array('jquery', 'polyfill.init')), 'polyfill.init' => array('path' => 'javascript/js-webshim/dev/polyfiller.init.js'));
         $scripts = array_merge($prototypeUncompressed, $jQueryUncompressed, $jQueryUiUncompressed, $livepipeUncompressed, array_slice($scripts, 5), $polyfillUncompressed);
     }
     return $scripts;
 }
Ejemplo n.º 11
0
 /**
  * upgrade
  */
 public function upgrade($oldversion)
 {
     // Upgrade dependent on old version number
     switch ($oldversion) {
         case '2.4':
             $prefix = $this->serviceManager['prefix'];
             $connection = Doctrine_Manager::getInstance()->getConnection('default');
             $sql = 'RENAME TABLE ' . $prefix . '_' . 'reviews' . ' TO ' . 'reviews';
             $stmt = $connection->prepare($sql);
             try {
                 $stmt->execute();
             } catch (Exception $e) {
                 LogUtil::registerError($e);
             }
         case '2.4.1':
             try {
                 DoctrineHelper::updateSchema($this->entityManager, $this->listEntityClasses());
             } catch (\Exception $e) {
                 if (System::isDevelopmentMode()) {
                     LogUtil::registerError($this->__('Doctrine Exception: ') . $e->getMessage());
                 }
                 return LogUtil::registerError($this->__f('An error was encountered while dropping the tables for the %s extension.', array($this->getName())));
             }
             $repository = $this->getEntityManager()->getRepository('Reviews_Entity_Review');
             // we get all old entries
             $result = DBUtil::executeSQL('SELECT * FROM `reviews`');
             $reviews = $result->fetchAll(Doctrine::FETCH_ASSOC);
             $dom = ZLanguage::getModuleDomain($this->name);
             $workflowHelper = new Zikula_Workflow('standard', 'Reviews');
             // we get serviceManager
             $serviceManager = ServiceUtil::getManager();
             // we get entityManager
             $entityManager = $serviceManager->getService('doctrine.entitymanager');
             if (count($reviews) > 0) {
                 foreach ($reviews as $key => $review) {
                     $newReview = new Reviews_Entity_Review();
                     $newReview->setWorkflowState('approved');
                     $newReview->setTitle($review['pn_title']);
                     $newReview->setText($review['pn_text']);
                     if ($review['pn_reviewer'] != '') {
                         $newReview->setReviewer($review['pn_reviewer']);
                     } else {
                         $newReview->setReviewer(__('Unknown', $dom));
                     }
                     if ($review['pn_email'] != '') {
                         $newReview->setEmail($review['pn_email']);
                     } else {
                         $adminmail = UserUtil::getVar('email', 2);
                         $newReview->setEmail(__($adminmail));
                     }
                     $newReview->setScore($review['pn_score']);
                     $newReview->setCover($review['pn_cover']);
                     $newReview->setUrl($review['pn_url']);
                     $newReview->setUrl_title($review['pn_url_title']);
                     $newReview->setHits($review['pn_hits']);
                     $newReview->setZlanguage($review['pn_language']);
                     $createdDate = new Datetime($review['pn_cr_date']);
                     $newReview->setCreatedDate($createdDate);
                     $updatedDate = new DateTime($review['pn_lu_date']);
                     $newReview->setUpdatedDate($updatedDate);
                     $newReview->setCreatedUserId($review['pn_cr_uid']);
                     $newReview->setUpdatedUserId($review['pn_lu_uid']);
                     $entityManager->persist($newReview);
                     $entityManager->flush();
                 }
             }
             $result2 = DBUtil::executeSQL('SELECT * FROM `reviews_review`');
             $reviews2 = $result2->fetchAll(Doctrine::FETCH_ASSOC);
             // we set the workflow
             foreach ($reviews2 as $key => $review2) {
                 $obj['__WORKFLOW__']['obj_table'] = 'review';
                 $obj['__WORKFLOW__']['obj_idcolumn'] = 'id';
                 $obj['id'] = $review2['id'];
                 $workflowHelper->registerWorkflow($obj, 'approved');
             }
             // move relations from categories_mapobj to reviews_category
             // then delete old data
             $connection = $this->entityManager->getConnection();
             $sqls = array();
             $sqls[] = "INSERT INTO reviews_review_category (entityId, registryId, categoryId) SELECT obj_id, reg_id, category_id FROM categories_mapobj WHERE modname = 'Reviews' AND tablename = 'reviews'";
             $sqls[] = "DELETE FROM categories_mapobj WHERE modname = 'Reviews' AND tablename = 'reviews'";
             // update category registry data to change tablename to EntityName
             $sqls[] = "UPDATE categories_registry SET tablename = 'Review' WHERE tablename = 'reviews'";
             // do changes
             foreach ($sqls as $sql) {
                 $stmt = $connection->prepare($sql);
                 try {
                     $stmt->execute();
                 } catch (Exception $e) {
                     LogUtil::registerError($e->getMessage());
                 }
             }
             $pagesize = $this->getVar('itemsperpage');
             $this->setVar('pagesize', $pagesize);
             $this->delVar('itemsperpage');
             $this->setVar('scoreForUsers', false);
             $addcategorytitletopermalink = $this->getVar('addcategorytitletopermalink');
             $this->setVar('addcategorytitletopermalink');
             // register persistent event handlers
             $this->registerPersistentEventHandlers();
             // register hook subscriber bundles
             HookUtil::registerSubscriberBundles($this->version->getHookSubscriberBundles());
             DBUtil::dropTable('reviews');
         case '2.5.0':
             // later upgrades
     }
     // upgrade successful
     return true;
 }
Ejemplo n.º 12
0
 /**
  * Uninstall Reviews.
  *
  * @return boolean True on success, false otherwise.
  */
 public function uninstall()
 {
     // delete stored object workflows
     $result = Zikula_Workflow_Util::deleteWorkflowsForModule($this->getName());
     if ($result === false) {
         return LogUtil::registerError($this->__f('An error was encountered while removing stored object workflows for the %s extension.', array($this->getName())));
     }
     try {
         DoctrineHelper::dropSchema($this->entityManager, $this->listEntityClasses());
     } catch (\Exception $e) {
         if (System::isDevelopmentMode()) {
             return LogUtil::registerError($this->__('Doctrine Exception: ') . $e->getMessage());
         }
         return LogUtil::registerError($this->__f('An error was encountered while dropping tables for the %s extension.', array($this->name)));
     }
     // unregister persistent event handlers
     EventUtil::unregisterPersistentModuleHandlers($this->name);
     // unregister hook subscriber bundles
     HookUtil::unregisterSubscriberBundles($this->version->getHookSubscriberBundles());
     // remove all module vars
     $this->delVars();
     // remove category registry entries
     ModUtil::dbInfoLoad('Categories');
     DBUtil::deleteWhere('categories_registry', 'modname = \'' . $this->name . '\'');
     // remove all thumbnails
     $manager = $this->getServiceManager()->getService('systemplugin.imagine.manager');
     $manager->setModule($this->name);
     $manager->cleanupModuleThumbs();
     // remind user about upload folders not being deleted
     $uploadPath = FileUtil::getDataDirectory() . '/' . $this->name . '/';
     LogUtil::registerStatus($this->__f('The upload directories at [%s] can be removed manually.', $uploadPath));
     // uninstallation successful
     return true;
 }
Ejemplo n.º 13
0
 /**
  * Register a Zikula_AbstractEventHandler as a persistent handler.
  *
  * @param string $moduleName Module name.
  * @param string $className  Class name (subclass of Zikula_AbstractEventHandler).
  *
  * @throws InvalidArgumentException If class is not available or not a subclass of Zikula_AbstractEventHandler.
  *
  * @return void
  *
  * Note: If the exact same handler is already registered, this function does nothing.
  */
 public static function registerPersistentEventHandlerClass($moduleName, $className)
 {
     if (!class_exists($className)) {
         throw new InvalidArgumentException(sprintf('Class %s does not exist or cannot be found', $className));
     }
     $reflection = new ReflectionClass($className);
     if (!$reflection->isSubclassOf('Zikula_AbstractEventHandler')) {
         throw new InvalidArgumentException(sprintf('%s is not a subclass of Zikula_AbstractEventHandler', $className));
     }
     $handlers = ModUtil::getVar(self::HANDLERS, $moduleName, array());
     $newHandler = array('classname' => $className);
     foreach ($handlers as $handler) {
         if ($handler == $newHandler) {
             // The exact same handler exists already. Do nothing but display a warning.
             if (System::isDevelopmentMode()) {
                 LogUtil::registerWarning(__f('The eventhandler class "%1$s" for "%2$s" could not be registered because it is registered already.', array($className, $moduleName)));
             } else {
                 $warns = LogUtil::getWarningMessages(false);
                 $msg = __f('The eventhandlers for "%1$s" could not be registered because they are registered already.', array($moduleName));
                 if (!in_array(DataUtil::formatForDisplayHTML($msg), $warns)) {
                     LogUtil::registerWarning($msg);
                 }
             }
             return;
         }
     }
     $handlers[] = $newHandler;
     ModUtil::setVar(self::HANDLERS, $moduleName, $handlers);
 }
Ejemplo n.º 14
0
/**
 * Inject a jQuery Timepicker plugin to the template.
 * @see https://github.com/trentrichardson/jQuery-Timepicker-Addon
 *
 * NOTE: This plugin is NOT configured to integrate the datepicker and timepicker
 *     together as one. It only displays the timepicker.
 *
 * Available attributes:
 *  - see inline docblocks of each parameter
 *  - additionally, one can set any parameter available in the timepicker documentation
 *    however, parameter names and values will not be validated, simply rendered as is.
 *    case in parameter names must be observed! all jQuery parameter values must be strings.
 *    see timepicker docs for options
 *  - regionalization attributes (i18n) are set in most cases automatically
 *
 * Examples:
 *
 *  Displays the timepicker with the current time as default:
 *
 *  <samp>{jquery_timepicker displayelement='time'}</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 required to render the timepicker
 */
function smarty_function_jquery_timepicker($params, Zikula_View $view)
{
    /**
     * defaultdate
     * php DateTime object
     * The initial datetime selected and displayed (default: now)
     */
    $defaultDate = isset($params['defaultdate']) && $params['defaultdate'] instanceof DateTime ? $params['defaultdate'] : new DateTime();
    unset($params['defaultdate']);
    /**
     * displayelement
     * string (do not include the '#' character)
     * (required) The id text of the html element where the timepicker displays the selection
     */
    $displayElement = isset($params['displayelement']) ? $params['displayelement'] : '';
    unset($params['displayelement']);
    /**
     * displayelement_class
     * string
     * (optional) The css class applied to the display element (default: null)
     */
    $displayElement_class = isset($params['displayelement_class']) ? $params['displayelement_class'] : null;
    unset($params['displayelement_class']);
    /**
     * valuestorageelement
     * string (do not include the '#' character)
     * (optional) the id text of the html element where the selected time will be stored (default null)
     * note: storage format is HH:MM (in 24 hour format)
     */
    $valueStorageElement = isset($params['valuestorageelement']) ? $params['valuestorageelement'] : null;
    unset($params['valuestorageelement']);
    /**
     * readonly
     * boolean
     * (optional) whether the display field is readonly of active (default: (boolean)true - IS readonly)
     */
    $readOnly = isset($params['readonly']) ? $params['readonly'] : true;
    unset($params['readonly']);
    /**
     * object
     * string
     * (optional) object name for html element names. e.g. name='myObjectName[myVariable]' (default: null)
     */
    $object = isset($params['object']) ? $params['object'] : null;
    unset($params['object']);
    /**
     * inlinestyle
     * string
     * contents of html style param - useful for setting display:none on load
     */
    $inlineStyle = isset($params['inlinestyle']) ? $params['inlinestyle'] : null;
    unset($params['inlinestyle']);
    /**
     * onclosecallback
     * string
     * (optional) javascript to perform onClose event (default: null)
     */
    $onCloseCallback = isset($params['onclosecallback']) ? $params['onclosecallback'] : null;
    unset($params['onclosecallback']);
    /**
     * theme
     * string
     * (optional) which jquery theme to use for this plugin. Uses JQueryUtil::loadTheme() (default: 'smoothness')
     */
    $jQueryTheme = isset($params['theme']) ? $params['theme'] : 'smoothness';
    unset($params['theme']);
    /**
     * lang
     * string
     * (optional) language of datepicker (default: current system language)
     */
    $lang = isset($params['lang']) ? $params['lang'] : ZLanguage::getLanguageCode();
    unset($params['lang']);
    /**
     * use24hour
     * boolean
     * (optional) use 24 hour time display or 12 hour am/pm (default: false)
     */
    $use24hour = isset($params['use24hour']) ? $params['use24hour'] : false;
    unset($params['use24hour']);
    // compute formats
    if ($use24hour) {
        $jqueryTimeFormat = 'HH:mm';
        $dateTimeFormat = 'G:i';
    } else {
        $jqueryTimeFormat = 'h:mm tt';
        $dateTimeFormat = 'g:i a';
    }
    // load required javascripts
    PageUtil::addVar("javascript", "jquery-ui");
    if (!System::isDevelopmentMode()) {
        PageUtil::addVar("javascript", "javascript/jquery-plugins/jQuery-Timepicker-Addon/jquery-ui-timepicker-addon.min.js");
        PageUtil::addVar("stylesheet", "javascript/jquery-plugins/jQuery-Timepicker-Addon/jquery-ui-timepicker-addon.min.css");
    } else {
        PageUtil::addVar("javascript", "javascript/jquery-plugins/jQuery-Timepicker-Addon/jquery-ui-timepicker-addon.js");
        PageUtil::addVar("stylesheet", "javascript/jquery-plugins/jQuery-Timepicker-Addon/jquery-ui-timepicker-addon.css");
    }
    if (!empty($lang) && $lang != 'en') {
        PageUtil::addVar("javascript", "javascript/jquery-plugins/jQuery-Timepicker-Addon/i18n/jquery-ui-timepicker-{$lang}.js");
    }
    $jQueryTheme = is_dir("web/jquery-ui/themes/{$jQueryTheme}") ? $jQueryTheme : 'smoothness';
    PageUtil::addVar("stylesheet", "web/jquery-ui/themes/{$jQueryTheme}/jquery-ui.css");
    // build the timepicker
    $javascript = "\n        jQuery(document).ready(function() {\n            jQuery('#{$displayElement}').timepicker({";
    // add additional parameters set in template first
    foreach ($params as $param => $value) {
        $javascript .= "\n                {$param}: {$value},";
    }
    // add configured/computed parameters from plugin
    if (isset($onCloseCallback)) {
        $javascript .= "\n                onClose: function(dateText, inst) {" . $onCloseCallback . "},";
    }
    if (isset($valueStorageElement)) {
        addTimepickerFormatTime();
        $javascript .= "\n                onSelect: function(dateText, inst) {\n                    jQuery('#{$valueStorageElement}').attr('value', timepickerFormatTime(jQuery(this).datepicker('getDate')));\n                },";
        //        note: as of v1.4.3, the altField param doesn't work as expected because it is getting it's default time from
        //        somewhere else so, the time in the picker defaults to 00:00 instead of the actual time. So this doesn't work yet:
        //        $javascript .= "
        //                altField: '#$valueStorageElement',
        //                altTimeFormat: 'HH:mm',";
    }
    $javascript .= "\n                timeFormat: '{$jqueryTimeFormat}',\n                parse: 'loose'\n            });\n        });";
    PageUtil::addVar("footer", "<script type='text/javascript'>{$javascript}</script>");
    $readOnlyHtml = $readOnly ? " readonly='readonly'" : "";
    $inlineStyle = isset($inlineStyle) ? " style='{$inlineStyle}'" : '';
    $name = isset($object) ? "{$object}[{$displayElement}]" : $displayElement;
    $class = isset($displayElement_class) ? " class='{$displayElement_class}'" : '';
    $html = "<input type='text'{$readOnlyHtml}{$inlineStyle} id='{$displayElement}'{$class} name='{$name}' value='{$defaultDate->format($dateTimeFormat)}' />\n";
    if (isset($valueStorageElement)) {
        $name = isset($object) ? "{$object}[{$valueStorageElement}]" : $valueStorageElement;
        $html .= "<input type='hidden' id='{$valueStorageElement}' name='{$name}' value='{$defaultDate->format('G:i')}' />\n";
    }
    return $html;
}
Ejemplo n.º 15
0
 /**
  * Get class object.
  *
  * @param string $className Class name.
  *
  * @throws LogicException If $className is neither a Zikula_AbstractApi nor a Zikula_AbstractController.
  * @return object         Module object.
  */
 public static function getObject($className)
 {
     if (!$className) {
         return false;
     }
     $serviceId = strtolower("module.{$className}");
     $sm = ServiceUtil::getManager();
     $callable = false;
     if ($sm->hasService($serviceId)) {
         $object = $sm->getService($serviceId);
     } else {
         $r = new ReflectionClass($className);
         $object = $r->newInstanceArgs(array($sm));
         try {
             if (strrpos($className, 'Api') && !$object instanceof Zikula_AbstractApi) {
                 throw new LogicException(sprintf('Api %s must inherit from Zikula_AbstractApi', $className));
             } elseif (!strrpos($className, 'Api') && !$object instanceof Zikula_AbstractController) {
                 throw new LogicException(sprintf('Controller %s must inherit from Zikula_AbstractController', $className));
             }
         } catch (LogicException $e) {
             if (System::isDevelopmentMode()) {
                 throw $e;
             } else {
                 LogUtil::registerError('A fatal error has occured which can be viewed only in development mode.', 500);
                 return false;
             }
         }
         $sm->attachService(strtolower($serviceId), $object);
     }
     return $object;
 }
Ejemplo n.º 16
0
 /**
  * Uninstall MUBoard.
  *
  * @return boolean True on success, false otherwise.
  */
 public function uninstall()
 {
     // delete stored object workflows
     $result = Zikula_Workflow_Util::deleteWorkflowsForModule($this->getName());
     if ($result === false) {
         return LogUtil::registerError($this->__f('An error was encountered while removing stored object workflows for the %s module.', array($this->getName())));
     }
     try {
         DoctrineHelper::dropSchema($this->entityManager, $this->listEntityClasses());
     } catch (Exception $e) {
         if (System::isDevelopmentMode()) {
             LogUtil::registerError($this->__('Doctrine Exception: ') . $e->getMessage());
         }
         return LogUtil::registerError($this->__f('An error was encountered while dropping the tables for the %s module.', array($this->getName())));
     }
     // unregister persistent event handlers
     EventUtil::unregisterPersistentModuleHandlers('MUBoard');
     // unregister hook subscriber bundles
     HookUtil::unregisterSubscriberBundles($this->version->getHookSubscriberBundles());
     // remove all module vars
     $this->delVars();
     // deletion successful
     return true;
 }
Ejemplo n.º 17
0
 /**
  * Execute SQL, check for errors and return result. Uses Doctrine's DBAL to generate DB-portable paging code.
  *
  * @param string  $sql          The SQL statement to execute.
  * @param integer $limitOffset  The lower limit bound (optional) (default=-1).
  * @param integer $limitNumRows The upper limit bound (optional) (default=-1).
  * @param boolean $exitOnError  Whether to exit on error (default=true) (optional).
  * @param boolean $verbose      Whether to be verbose (default=true) (optional).
  *
  * @return mixed The result set of the successfully executed query or false on error.
  * @throws Exception No SQL statment.
  */
 public static function executeSQL($sql, $limitOffset = -1, $limitNumRows = -1, $exitOnError = true, $verbose = true)
 {
     if (!$sql) {
         throw new Exception(__('No SQL statement to execute'));
     }
     $connection = Doctrine_Manager::getInstance()->getCurrentConnection();
     if (!$connection && System::isInstalling()) {
         return false;
     }
     try {
         if ($limitNumRows > 0) {
             $tStr = strtoupper(substr(trim($sql), 0, 6));
             if ($tStr !== 'SELECT') {
                 // TODO D [use normal Select instead of showing an error message if paging is desired for something different than SELECTs] (Guite)
                 throw new Exception(__('Paging parameters can only be used for SELECT statements'));
             }
             if ($limitOffset > 0) {
                 $sql = $connection->modifyLimitQuery($sql, $limitNumRows, $limitOffset);
             } else {
                 $sql = $connection->modifyLimitQuery($sql, $limitNumRows);
             }
         }
         $stmt = $connection->prepare($sql);
         //$stmt->setHydrationMode(Doctrine_Core::HYDRATE_RECORD);
         if ($stmt->execute()) {
             $result = $stmt;
         }
         if ($result) {
             return $result;
         }
     } catch (Exception $e) {
         echo 'Error in DBUtil::executeSQL: ' . $sql . '<br />' . $e->getMessage() . '<br />';
         if (System::isDevelopmentMode() && SecurityUtil::checkPermission('.*', '.*', ACCESS_ADMIN)) {
             echo nl2br($e->getTraceAsString());
         }
         System::shutDown();
     }
     return false;
 }
Ejemplo n.º 18
0
 /**
  * Adjusts the error file name, removing path information if the system is not in development mode.
  *
  * @param string $errfile The name of the file in which the error was raised.
  *
  * @return The name of the file in which the error was raised, without path information if the system is not in
  *              development mode.
  */
 public function decoratePath($errfile)
 {
     // Remove full path information if not in development mode.
     if (!\System::isDevelopmentMode()) {
         $rootpath = realpath('.') . \DIRECTORY_SEPARATOR;
         if (strpos($errfile, $rootpath)) {
             $errfile = str_replace($rootpath, '', $errfile);
         } else {
             $errfile = basename($errfile);
         }
     }
     return $errfile;
 }
Ejemplo n.º 19
0
 /**
  * Execute SQL, check for errors and return result. Uses Doctrine's DBAL to generate DB-portable paging code.
  *
  * @param string  $sql          The SQL statement to execute.
  * @param integer $limitOffset  The lower limit bound (optional) (default=-1).
  * @param integer $limitNumRows The upper limit bound (optional) (default=-1).
  * @param boolean $exitOnError  Whether to exit on error (default=true) (optional).
  * @param boolean $verbose      Whether to be verbose (default=true) (optional).
  *
  * @return mixed     The result set of the successfully executed query or false on error.
  * @throws Exception No SQL statment.
  */
 public static function executeSQL($sql, $limitOffset = -1, $limitNumRows = -1, $exitOnError = true, $verbose = true)
 {
     if (!$sql) {
         throw new Exception(__('No SQL statement to execute'));
     }
     $connection = Doctrine_Manager::getInstance()->getCurrentConnection();
     if (!$connection && System::isInstalling()) {
         return false;
     }
     try {
         if ($limitNumRows > 0) {
             $tStr = strtoupper(substr(trim($sql), 0, 7));
             // Grab first 7 chars to allow syntax like "(SELECT" which may happen with UNION statements
             if (strpos($tStr, 'SELECT') === false) {
                 // TODO D [use normal Select instead of showing an error message if paging is desired for something different than SELECTs] (Guite)
                 throw new Exception(__('Paging parameters can only be used for SELECT statements'));
             }
             if ($limitOffset > 0) {
                 $sql = $connection->modifyLimitQuery($sql, $limitNumRows, $limitOffset);
             } else {
                 $sql = $connection->modifyLimitQuery($sql, $limitNumRows);
             }
         }
         $stmt = $connection->prepare($sql);
         //$stmt->setHydrationMode(Doctrine_Core::HYDRATE_RECORD);
         if ($stmt->execute()) {
             $result = $stmt;
         }
         if ($result) {
             // catch manual SQL which requires cache flushes
             $tab = null;
             $sql = strtolower(trim(preg_replace("/\\s+/", " ", $sql)));
             if (strpos($sql, 'update') === 0) {
                 list(, $tab, ) = explode(' ', $sql);
             }
             if (strpos($sql, 'delete') === 0) {
                 list(, , $tab, ) = explode(' ', $sql);
             }
             if ($tab && strpos($tab, 'session_info') === false) {
                 self::flushCache($tab);
             }
             return $result;
         }
     } catch (Exception $e) {
         echo 'Error in DBUtil::executeSQL: ' . $sql . '<br />' . $e->getMessage() . '<br />';
         if (System::isDevelopmentMode() && SecurityUtil::checkPermission('.*', '.*', ACCESS_ADMIN)) {
             echo nl2br($e->getTraceAsString());
         }
         if ($exitOnError) {
             System::shutDown();
         }
     }
     return false;
 }
Ejemplo n.º 20
0
 /**
  * Command event handler.
  *
  * This event handler is called when a command is issued by the user. Commands are typically something
  * that originates from a {@link Zikula_Form_Plugin_Button} plugin. The passed args contains different properties
  * depending on the command source, but you should at least find a <var>$args['commandName']</var>
  * value indicating the name of the command. The command name is normally specified by the plugin
  * that initiated the command.
  *
  * @param Zikula_Form_View $view The form view instance.
  * @param array            $args Additional arguments.
  *
  * @see Zikula_Form_Plugin_Button
  * @see Zikula_Form_Plugin_ImageButton
  *
  * @return mixed Redirect or false on errors.
  */
 public function handleCommand(Zikula_Form_View $view, &$args)
 {
     if ($args['commandName'] == 'save') {
         // check if all fields are valid
         if (!$this->view->isValid()) {
             return false;
         }
         // retrieve form data
         $data = $this->view->getValues();
         // update all module vars
         try {
             $this->setVars($data['config']);
         } catch (\Exception $e) {
             $msg = $this->__('Error! Failed to set configuration variables.');
             if (System::isDevelopmentMode()) {
                 $msg .= ' ' . $e->getMessage();
             }
             return LogUtil::registerError($msg);
         }
         LogUtil::registerStatus($this->__('Done! Module configuration updated.'));
     } else {
         if ($args['commandName'] == 'cancel') {
             // nothing to do there
         }
     }
     // redirect back to the config page
     $url = ModUtil::url($this->name, 'admin', 'config');
     return $this->view->redirect($url);
 }
Ejemplo n.º 21
0
 /**
  * Perform some checks that might result in a die() upon failure.
  *
  * Listens on the 'core.preinit' event.
  *
  * @param Zikula_Event $event Event.
  *
  * @return void
  */
 public function systemCheck(Zikula_Event $event)
 {
     $die = false;
     if (get_magic_quotes_runtime()) {
         echo __('Error! Zikula does not support PHP magic_quotes_runtime - please disable this feature in php.ini.');
         $die = true;
     }
     if (ini_get('magic_quotes_gpc')) {
         echo __('Error! Zikula does not support PHP magic_quotes_gpc = On - please disable this feature in your php.ini file.');
         $die = true;
     }
     if (ini_get('register_globals')) {
         echo __('Error! Zikula does not support PHP register_globals = On - please disable this feature in your php.ini or .htaccess file.');
         $die = true;
     }
     // check PHP version, shouldn't be necessary, but....
     $x = explode('.', str_replace('-', '.', phpversion()));
     $phpVersion = "{$x['0']}.{$x['1']}.{$x['2']}";
     if (version_compare($phpVersion, Zikula_Core::PHP_MINIMUM_VERSION, '>=') == false) {
         echo __f('Error! Zikula requires PHP version %1$s or greater. Your server seems to be using version %2$s.', array(Zikula_Core::PHP_MINIMUM_VERSION, $phpVersion));
         $die = true;
     }
     // token_get_all needed for Smarty
     if (!function_exists('token_get_all')) {
         echo __("Error! PHP 'token_get_all()' is required but unavailable.");
         $die = true;
     }
     // mb_string is needed too
     if (!function_exists('mb_get_info')) {
         echo __("Error! PHP must have the mbstring extension loaded.");
         $die = true;
     }
     if (!function_exists('fsockopen')) {
         echo __("Error! The PHP function 'fsockopen()' is needed within the Zikula mailer module, but is not available.");
         $die = true;
     }
     if ($die) {
         echo __("Please configure your server to meet the Zikula system requirements.");
         exit;
     }
     if (System::isDevelopmentMode() || System::isInstalling()) {
         $temp = $this->serviceManager->getArgument('temp');
         if (!is_dir($temp) || !is_writable($temp)) {
             echo __f('The temporary directory "%s" and its subfolders must be writable.', $temp) . '<br />';
             die(__('Please ensure that the permissions are set correctly on your server.'));
         }
         $folders = array($temp, "{$temp}/error_logs", "{$temp}/view_compiled", "{$temp}/view_cache", "{$temp}/Theme_compiled", "{$temp}/Theme_cache", "{$temp}/Theme_Config", "{$temp}/Theme_cache", "{$temp}/purifierCache", "{$temp}/idsTmp");
         foreach ($folders as $folder) {
             if (!is_dir($folder)) {
                 mkdir($folder, $this->serviceManager->getArgument('system.chmod_dir'), true);
             }
             if (!is_writable($folder)) {
                 echo __f("System error! Folder '%s' was not found or is not writable.", $folder) . '<br />';
                 $die = true;
             }
         }
     }
     if ($die) {
         echo __('Please ensure that the permissions are set correctly for the mentioned folders.');
         exit;
     }
 }