Example #1
0
 /**
  * Overview for plugins
  * Copied from PluginsController 2015-10-02
  */
 public function index()
 {
     $oPluginManager = App()->getPluginManager();
     // Scan the plugins folder.
     $aDiscoveredPlugins = $oPluginManager->scanPlugins();
     $aInstalledPlugins = $oPluginManager->getInstalledPlugins();
     $aInstalledNames = array_map(function ($installedPlugin) {
         return $installedPlugin->name;
     }, $aInstalledPlugins);
     // Install newly discovered plugins.
     foreach ($aDiscoveredPlugins as $discoveredPlugin) {
         if (!in_array($discoveredPlugin['pluginClass'], $aInstalledNames)) {
             $oPlugin = new Plugin();
             $oPlugin->name = $discoveredPlugin['pluginClass'];
             $oPlugin->active = 0;
             $oPlugin->save();
         }
     }
     $aoPlugins = Plugin::model()->findAll();
     $data = array();
     foreach ($aoPlugins as $oPlugin) {
         /* @var $plugin Plugin */
         if (array_key_exists($oPlugin->name, $aDiscoveredPlugins)) {
             $aPluginSettings = App()->getPluginManager()->loadPlugin($oPlugin->name, $oPlugin->id)->getPluginSettings(false);
             $data[] = array('id' => $oPlugin->id, 'name' => $aDiscoveredPlugins[$oPlugin->name]['pluginName'], 'description' => $aDiscoveredPlugins[$oPlugin->name]['description'], 'active' => $oPlugin->active, 'settings' => $aPluginSettings, 'new' => !in_array($oPlugin->name, $aInstalledNames));
         } else {
             // This plugin is missing, maybe the files were deleted but the record was not removed from the database
             // Now delete this record. Depending on the plugin the settings will be preserved
             App()->user->setFlash('pluginDelete' . $oPlugin->id, sprintf(gT("Plugin '%s' was missing and is removed from the database."), $oPlugin->name));
             $oPlugin->delete();
         }
     }
     $this->_renderWrappedTemplate('pluginmanager', 'index', array('data' => $data));
 }
 function scanPlugins()
 {
     $plugins = array();
     $dir = ROOT . "/plugins";
     if ($dh = opendir($dir)) {
         while (($file = readdir($dh)) !== false) {
             if (is_dir($dir . "/" . $file) && $file != "." && $file != "..") {
                 if (file_exists($dir . "/" . $file . "/info.php")) {
                     $plugin_info = (include_once $dir . "/" . $file . "/info.php");
                     array_push($plugins, $plugin_info);
                 }
             }
         }
         closedir($dh);
     }
     usort($plugins, 'plugin_sort');
     foreach ($plugins as $plg) {
         if (!Plugins::instance()->findOne(array("conditions" => "name = '" . $plg['name'] . "'"))) {
             $plugin = new Plugin();
             //if ( isset($plg["id"]) && is_numeric($plg["id"]) ) {
             //$plugin->setId($plg['id']);
             //}
             $plugin->setName($plg["name"]);
             $plugin->setIsActivated(0);
             $plugin->setIsInstalled(0);
             $plugin->setVersion(array_var($plg, 'version'));
             $plugin->save();
         }
     }
 }
Example #3
0
 /**
  * Performs the work of inserting or updating the row in the database.
  *
  * If the object is new, it inserts it; otherwise an update is performed.
  * All related objects are also updated in this method.
  *
  * @param PropelPDO $con
  * @return int             The number of rows affected by this insert/update and any referring fk objects' save() operations.
  * @throws PropelException
  * @see        save()
  */
 protected function doSave(PropelPDO $con)
 {
     $affectedRows = 0;
     // initialize var to track total num of affected rows
     if (!$this->alreadyInSave) {
         $this->alreadyInSave = true;
         // We call the save method on the following object(s) if they
         // were passed to this object by their coresponding set
         // method.  This object relates to these object(s) by a
         // foreign key reference.
         if ($this->aPlugin !== null) {
             if ($this->aPlugin->isModified() || $this->aPlugin->isNew()) {
                 $affectedRows += $this->aPlugin->save($con);
             }
             $this->setPlugin($this->aPlugin);
         }
         if ($this->isNew() || $this->isModified()) {
             // persist changes
             if ($this->isNew()) {
                 $this->doInsert($con);
             } else {
                 $this->doUpdate($con);
             }
             $affectedRows += 1;
             $this->resetModified();
         }
         $this->alreadyInSave = false;
     }
     return $affectedRows;
 }
Example #4
0
 public function index()
 {
     $db_plugins = dm_column(Plugin::factory()->get(), 'slug');
     $fs_plugins = PluginManager::list_all();
     foreach ($fs_plugins as $plg) {
         if (!in_array($plg, $db_plugins)) {
             $pl = PluginManager::plugin($plg);
             $pli = $pl->get_info();
             $dbp = new Plugin();
             $dbp->name = $pli['name'];
             $dbp->url = $pli['url'];
             $dbp->slug = $pli['slug'];
             $dbp->version = $pli['version'];
             $dbp->author = $pli['author'];
             $dbp->author_url = $pli['author_url'];
             $dbp->description = $pli['description'];
             $dbp->active = false;
             $dbp->save();
             $pl->install();
         }
     }
     $this->templatemanager->assign('db_plugins', $db_plugins);
     $this->templatemanager->assign('fs_plugins', $fs_plugins);
     $this->templatemanager->show_template('plugins_list');
 }
Example #5
0
function install($pattern)
{
    _apply($pattern, function ($id) {
        $tmp = new Plugin();
        $tmp->setId($id);
        // check if plugin files exist
        if (!file_exists($tmp->getPath())) {
            print "No plugin found with that name. Skipping.\n";
            return false;
        }
        if (!file_exists($tmp->getPath() . 'package.json')) {
            print "Path exists, but no package.json found. Skipping.\n";
            return false;
        }
        // check if plugin is already installed
        $plugin = PluginQuery::create()->findPk($id);
        if ($plugin) {
            _loadPluginClass($plugin)->install();
            print "Re-installed plugin {$id}.\n";
        } else {
            $plugin = new Plugin();
            $plugin->setId($id);
            $plugin->save();
            _loadPluginClass($plugin)->install();
            print "Installed plugin {$id}.\n";
        }
    });
    exit;
}
Example #6
0
 /**
  * Cria um novo plugin
  * @param  int $menu_id     id do menu ao qual o plugin se refere
  * @param  string $plugin_name nome do plugin
  * @return boolean              Verdadeiro caso sucesso ou falso caso ocorra alguma falha
  */
 public function createPlugin($menu_id, $plugin_name)
 {
     $plugin = new Plugin();
     $plugin->menu_id = $menu_id;
     $plugin->plugin_name = $plugin_name;
     $return = $plugin->save();
     return $return;
 }
 function save_data()
 {
     if (class_exists('Plugin')) {
         $p = new Plugin();
         $p->where('path', $this->get_key())->get();
         $p->data = serialize((array) $this->get_data());
         $p->save();
     } else {
         return false;
     }
 }
Example #8
0
 public function actionIndex()
 {
     // список всех плагинов
     $plugins = Yii::app()->getPlugins();
     // все плагины регистрируем в бд
     // TODO если в базе нашлись плагины, которых уже нет, то помечаем их как удаленные
     // список плагинов, зарегистрированных в системе
     $pluginsDb = Plugin::model()->findAll();
     $finded = array();
     foreach ($plugins as $code => $config) {
         if (is_int($code)) {
             $code = $config;
             $config = array();
         }
         if (!isset($config['class'])) {
             $config['class'] = $code;
         }
         foreach ($pluginsDb as $plugin) {
             if ($plugin->code == $code) {
                 if ($plugin->class_name != $config['class']) {
                     $plugin->class_name = $config['class'];
                     $plugin->save();
                 }
                 $finded[] = $code;
                 continue 2;
             }
         }
         // плагина ещё нет в базе
         $newPlugin = new Plugin();
         $newPlugin->code = $code;
         $newPlugin->status = Plugin::STATUS_NEW;
         $newPlugin->class_name = $config['class'];
         //-------------------
         $newPlugin->name = $newPlugin->getName();
         // нигде не используется, исключительно для легкого чтения таблицы
         //-------------------
         $finded[] = $code;
         $newPlugin->save();
     }
     foreach ($pluginsDb as $plugin) {
         if (!in_array($plugin->code, $finded)) {
             // пропавшие плагины просто удаляем из базы
             try {
                 $plugin->deactivate($plugin);
             } catch (Exception $e) {
             }
             $plugin->delete();
             Yii::app()->compilePluginsConfig();
         }
     }
     $plugins = Plugin::model()->notDeleted()->findAll(array('order' => 'name'));
     $this->render('/index', array('plugins' => $plugins));
 }
Example #9
0
 /**
  * Store a newly created resource in storage.
  * POST /plugin
  *
  * @return Response
  */
 public function store()
 {
     $rules = ['name' => 'required|min:3'];
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         return Redirect::back()->withErrors($validator->messages());
     }
     $plugin = new Plugin();
     $plugin->name = Input::get('name');
     $plugin->docurl = Input::get('docurl');
     $plugin->save();
     return Redirect::action('plugin.version.create', [$plugin->id]);
 }
 /**
  * Enable the plugin,
  * Check if there is a static folder,
  * Copy the content to www/static/plugins/<plugin_name>/
  */
 public function install()
 {
     $plugin = PluginQuery::create()->findPK($this->getName());
     if (empty($plugin)) {
         $plugin = new Plugin();
         $plugin->setId($this->getName());
     }
     $plugin->setEnabled(true);
     $plugin->setInstalledAt(time());
     $plugin->save();
     $this->copyStaticFiles();
     $this->copyTemplates();
 }
Example #11
0
 public function setUp()
 {
     parent::setUp();
     $plugin = $this->db->getTable('Plugin')->find(1);
     if ($plugin) {
         $plugin->delete();
     }
     $plugin = new Plugin();
     $plugin->setDirectoryName(self::PLUGIN_NAME);
     $plugin->setActive(true);
     $plugin->setDbVersion('1.0');
     $plugin->save();
     $this->plugin = $plugin;
 }
Example #12
0
 public function plugin_activate($slug)
 {
     $plugin = Plugin::where('slug', '=', $slug)->first();
     $plugin_data = Plugins::get_plugin($slug);
     if (!empty($plugin->slug)) {
         $plugin->active = 1;
         $plugin->save();
     } else {
         $new_plugin = new Plugin();
         $new_plugin->name = $plugin_data['name'];
         $new_plugin->description = $plugin_data['description'];
         $new_plugin->version = $plugin_data['version'];
         $new_plugin->slug = $slug;
         $new_plugin->active = 1;
         $new_plugin->save();
     }
     return Redirect::to('admin#plugins')->with(array('note' => 'Successfully Activated ' . $plugin_data['name'], 'note_type' => 'success'));
 }
Example #13
0
 /**
  * Overview for plugins
  * Copied from PluginsController 2015-10-02
  */
 public function index()
 {
     $oPluginManager = App()->getPluginManager();
     // Scan the plugins folder.
     $aDiscoveredPlugins = $oPluginManager->scanPlugins();
     $aInstalledPlugins = $oPluginManager->getInstalledPlugins();
     $aInstalledNames = array_map(function ($installedPlugin) {
         return $installedPlugin->name;
     }, $aInstalledPlugins);
     // Install newly discovered plugins.
     foreach ($aDiscoveredPlugins as $discoveredPlugin) {
         if (!in_array($discoveredPlugin['pluginClass'], $aInstalledNames)) {
             $oPlugin = new Plugin();
             $oPlugin->name = $discoveredPlugin['pluginClass'];
             $oPlugin->active = 0;
             $oPlugin->save();
         }
     }
     $aoPlugins = Plugin::model()->findAll(array('order' => 'name'));
     $data = array();
     foreach ($aoPlugins as $oPlugin) {
         /* @var $plugin Plugin */
         if (array_key_exists($oPlugin->name, $aDiscoveredPlugins)) {
             $aPluginSettings = App()->getPluginManager()->loadPlugin($oPlugin->name, $oPlugin->id)->getPluginSettings(false);
             $data[] = array('id' => $oPlugin->id, 'name' => $aDiscoveredPlugins[$oPlugin->name]['pluginName'], 'description' => $aDiscoveredPlugins[$oPlugin->name]['description'], 'active' => $oPlugin->active, 'settings' => $aPluginSettings, 'new' => !in_array($oPlugin->name, $aInstalledNames));
         } else {
             // This plugin is missing, maybe the files were deleted but the record was not removed from the database
             // Now delete this record. Depending on the plugin the settings will be preserved
             App()->user->setFlash('pluginDelete' . $oPlugin->id, sprintf(gT("Plugin '%s' was missing and is removed from the database."), $oPlugin->name));
             $oPlugin->delete();
         }
     }
     if (Yii::app()->request->getParam('pageSize')) {
         Yii::app()->user->setState('pageSize', intval(Yii::app()->request->getParam('pageSize')));
     }
     $aData['fullpagebar']['returnbutton']['url'] = 'index';
     $aData['fullpagebar']['returnbutton']['text'] = gT('Return to admin home');
     $aData['data'] = $data;
     $this->_renderWrappedTemplate('pluginmanager', 'index', $aData);
     if (!Permission::model()->hasGlobalPermission('settings', 'read')) {
         Yii::app()->setFlashMessage(gT("No permission"), 'error');
         $this->getController()->redirect(array('/admin'));
     }
 }
Example #14
0
 public function registerPlugin(Bc_Application_Plugin_Descriptor $descriptor)
 {
     if ($this->isPluginRegistered($descriptor->getId())) {
         return;
     }
     if (is_dir($descriptor->getModelsPath())) {
         try {
             Doctrine::createTablesFromModels($descriptor->getModelsPath());
         } catch (Exception $e) {
             var_dump($e);
         }
     }
     $plugin = new Plugin();
     $plugin->name = $descriptor->getId();
     $plugin->description = $descriptor->getDescription();
     $plugin->title = $descriptor->getName();
     $plugin->active = true;
     $plugin->save();
 }
Example #15
0
function install($pattern)
{
    _apply($pattern, function ($id) {
        $tmp = new Plugin();
        $tmp->setId($id);
        // check if plugin files exist
        if (!file_exists($tmp->getPath())) {
            global $plugin_urls;
            if ($plugin_urls) {
                if (isset($plugin_urls[$id])) {
                    print "Found " . $id . " in plugins.json.\n";
                    install($plugin_urls[$id]);
                    // try installing from git repository
                    return true;
                    // cancel apply loop
                }
            }
            print "No plugin found with that name. Skipping.\n";
            return true;
            // cancel apply loop
        }
        if (!file_exists($tmp->getPath() . 'package.json')) {
            print "Path exists, but no package.json found. Skipping.\n";
            return true;
            // cancel apply loop
        }
        // check if plugin is already installed
        $plugin = PluginQuery::create()->findPk($id);
        if ($plugin) {
            _loadPluginClass($plugin)->install();
            print "Re-installed plugin {$id}.\n";
        } else {
            $plugin = new Plugin();
            $plugin->setId($id);
            $plugin->setInstalledAt(time());
            $plugin->save();
            _loadPluginClass($plugin)->install();
            print "Installed plugin {$id}.\n";
        }
        global $argv;
        if ($argv[count($argv) - 1] == '--private') {
            $plugin->setIsPrivate(true);
            $plugin->save();
            print "Set plugin {$id} to private.\n";
        }
    });
}
/**
 * @param integer $iOldDBVersion
 */
function db_upgrade_all($iOldDBVersion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $modifyoutput;
    Yii::app()->loadHelper('database');
    $sUserTemplateRootDir = Yii::app()->getConfig('usertemplaterootdir');
    $sStandardTemplateRootDir = Yii::app()->getConfig('standardtemplaterootdir');
    $oDB = Yii::app()->getDb();
    Yii::app()->setConfig('Updating', true);
    $oDB->schemaCachingDuration = 0;
    // Deactivate schema caching
    $oTransaction = $oDB->beginTransaction();
    try {
        if ($iOldDBVersion < 111) {
            // Language upgrades from version 110 to 111 because the language names did change
            $aOldNewLanguages = array('german_informal' => 'german-informal', 'cns' => 'cn-Hans', 'cnt' => 'cn-Hant', 'pt_br' => 'pt-BR', 'gr' => 'el', 'jp' => 'ja', 'si' => 'sl', 'se' => 'sv', 'vn' => 'vi');
            foreach ($aOldNewLanguages as $sOldLanguageCode => $sNewLanguageCode) {
                alterLanguageCode($sOldLanguageCode, $sNewLanguageCode);
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 111), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 112) {
            // New size of the username field (it was previously 20 chars wide)
            $oDB->createCommand()->alterColumn('{{users}}', 'users_name', "string(64) NOT NULL");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 112), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 113) {
            //Fixes the collation for the complete DB, tables and columns
            if (Yii::app()->db->driverName == 'mysql') {
                $sDatabaseName = getDBConnectionStringProperty('dbname');
                fixMySQLCollations();
                modifyDatabase("", "ALTER DATABASE `{$sDatabaseName}` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
                echo $modifyoutput;
                flush();
                @ob_flush();
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 113), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 114) {
            $oDB->createCommand()->alterColumn('{{saved_control}}', 'email', "string(320) NOT NULL");
            $oDB->createCommand()->alterColumn('{{surveys}}', 'adminemail', "string(320) NOT NULL");
            $oDB->createCommand()->alterColumn('{{users}}', 'email', "string(320) NOT NULL");
            $oDB->createCommand()->insert('{{settings_global}}', array('stg_name' => 'SessionName', 'stg_value' => randomChars(64, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!"$%&/()=?`+*~#",;.:abcdefghijklmnopqrstuvwxyz123456789')));
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 114), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 126) {
            addColumn('{{surveys}}', 'printanswers', "string(1) default 'N'");
            addColumn('{{surveys}}', 'listpublic', "string(1) default 'N'");
            upgradeSurveyTables126();
            upgradeTokenTables126();
            // Create quota table
            $oDB->createCommand()->createTable('{{quota}}', array('id' => 'pk', 'sid' => 'integer', 'qlimit' => 'integer', 'name' => 'string', 'action' => 'integer', 'active' => 'integer NOT NULL DEFAULT 1'));
            // Create quota_members table
            $oDB->createCommand()->createTable('{{quota_members}}', array('id' => 'pk', 'sid' => 'integer', 'qid' => 'integer', 'quota_id' => 'integer', 'code' => 'string(5)'));
            $oDB->createCommand()->createIndex('sid', '{{quota_members}}', 'sid,qid,quota_id,code', true);
            // Create templates_rights table
            $oDB->createCommand()->createTable('{{templates_rights}}', array('uid' => 'integer NOT NULL', 'folder' => 'string NOT NULL', 'use' => 'integer', 'PRIMARY KEY (uid, folder)'));
            // Create templates table
            $oDB->createCommand()->createTable('{{templates}}', array('folder' => 'string NOT NULL', 'creator' => 'integer NOT NULL', 'PRIMARY KEY (folder)'));
            // Rename Norwegian language codes
            alterLanguageCode('no', 'nb');
            addColumn('{{surveys}}', 'htmlemail', "string(1) default 'N'");
            addColumn('{{surveys}}', 'tokenanswerspersistence', "string(1) default 'N'");
            addColumn('{{surveys}}', 'usecaptcha', "string(1) default 'N'");
            addColumn('{{surveys}}', 'bounce_email', 'text');
            addColumn('{{users}}', 'htmleditormode', "string(7) default 'default'");
            addColumn('{{users}}', 'superadmin', "integer NOT NULL default '0'");
            addColumn('{{questions}}', 'lid1', "integer NOT NULL default '0'");
            alterColumn('{{conditions}}', 'value', "string", false, '');
            alterColumn('{{labels}}', 'title', "text");
            $oDB->createCommand()->update('{{users}}', array('superadmin' => 1), "create_survey=1 AND create_user=1 AND move_user=1 AND delete_user=1 AND configurator=1");
            $oDB->createCommand()->update('{{conditions}}', array('method' => '=='), "(method is null) or method='' or method='0'");
            dropColumn('{{users}}', 'move_user');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 126), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 127) {
            modifyDatabase("", "create index answers_idx2 on {{answers}} (sortorder)");
            echo $modifyoutput;
            modifyDatabase("", "create index assessments_idx2 on {{assessments}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index assessments_idx3 on {{assessments}} (gid)");
            echo $modifyoutput;
            modifyDatabase("", "create index conditions_idx2 on {{conditions}} (qid)");
            echo $modifyoutput;
            modifyDatabase("", "create index conditions_idx3 on {{conditions}} (cqid)");
            echo $modifyoutput;
            modifyDatabase("", "create index groups_idx2 on {{groups}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index question_attributes_idx2 on {{question_attributes}} (qid)");
            echo $modifyoutput;
            modifyDatabase("", "create index questions_idx2 on {{questions}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index questions_idx3 on {{questions}} (gid)");
            echo $modifyoutput;
            modifyDatabase("", "create index questions_idx4 on {{questions}} (type)");
            echo $modifyoutput;
            modifyDatabase("", "create index quota_idx2 on {{quota}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index saved_control_idx2 on {{saved_control}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index user_in_groups_idx1 on {{user_in_groups}} (ugid, uid)");
            echo $modifyoutput;
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 127), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 128) {
            upgradeTokens128();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 128), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 129) {
            addColumn('{{surveys}}', 'startdate', "datetime");
            addColumn('{{surveys}}', 'usestartdate', "string(1) NOT NULL default 'N'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 129), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 130) {
            addColumn('{{conditions}}', 'scenario', "integer NOT NULL default '1'");
            $oDB->createCommand()->update('{{conditions}}', array('scenario' => '1'), "(scenario is null) or scenario=0");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 130), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 131) {
            addColumn('{{surveys}}', 'publicstatistics', "string(1) NOT NULL default 'N'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 131), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 132) {
            addColumn('{{surveys}}', 'publicgraphs', "string(1) NOT NULL default 'N'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 132), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 133) {
            addColumn('{{users}}', 'one_time_pw', 'binary');
            // Add new assessment setting
            addColumn('{{surveys}}', 'assessments', "string(1) NOT NULL default 'N'");
            // add new assessment value fields to answers & labels
            addColumn('{{answers}}', 'assessment_value', "integer NOT NULL default '0'");
            addColumn('{{labels}}', 'assessment_value', "integer NOT NULL default '0'");
            // copy any valid codes from code field to assessment field
            switch (Yii::app()->db->driverName) {
                case 'mysql':
                case 'mysqli':
                    $oDB->createCommand("UPDATE {{answers}} SET assessment_value=CAST(`code` as SIGNED) where `code` REGEXP '^-?[0-9]+\$'")->execute();
                    $oDB->createCommand("UPDATE {{labels}} SET assessment_value=CAST(`code` as SIGNED) where `code` REGEXP '^-?[0-9]+\$'")->execute();
                    // copy assessment link to message since from now on we will have HTML assignment messages
                    $oDB->createCommand("UPDATE {{assessments}} set message=concat(replace(message,'/''',''''),'<br /><a href=\"',link,'\">',link,'</a>')")->execute();
                    break;
                case 'sqlsrv':
                case 'dblib':
                case 'mssql':
                    try {
                        $oDB->createCommand("UPDATE {{answers}} SET assessment_value=CAST([code] as int) WHERE ISNUMERIC([code])=1")->execute();
                        $oDB->createCommand("UPDATE {{labels}} SET assessment_value=CAST([code] as int) WHERE ISNUMERIC([code])=1")->execute();
                    } catch (Exception $e) {
                    }
                    // copy assessment link to message since from now on we will have HTML assignment messages
                    alterColumn('{{assessments}}', 'link', "text", false);
                    alterColumn('{{assessments}}', 'message', "text", false);
                    $oDB->createCommand("UPDATE {{assessments}} set message=replace(message,'/''','''')+'<br /><a href=\"'+link+'\">'+link+'</a>'")->execute();
                    break;
                case 'pgsql':
                    $oDB->createCommand("UPDATE {{answers}} SET assessment_value=CAST(code as integer) where code ~ '^[0-9]+'")->execute();
                    $oDB->createCommand("UPDATE {{labels}} SET assessment_value=CAST(code as integer) where code ~ '^[0-9]+'")->execute();
                    // copy assessment link to message since from now on we will have HTML assignment messages
                    $oDB->createCommand("UPDATE {{assessments}} set message=replace(message,'/''','''')||'<br /><a href=\"'||link||'\">'||link||'</a>'")->execute();
                    break;
                default:
                    die('Unknown database type');
            }
            // activate assessment where assessment rules exist
            $oDB->createCommand("UPDATE {{surveys}} SET assessments='Y' where sid in (SELECT sid FROM {{assessments}} group by sid)")->execute();
            // add language field to assessment table
            addColumn('{{assessments}}', 'language', "string(20) NOT NULL default 'en'");
            // update language field with default language of that particular survey
            $oDB->createCommand("UPDATE {{assessments}} SET language=(select language from {{surveys}} where sid={{assessments}}.sid)")->execute();
            // drop the old link field
            dropColumn('{{assessments}}', 'link');
            // Add new fields to survey language settings
            addColumn('{{surveys_languagesettings}}', 'surveyls_url', "string");
            addColumn('{{surveys_languagesettings}}', 'surveyls_endtext', 'text');
            // copy old URL fields ot language specific entries
            $oDB->createCommand("UPDATE {{surveys_languagesettings}} set surveyls_url=(select url from {{surveys}} where sid={{surveys_languagesettings}}.surveyls_survey_id)")->execute();
            // drop old URL field
            dropColumn('{{surveys}}', 'url');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 133), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 134) {
            // Add new tokens setting
            addColumn('{{surveys}}', 'usetokens', "string(1) NOT NULL default 'N'");
            addColumn('{{surveys}}', 'attributedescriptions', 'text');
            dropColumn('{{surveys}}', 'attribute1');
            dropColumn('{{surveys}}', 'attribute2');
            upgradeTokenTables134();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 134), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 135) {
            alterColumn('{{question_attributes}}', 'value', 'text');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 135), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 136) {
            addColumn('{{quota}}', 'autoload_url', "integer NOT NULL default 0");
            // Create quota table
            $aFields = array('quotals_id' => 'pk', 'quotals_quota_id' => 'integer NOT NULL DEFAULT 0', 'quotals_language' => "string(45) NOT NULL default 'en'", 'quotals_name' => 'string', 'quotals_message' => 'text NOT NULL', 'quotals_url' => 'string', 'quotals_urldescrip' => 'string');
            $oDB->createCommand()->createTable('{{quota_languagesettings}}', $aFields);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 136), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 137) {
            addColumn('{{surveys_languagesettings}}', 'surveyls_dateformat', "integer NOT NULL default 1");
            addColumn('{{users}}', 'dateformat', "integer NOT NULL default 1");
            $oDB->createCommand()->update('{{surveys}}', array('startdate' => NULL), "usestartdate='N'");
            $oDB->createCommand()->update('{{surveys}}', array('expires' => NULL), "useexpiry='N'");
            dropColumn('{{surveys}}', 'useexpiry');
            dropColumn('{{surveys}}', 'usestartdate');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 137), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 138) {
            alterColumn('{{quota_members}}', 'code', "string(11)");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 138), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 139) {
            upgradeSurveyTables139();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 139), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 140) {
            addColumn('{{surveys}}', 'emailresponseto', 'text');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 140), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 141) {
            addColumn('{{surveys}}', 'tokenlength', 'integer NOT NULL default 15');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 141), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 142) {
            upgradeQuestionAttributes142();
            $oDB->createCommand()->alterColumn('{{surveys}}', 'expires', "datetime");
            $oDB->createCommand()->alterColumn('{{surveys}}', 'startdate', "datetime");
            $oDB->createCommand()->update('{{question_attributes}}', array('value' => 0), "value='false'");
            $oDB->createCommand()->update('{{question_attributes}}', array('value' => 1), "value='true'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 142), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 143) {
            addColumn('{{questions}}', 'parent_qid', 'integer NOT NULL default 0');
            addColumn('{{answers}}', 'scale_id', 'integer NOT NULL default 0');
            addColumn('{{questions}}', 'scale_id', 'integer NOT NULL default 0');
            addColumn('{{questions}}', 'same_default', 'integer NOT NULL default 0');
            dropPrimaryKey('answers');
            addPrimaryKey('answers', array('qid', 'code', 'language', 'scale_id'));
            $aFields = array('qid' => "integer NOT NULL default 0", 'scale_id' => 'integer NOT NULL default 0', 'sqid' => 'integer  NOT NULL default 0', 'language' => 'string(20) NOT NULL', 'specialtype' => "string(20) NOT NULL default ''", 'defaultvalue' => 'text');
            $oDB->createCommand()->createTable('{{defaultvalues}}', $aFields);
            addPrimaryKey('defaultvalues', array('qid', 'specialtype', 'language', 'scale_id', 'sqid'));
            // -Move all 'answers' that are subquestions to the questions table
            // -Move all 'labels' that are answers to the answers table
            // -Transscribe the default values where applicable
            // -Move default values from answers to questions
            upgradeTables143();
            dropColumn('{{answers}}', 'default_value');
            dropColumn('{{questions}}', 'lid');
            dropColumn('{{questions}}', 'lid1');
            $aFields = array('sesskey' => "string(64) NOT NULL DEFAULT ''", 'expiry' => "datetime NOT NULL", 'expireref' => "string(250) DEFAULT ''", 'created' => "datetime NOT NULL", 'modified' => "datetime NOT NULL", 'sessdata' => 'text');
            $oDB->createCommand()->createTable('{{sessions}}', $aFields);
            addPrimaryKey('sessions', array('sesskey'));
            $oDB->createCommand()->createIndex('sess2_expiry', '{{sessions}}', 'expiry');
            $oDB->createCommand()->createIndex('sess2_expireref', '{{sessions}}', 'expireref');
            // Move all user templates to the new user template directory
            echo "<br>" . sprintf(gT("Moving user templates to new location at %s..."), $sUserTemplateRootDir) . "<br />";
            $hTemplateDirectory = opendir($sStandardTemplateRootDir);
            $aFailedTemplates = array();
            // get each entry
            while ($entryName = readdir($hTemplateDirectory)) {
                if (!in_array($entryName, array('.', '..', '.svn')) && is_dir($sStandardTemplateRootDir . DIRECTORY_SEPARATOR . $entryName) && !isStandardTemplate($entryName)) {
                    if (!rename($sStandardTemplateRootDir . DIRECTORY_SEPARATOR . $entryName, $sUserTemplateRootDir . DIRECTORY_SEPARATOR . $entryName)) {
                        $aFailedTemplates[] = $entryName;
                    }
                }
            }
            if (count($aFailedTemplates) > 0) {
                echo "The following templates at {$sStandardTemplateRootDir} could not be moved to the new location at {$sUserTemplateRootDir}:<br /><ul>";
                foreach ($aFailedTemplates as $sFailedTemplate) {
                    echo "<li>{$sFailedTemplate}</li>";
                }
                echo "</ul>Please move these templates manually after the upgrade has finished.<br />";
            }
            // close directory
            closedir($hTemplateDirectory);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 143), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 145) {
            addColumn('{{surveys}}', 'savetimings', "string(1) NULL default 'N'");
            addColumn('{{surveys}}', 'showXquestions', "string(1) NULL default 'Y'");
            addColumn('{{surveys}}', 'showgroupinfo', "string(1) NULL default 'B'");
            addColumn('{{surveys}}', 'shownoanswer', "string(1) NULL default 'Y'");
            addColumn('{{surveys}}', 'showqnumcode', "string(1) NULL default 'X'");
            addColumn('{{surveys}}', 'bouncetime', 'integer');
            addColumn('{{surveys}}', 'bounceprocessing', "string(1) NULL default 'N'");
            addColumn('{{surveys}}', 'bounceaccounttype', "string(4)");
            addColumn('{{surveys}}', 'bounceaccounthost', "string(200)");
            addColumn('{{surveys}}', 'bounceaccountpass', "string(100)");
            addColumn('{{surveys}}', 'bounceaccountencryption', "string(3)");
            addColumn('{{surveys}}', 'bounceaccountuser', "string(200)");
            addColumn('{{surveys}}', 'showwelcome', "string(1) default 'Y'");
            addColumn('{{surveys}}', 'showprogress', "string(1) default 'Y'");
            addColumn('{{surveys}}', 'allowjumps', "string(1) default 'N'");
            addColumn('{{surveys}}', 'navigationdelay', "integer default 0");
            addColumn('{{surveys}}', 'nokeyboard', "string(1) default 'N'");
            addColumn('{{surveys}}', 'alloweditaftercompletion', "string(1) default 'N'");
            $aFields = array('sid' => "integer NOT NULL", 'uid' => "integer NOT NULL", 'permission' => 'string(20) NOT NULL', 'create_p' => "integer NOT NULL default 0", 'read_p' => "integer NOT NULL default 0", 'update_p' => "integer NOT NULL default 0", 'delete_p' => "integer NOT NULL default 0", 'import_p' => "integer NOT NULL default 0", 'export_p' => "integer NOT NULL default 0");
            $oDB->createCommand()->createTable('{{survey_permissions}}', $aFields);
            addPrimaryKey('survey_permissions', array('sid', 'uid', 'permission'));
            upgradeSurveyPermissions145();
            // drop the old survey rights table
            $oDB->createCommand()->dropTable('{{surveys_rights}}');
            // Add new fields for email templates
            addColumn('{{surveys_languagesettings}}', 'email_admin_notification_subj', "string");
            addColumn('{{surveys_languagesettings}}', 'email_admin_responses_subj', "string");
            addColumn('{{surveys_languagesettings}}', 'email_admin_notification', "text");
            addColumn('{{surveys_languagesettings}}', 'email_admin_responses', "text");
            //Add index to questions table to speed up subquestions
            $oDB->createCommand()->createIndex('parent_qid_idx', '{{questions}}', 'parent_qid');
            addColumn('{{surveys}}', 'emailnotificationto', "text");
            upgradeSurveys145();
            dropColumn('{{surveys}}', 'notification');
            alterColumn('{{conditions}}', 'method', "string(5)", false, '');
            $oDB->createCommand()->renameColumn('{{surveys}}', 'private', 'anonymized');
            $oDB->createCommand()->update('{{surveys}}', array('anonymized' => 'N'), "anonymized is NULL");
            alterColumn('{{surveys}}', 'anonymized', "string(1)", false, 'N');
            //now we clean up things that were not properly set in previous DB upgrades
            $oDB->createCommand()->update('{{answers}}', array('answer' => ''), "answer is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('scope' => ''), "scope is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('name' => ''), "name is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('message' => ''), "message is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('minimum' => ''), "minimum is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('maximum' => ''), "maximum is NULL");
            $oDB->createCommand()->update('{{groups}}', array('group_name' => ''), "group_name is NULL");
            $oDB->createCommand()->update('{{labels}}', array('code' => ''), "code is NULL");
            $oDB->createCommand()->update('{{labelsets}}', array('label_name' => ''), "label_name is NULL");
            $oDB->createCommand()->update('{{questions}}', array('type' => 'T'), "type is NULL");
            $oDB->createCommand()->update('{{questions}}', array('title' => ''), "title is NULL");
            $oDB->createCommand()->update('{{questions}}', array('question' => ''), "question is NULL");
            $oDB->createCommand()->update('{{questions}}', array('other' => 'N'), "other is NULL");
            alterColumn('{{answers}}', 'answer', "text", false);
            alterColumn('{{answers}}', 'assessment_value', 'integer', false, '0');
            alterColumn('{{assessments}}', 'scope', "string(5)", false, '');
            alterColumn('{{assessments}}', 'name', "text", false);
            alterColumn('{{assessments}}', 'message', "text", false);
            alterColumn('{{assessments}}', 'minimum', "string(50)", false, '');
            alterColumn('{{assessments}}', 'maximum', "string(50)", false, '');
            // change the primary index to include language
            if (Yii::app()->db->driverName == 'mysql') {
                modifyPrimaryKey('assessments', array('id', 'language'));
            } else {
                dropPrimaryKey('assessments');
                addPrimaryKey('assessments', array('id', 'language'));
            }
            alterColumn('{{conditions}}', 'cfieldname', "string(50)", false, '');
            dropPrimaryKey('defaultvalues');
            alterColumn('{{defaultvalues}}', 'specialtype', "string(20)", false, '');
            addPrimaryKey('defaultvalues', array('qid', 'specialtype', 'language', 'scale_id', 'sqid'));
            alterColumn('{{groups}}', 'group_name', "string(100)", false, '');
            alterColumn('{{labels}}', 'code', "string(5)", false, '');
            dropPrimaryKey('labels');
            alterColumn('{{labels}}', 'language', "string(20)", false, 'en');
            addPrimaryKey('labels', array('lid', 'sortorder', 'language'));
            alterColumn('{{labelsets}}', 'label_name', "string(100)", false, '');
            alterColumn('{{questions}}', 'parent_qid', 'integer', false, '0');
            alterColumn('{{questions}}', 'title', "string(20)", false, '');
            alterColumn('{{questions}}', 'question', "text", false);
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('questions_idx4', '{{questions}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{questions}}', 'type', "string(1)", false, 'T');
            try {
                $oDB->createCommand()->createIndex('questions_idx4', '{{questions}}', 'type');
            } catch (Exception $e) {
            }
            alterColumn('{{questions}}', 'other', "string(1)", false, 'N');
            alterColumn('{{questions}}', 'mandatory', "string(1)");
            alterColumn('{{question_attributes}}', 'attribute', "string(50)");
            alterColumn('{{quota}}', 'qlimit', 'integer');
            $oDB->createCommand()->update('{{saved_control}}', array('identifier' => ''), "identifier is NULL");
            alterColumn('{{saved_control}}', 'identifier', "text", false);
            $oDB->createCommand()->update('{{saved_control}}', array('access_code' => ''), "access_code is NULL");
            alterColumn('{{saved_control}}', 'access_code', "text", false);
            alterColumn('{{saved_control}}', 'email', "string(320)");
            $oDB->createCommand()->update('{{saved_control}}', array('ip' => ''), "ip is NULL");
            alterColumn('{{saved_control}}', 'ip', "text", false);
            $oDB->createCommand()->update('{{saved_control}}', array('saved_thisstep' => ''), "saved_thisstep is NULL");
            alterColumn('{{saved_control}}', 'saved_thisstep', "text", false);
            $oDB->createCommand()->update('{{saved_control}}', array('status' => ''), "status is NULL");
            alterColumn('{{saved_control}}', 'status', "string(1)", false, '');
            $oDB->createCommand()->update('{{saved_control}}', array('saved_date' => '1980-01-01 00:00:00'), "saved_date is NULL");
            alterColumn('{{saved_control}}', 'saved_date', "datetime", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => ''), "stg_value is NULL");
            alterColumn('{{settings_global}}', 'stg_value', "string", false, '');
            alterColumn('{{surveys}}', 'admin', "string(50)");
            $oDB->createCommand()->update('{{surveys}}', array('active' => 'N'), "active is NULL");
            alterColumn('{{surveys}}', 'active', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'startdate', "datetime");
            alterColumn('{{surveys}}', 'adminemail', "string(320)");
            alterColumn('{{surveys}}', 'anonymized', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'faxto', "string(20)");
            alterColumn('{{surveys}}', 'format', "string(1)");
            alterColumn('{{surveys}}', 'language', "string(50)");
            alterColumn('{{surveys}}', 'additional_languages', "string");
            alterColumn('{{surveys}}', 'printanswers', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'publicstatistics', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'publicgraphs', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'assessments', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'usetokens', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'bounce_email', "string(320)");
            alterColumn('{{surveys}}', 'tokenlength', 'integer', true, 15);
            $oDB->createCommand()->update('{{surveys_languagesettings}}', array('surveyls_title' => ''), "surveyls_title is NULL");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_title', "string(200)", false);
            alterColumn('{{surveys_languagesettings}}', 'surveyls_endtext', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_url', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_urldescription', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_invite_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_remind_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_register_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_confirm_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_dateformat', 'integer', false, 1);
            $oDB->createCommand()->update('{{users}}', array('users_name' => ''), "users_name is NULL");
            $oDB->createCommand()->update('{{users}}', array('full_name' => ''), "full_name is NULL");
            alterColumn('{{users}}', 'users_name', "string(64)", false, '');
            alterColumn('{{users}}', 'full_name', "string(50)", false);
            alterColumn('{{users}}', 'lang', "string(20)");
            alterColumn('{{users}}', 'email', "string(320)");
            alterColumn('{{users}}', 'superadmin', 'integer', false, 0);
            alterColumn('{{users}}', 'htmleditormode', "string(7)", true, 'default');
            alterColumn('{{users}}', 'dateformat', 'integer', false, 1);
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('email', '{{users}}');
            } catch (Exception $e) {
                // do nothing
                rollBackToTransactionBookmark();
            }
            $oDB->createCommand()->update('{{user_groups}}', array('name' => ''), "name is NULL");
            $oDB->createCommand()->update('{{user_groups}}', array('description' => ''), "description is NULL");
            alterColumn('{{user_groups}}', 'name', "string(20)", false);
            alterColumn('{{user_groups}}', 'description', "text", false);
            try {
                $oDB->createCommand()->dropIndex('user_in_groups_idx1', '{{user_in_groups}}');
            } catch (Exception $e) {
            }
            try {
                addPrimaryKey('user_in_groups', array('ugid', 'uid'));
            } catch (Exception $e) {
            }
            addColumn('{{surveys_languagesettings}}', 'surveyls_numberformat', "integer NOT NULL DEFAULT 0");
            $oDB->createCommand()->createTable('{{failed_login_attempts}}', array('id' => "pk", 'ip' => 'string(37) NOT NULL', 'last_attempt' => 'string(20) NOT NULL', 'number_attempts' => "integer NOT NULL"));
            upgradeTokens145();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 145), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 146) {
            upgradeSurveyTimings146();
            // Fix permissions for new feature quick-translation
            try {
                setTransactionBookmark();
                $oDB->createCommand("INSERT into {{survey_permissions}} (sid,uid,permission,read_p,update_p) SELECT sid,owner_id,'translations','1','1' from {{surveys}}")->execute();
                echo $modifyoutput;
                flush();
                @ob_flush();
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 146), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 147) {
            addColumn('{{users}}', 'templateeditormode', "string(7) NOT NULL default 'default'");
            addColumn('{{users}}', 'questionselectormode', "string(7) NOT NULL default 'default'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 147), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 148) {
            addColumn('{{users}}', 'participant_panel', "integer NOT NULL default 0");
            $oDB->createCommand()->createTable('{{participants}}', array('participant_id' => 'string(50) NOT NULL', 'firstname' => 'string(40) default NULL', 'lastname' => 'string(40) default NULL', 'email' => 'string(80) default NULL', 'language' => 'string(40) default NULL', 'blacklisted' => 'string(1) NOT NULL', 'owner_uid' => "integer NOT NULL"));
            addPrimaryKey('participants', array('participant_id'));
            $oDB->createCommand()->createTable('{{participant_attribute}}', array('participant_id' => 'string(50) NOT NULL', 'attribute_id' => "integer NOT NULL", 'value' => 'string(50) NOT NULL'));
            addPrimaryKey('participant_attribute', array('participant_id', 'attribute_id'));
            $oDB->createCommand()->createTable('{{participant_attribute_names}}', array('attribute_id' => 'autoincrement', 'attribute_type' => 'string(4) NOT NULL', 'visible' => 'string(5) NOT NULL', 'PRIMARY KEY (attribute_id,attribute_type)'));
            $oDB->createCommand()->createTable('{{participant_attribute_names_lang}}', array('attribute_id' => 'integer NOT NULL', 'attribute_name' => 'string(30) NOT NULL', 'lang' => 'string(20) NOT NULL'));
            addPrimaryKey('participant_attribute_names_lang', array('attribute_id', 'lang'));
            $oDB->createCommand()->createTable('{{participant_attribute_values}}', array('attribute_id' => 'integer NOT NULL', 'value_id' => 'pk', 'value' => 'string(20) NOT NULL'));
            $oDB->createCommand()->createTable('{{participant_shares}}', array('participant_id' => 'string(50) NOT NULL', 'share_uid' => 'integer NOT NULL', 'date_added' => 'datetime NOT NULL', 'can_edit' => 'string(5) NOT NULL'));
            addPrimaryKey('participant_shares', array('participant_id', 'share_uid'));
            $oDB->createCommand()->createTable('{{survey_links}}', array('participant_id' => 'string(50) NOT NULL', 'token_id' => 'integer NOT NULL', 'survey_id' => 'integer NOT NULL', 'date_created' => 'datetime NOT NULL'));
            addPrimaryKey('survey_links', array('participant_id', 'token_id', 'survey_id'));
            // Add language field to question_attributes table
            addColumn('{{question_attributes}}', 'language', "string(20)");
            upgradeQuestionAttributes148();
            fixSubquestions();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 148), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 149) {
            $aFields = array('id' => 'integer', 'sid' => 'integer', 'parameter' => 'string(50)', 'targetqid' => 'integer', 'targetsqid' => 'integer');
            $oDB->createCommand()->createTable('{{survey_url_parameters}}', $aFields);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 149), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 150) {
            addColumn('{{questions}}', 'relevance', 'TEXT');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 150), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 151) {
            addColumn('{{groups}}', 'randomization_group', "string(20) NOT NULL default ''");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 151), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 152) {
            $oDB->createCommand()->createIndex('question_attributes_idx3', '{{question_attributes}}', 'attribute');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 152), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 153) {
            $oDB->createCommand()->createTable('{{expression_errors}}', array('id' => 'pk', 'errortime' => 'string(50)', 'sid' => 'integer', 'gid' => 'integer', 'qid' => 'integer', 'gseq' => 'integer', 'qseq' => 'integer', 'type' => 'string(50)', 'eqn' => 'text', 'prettyprint' => 'text'));
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 153), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 154) {
            $oDB->createCommand()->addColumn('{{groups}}', 'grelevance', "text");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 154), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 155) {
            addColumn('{{surveys}}', 'googleanalyticsstyle', "string(1)");
            addColumn('{{surveys}}', 'googleanalyticsapikey', "string(25)");
            try {
                setTransactionBookmark();
                $oDB->createCommand()->renameColumn('{{surveys}}', 'showXquestions', 'showxquestions');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 155), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 156) {
            try {
                $oDB->createCommand()->dropTable('{{survey_url_parameters}}');
            } catch (Exception $e) {
                // do nothing
            }
            $oDB->createCommand()->createTable('{{survey_url_parameters}}', array('id' => 'pk', 'sid' => 'integer NOT NULL', 'parameter' => 'string(50) NOT NULL', 'targetqid' => 'integer', 'targetsqid' => 'integer'));
            $oDB->createCommand()->dropTable('{{sessions}}');
            if (Yii::app()->db->driverName == 'mysql') {
                $oDB->createCommand()->createTable('{{sessions}}', array('id' => 'string(32) NOT NULL', 'expire' => 'integer', 'data' => 'longtext'));
            } else {
                $oDB->createCommand()->createTable('{{sessions}}', array('id' => 'string(32) NOT NULL', 'expire' => 'integer', 'data' => 'text'));
            }
            addPrimaryKey('sessions', array('id'));
            addColumn('{{surveys_languagesettings}}', 'surveyls_attributecaptions', "TEXT");
            addColumn('{{surveys}}', 'sendconfirmation', "string(1) default 'Y'");
            upgradeSurveys156();
            // If a survey has an deleted owner, re-own the survey to the superadmin
            $oDB->schema->refresh();
            Survey::model()->refreshMetaData();
            $surveys = Survey::model();
            $surveys = $surveys->with(array('owner'))->findAll();
            foreach ($surveys as $row) {
                if (!isset($row->owner->attributes)) {
                    Survey::model()->updateByPk($row->sid, array('owner_id' => 1));
                }
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 156), "stg_name='DBVersion'");
            $oTransaction->commit();
            $oTransaction = $oDB->beginTransaction();
        }
        if ($iOldDBVersion < 157) {
            // MySQL DB corrections
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('questions_idx4', '{{questions}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{answers}}', 'assessment_value', 'integer', false, '0');
            dropPrimaryKey('answers');
            alterColumn('{{answers}}', 'scale_id', 'integer', false, '0');
            addPrimaryKey('answers', array('qid', 'code', 'language', 'scale_id'));
            alterColumn('{{conditions}}', 'method', "string(5)", false, '');
            alterColumn('{{participants}}', 'owner_uid', 'integer', false);
            alterColumn('{{participant_attribute_names}}', 'visible', 'string(5)', false);
            alterColumn('{{questions}}', 'type', "string(1)", false, 'T');
            alterColumn('{{questions}}', 'other', "string(1)", false, 'N');
            alterColumn('{{questions}}', 'mandatory', "string(1)");
            alterColumn('{{questions}}', 'scale_id', 'integer', false, '0');
            alterColumn('{{questions}}', 'parent_qid', 'integer', false, '0');
            alterColumn('{{questions}}', 'same_default', 'integer', false, '0');
            alterColumn('{{quota}}', 'qlimit', 'integer');
            alterColumn('{{quota}}', 'action', 'integer');
            alterColumn('{{quota}}', 'active', 'integer', false, '1');
            alterColumn('{{quota}}', 'autoload_url', 'integer', false, '0');
            alterColumn('{{saved_control}}', 'status', "string(1)", false, '');
            try {
                setTransactionBookmark();
                alterColumn('{{sessions}}', 'id', "string(32)", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{surveys}}', 'active', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'anonymized', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'format', "string(1)");
            alterColumn('{{surveys}}', 'savetimings', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'datestamp', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'usecookie', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'allowregister', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'allowsave', "string(1)", false, 'Y');
            alterColumn('{{surveys}}', 'autonumber_start', 'integer', false, '0');
            alterColumn('{{surveys}}', 'autoredirect', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'allowprev', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'printanswers', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'ipaddr', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'refurl', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'publicstatistics', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'publicgraphs', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'listpublic', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'htmlemail', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'sendconfirmation', "string(1)", false, 'Y');
            alterColumn('{{surveys}}', 'tokenanswerspersistence', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'assessments', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'usecaptcha', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'usetokens', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'tokenlength', 'integer', false, '15');
            alterColumn('{{surveys}}', 'showxquestions', "string(1)", true, 'Y');
            alterColumn('{{surveys}}', 'showgroupinfo', "string(1) ", true, 'B');
            alterColumn('{{surveys}}', 'shownoanswer', "string(1) ", true, 'Y');
            alterColumn('{{surveys}}', 'showqnumcode', "string(1) ", true, 'X');
            alterColumn('{{surveys}}', 'bouncetime', 'integer');
            alterColumn('{{surveys}}', 'showwelcome', "string(1)", true, 'Y');
            alterColumn('{{surveys}}', 'showprogress', "string(1)", true, 'Y');
            alterColumn('{{surveys}}', 'allowjumps', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'navigationdelay', 'integer', false, '0');
            alterColumn('{{surveys}}', 'nokeyboard', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'alloweditaftercompletion', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'googleanalyticsstyle', "string(1)");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_dateformat', 'integer', false, 1);
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'sid', "integer", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'uid', "integer", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{survey_permissions}}', 'create_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'read_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'update_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'delete_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'import_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'export_p', 'integer', false, '0');
            alterColumn('{{survey_url_parameters}}', 'targetqid', 'integer');
            alterColumn('{{survey_url_parameters}}', 'targetsqid', 'integer');
            alterColumn('{{templates_rights}}', 'use', 'integer', false);
            alterColumn('{{users}}', 'create_survey', 'integer', false, '0');
            alterColumn('{{users}}', 'create_user', 'integer', false, '0');
            alterColumn('{{users}}', 'participant_panel', 'integer', false, '0');
            alterColumn('{{users}}', 'delete_user', 'integer', false, '0');
            alterColumn('{{users}}', 'superadmin', 'integer', false, '0');
            alterColumn('{{users}}', 'configurator', 'integer', false, '0');
            alterColumn('{{users}}', 'manage_template', 'integer', false, '0');
            alterColumn('{{users}}', 'manage_label', 'integer', false, '0');
            alterColumn('{{users}}', 'dateformat', 'integer', false, 1);
            alterColumn('{{users}}', 'participant_panel', 'integer', false, '0');
            alterColumn('{{users}}', 'parent_id', 'integer', false);
            try {
                setTransactionBookmark();
                alterColumn('{{surveys_languagesettings}}', 'surveyls_survey_id', "integer", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{user_groups}}', 'owner_id', "integer", false);
            dropPrimaryKey('user_in_groups');
            alterColumn('{{user_in_groups}}', 'ugid', "integer", false);
            alterColumn('{{user_in_groups}}', 'uid', "integer", false);
            // Additional corrections for Postgres
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('questions_idx3', '{{questions}}', 'gid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('conditions_idx3', '{{conditions}}', 'cqid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('questions_idx4', '{{questions}}', 'type');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('user_in_groups_idx1', '{{user_in_groups}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('{{user_name_key}}', '{{users}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('users_name', '{{users}}', 'users_name', true);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                addPrimaryKey('user_in_groups', array('ugid', 'uid'));
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{participant_attribute}}', 'value', "string(50)", false);
            try {
                setTransactionBookmark();
                alterColumn('{{participant_attribute_names}}', 'attribute_type', "string(4)", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                dropColumn('{{participant_attribute_names_lang}}', 'id');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                addPrimaryKey('participant_attribute_names_lang', array('attribute_id', 'lang'));
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->renameColumn('{{participant_shares}}', 'shared_uid', 'share_uid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{participant_shares}}', 'date_added', "datetime", false);
            alterColumn('{{participants}}', 'firstname', "string(40)");
            alterColumn('{{participants}}', 'lastname', "string(40)");
            alterColumn('{{participants}}', 'email', "string(80)");
            alterColumn('{{participants}}', 'language', "string(40)");
            alterColumn('{{quota_languagesettings}}', 'quotals_name', "string");
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'sid', 'integer', false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'uid', 'integer', false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{users}}', 'htmleditormode', "string(7)", true, 'default');
            // Sometimes the survey_links table was deleted before this step, if so
            // we recreate it (copied from line 663)
            if (!tableExists('{survey_links}')) {
                $oDB->createCommand()->createTable('{{survey_links}}', array('participant_id' => 'string(50) NOT NULL', 'token_id' => 'integer NOT NULL', 'survey_id' => 'integer NOT NULL', 'date_created' => 'datetime NOT NULL'));
                addPrimaryKey('survey_links', array('participant_id', 'token_id', 'survey_id'));
            }
            alterColumn('{{survey_links}}', 'date_created', "datetime", true);
            alterColumn('{{saved_control}}', 'identifier', "text", false);
            alterColumn('{{saved_control}}', 'email', "string(320)");
            alterColumn('{{surveys}}', 'adminemail', "string(320)");
            alterColumn('{{surveys}}', 'bounce_email', "string(320)");
            alterColumn('{{users}}', 'email', "string(320)");
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('assessments_idx', '{{assessments}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('assessments_idx3', '{{assessments}}', 'gid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('ixcode', '{{labels}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('{{labels_ixcode_idx}}', '{{labels}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('labels_code_idx', '{{labels}}', 'code');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            if (Yii::app()->db->driverName == 'pgsql') {
                try {
                    setTransactionBookmark();
                    $oDB->createCommand("ALTER TABLE ONLY {{user_groups}} ADD PRIMARY KEY (ugid); ")->execute;
                } catch (Exception $e) {
                    rollBackToTransactionBookmark();
                }
                try {
                    setTransactionBookmark();
                    $oDB->createCommand("ALTER TABLE ONLY {{users}} ADD PRIMARY KEY (uid); ")->execute;
                } catch (Exception $e) {
                    rollBackToTransactionBookmark();
                }
            }
            // Additional corrections for MSSQL
            alterColumn('{{answers}}', 'answer', "text", false);
            alterColumn('{{assessments}}', 'name', "text", false);
            alterColumn('{{assessments}}', 'message', "text", false);
            alterColumn('{{defaultvalues}}', 'defaultvalue', "text");
            alterColumn('{{expression_errors}}', 'eqn', "text");
            alterColumn('{{expression_errors}}', 'prettyprint', "text");
            alterColumn('{{groups}}', 'description', "text");
            alterColumn('{{groups}}', 'grelevance', "text");
            alterColumn('{{labels}}', 'title', "text");
            alterColumn('{{question_attributes}}', 'value', "text");
            alterColumn('{{questions}}', 'preg', "text");
            alterColumn('{{questions}}', 'help', "text");
            alterColumn('{{questions}}', 'relevance', "text");
            alterColumn('{{questions}}', 'question', "text", false);
            alterColumn('{{quota_languagesettings}}', 'quotals_quota_id', "integer", false);
            alterColumn('{{quota_languagesettings}}', 'quotals_message', "text", false);
            alterColumn('{{saved_control}}', 'refurl', "text");
            alterColumn('{{saved_control}}', 'access_code', "text", false);
            alterColumn('{{saved_control}}', 'ip', "text", false);
            alterColumn('{{saved_control}}', 'saved_thisstep', "text", false);
            alterColumn('{{saved_control}}', 'saved_date', "datetime", false);
            alterColumn('{{surveys}}', 'attributedescriptions', "text");
            alterColumn('{{surveys}}', 'emailresponseto', "text");
            alterColumn('{{surveys}}', 'emailnotificationto', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_description', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_welcometext', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_invite', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_remind', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_register', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_confirm', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_attributecaptions', "text");
            alterColumn('{{surveys_languagesettings}}', 'email_admin_notification', "text");
            alterColumn('{{surveys_languagesettings}}', 'email_admin_responses', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_endtext', "text");
            alterColumn('{{user_groups}}', 'description', "text", false);
            alterColumn('{{conditions}}', 'value', 'string', false, '');
            alterColumn('{{participant_shares}}', 'can_edit', "string(5)", false);
            alterColumn('{{users}}', 'password', "binary", false);
            dropColumn('{{users}}', 'one_time_pw');
            addColumn('{{users}}', 'one_time_pw', 'binary');
            $oDB->createCommand()->update('{{question_attributes}}', array('value' => '1'), "attribute = 'random_order' and value = '2'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 157), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 158) {
            LimeExpressionManager::UpgradeConditionsToRelevance();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 158), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 159) {
            alterColumn('{{failed_login_attempts}}', 'ip', "string(40)", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 159), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 160) {
            alterLanguageCode('it', 'it-informal');
            alterLanguageCode('it-formal', 'it');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 160), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 161) {
            addColumn('{{survey_links}}', 'date_invited', 'datetime NULL default NULL');
            addColumn('{{survey_links}}', 'date_completed', 'datetime NULL default NULL');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 161), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 162) {
            /* Fix participant db types */
            alterColumn('{{participant_attribute}}', 'value', "text", false);
            alterColumn('{{participant_attribute_names_lang}}', 'attribute_name', "string(255)", false);
            alterColumn('{{participant_attribute_values}}', 'value', "text", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 162), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 163) {
            //Replace  by <script type="text/javascript" src="{TEMPLATEURL}template.js"></script> by {TEMPLATEJS}
            $replacedTemplate = replaceTemplateJS();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 163), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 164) {
            upgradeTokens148();
            // this should have bee done in 148 - that's why it is named this way
            // fix survey tables for missing or incorrect token field
            upgradeSurveyTables164();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 164), "stg_name='DBVersion'");
            // Not updating settings table as upgrade process takes care of that step now
        }
        if ($iOldDBVersion < 165) {
            $oDB->createCommand()->createTable('{{plugins}}', array('id' => 'pk', 'name' => 'string NOT NULL', 'active' => 'boolean'));
            $oDB->createCommand()->createTable('{{plugin_settings}}', array('id' => 'pk', 'plugin_id' => 'integer NOT NULL', 'model' => 'string', 'model_id' => 'integer', 'key' => 'string', 'value' => 'text'));
            alterColumn('{{surveys_languagesettings}}', 'surveyls_url', "text");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 165), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 166) {
            $oDB->createCommand()->renameTable('{{survey_permissions}}', '{{permissions}}');
            dropPrimaryKey('permissions');
            alterColumn('{{permissions}}', 'permission', "string(100)", false);
            $oDB->createCommand()->renameColumn('{{permissions}}', 'sid', 'entity_id');
            alterColumn('{{permissions}}', 'entity_id', "string(100)", false);
            addColumn('{{permissions}}', 'entity', "string(50)");
            $oDB->createCommand("update {{permissions}} set entity='survey'")->query();
            addColumn('{{permissions}}', 'id', 'pk');
            $oDB->createCommand()->createIndex('idxPermissions', '{{permissions}}', 'entity_id,entity,permission,uid', true);
            upgradePermissions166();
            dropColumn('{{users}}', 'create_survey');
            dropColumn('{{users}}', 'create_user');
            dropColumn('{{users}}', 'delete_user');
            dropColumn('{{users}}', 'superadmin');
            dropColumn('{{users}}', 'configurator');
            dropColumn('{{users}}', 'manage_template');
            dropColumn('{{users}}', 'manage_label');
            dropColumn('{{users}}', 'participant_panel');
            $oDB->createCommand()->dropTable('{{templates_rights}}');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 166), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 167) {
            addColumn('{{surveys_languagesettings}}', 'attachments', 'text');
            addColumn('{{users}}', 'created', 'datetime');
            addColumn('{{users}}', 'modified', 'datetime');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 167), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 168) {
            addColumn('{{participants}}', 'created', 'datetime');
            addColumn('{{participants}}', 'modified', 'datetime');
            addColumn('{{participants}}', 'created_by', 'integer');
            $oDB->createCommand('update {{participants}} set created_by=owner_uid')->query();
            alterColumn('{{participants}}', 'created_by', "integer", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 168), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 169) {
            // Add new column for question index options.
            addColumn('{{surveys}}', 'questionindex', 'integer not null default 0');
            // Set values for existing surveys.
            $oDB->createCommand("update {{surveys}} set questionindex = 0 where allowjumps <> 'Y'")->query();
            $oDB->createCommand("update {{surveys}} set questionindex = 1 where allowjumps = 'Y'")->query();
            // Remove old column.
            dropColumn('{{surveys}}', 'allowjumps');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 169), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 170) {
            // renamed advanced attributes fields dropdown_dates_year_min/max
            $oDB->createCommand()->update('{{question_attributes}}', array('attribute' => 'date_min'), "attribute='dropdown_dates_year_min'");
            $oDB->createCommand()->update('{{question_attributes}}', array('attribute' => 'date_max'), "attribute='dropdown_dates_year_max'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 170), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 171) {
            try {
                dropColumn('{{sessions}}', 'data');
            } catch (Exception $e) {
            }
            switch (Yii::app()->db->driverName) {
                case 'mysql':
                case 'mysqli':
                    addColumn('{{sessions}}', 'data', 'longbinary');
                    break;
                case 'sqlsrv':
                case 'dblib':
                case 'mssql':
                    addColumn('{{sessions}}', 'data', 'VARBINARY(MAX)');
                    break;
                case 'pgsql':
                    addColumn('{{sessions}}', 'data', 'BYTEA');
                    break;
                default:
                    die('Unknown database type');
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 171), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 172) {
            switch (Yii::app()->db->driverName) {
                case 'pgsql':
                    // Special treatment for Postgres as it is too dumb to convert a string to a number without explicit being told to do so ... seriously?
                    alterColumn('{{permissions}}', 'entity_id', "INTEGER USING (entity_id::integer)", false);
                    break;
                case 'sqlsrv':
                case 'dblib':
                case 'mssql':
                    try {
                        setTransactionBookmark();
                        $oDB->createCommand()->dropIndex('permissions_idx2', '{{permissions}}');
                    } catch (Exception $e) {
                        rollBackToTransactionBookmark();
                    }
                    try {
                        setTransactionBookmark();
                        $oDB->createCommand()->dropIndex('idxPermissions', '{{permissions}}');
                    } catch (Exception $e) {
                        rollBackToTransactionBookmark();
                    }
                    alterColumn('{{permissions}}', 'entity_id', "INTEGER", false);
                    $oDB->createCommand()->createIndex('permissions_idx2', '{{permissions}}', 'entity_id,entity,permission,uid', true);
                    break;
                default:
                    alterColumn('{{permissions}}', 'entity_id', "INTEGER", false);
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 172), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 173) {
            addColumn('{{participant_attribute_names}}', 'defaultname', "string(50) NOT NULL default ''");
            upgradeCPDBAttributeDefaultNames173();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 173), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 174) {
            alterColumn('{{participants}}', 'email', "string(254)");
            alterColumn('{{saved_control}}', 'email', "string(254)");
            alterColumn('{{surveys}}', 'adminemail', "string(254)");
            alterColumn('{{surveys}}', 'bounce_email', "string(254)");
            switch (Yii::app()->db->driverName) {
                case 'sqlsrv':
                case 'dblib':
                case 'mssql':
                    dropUniqueKeyMSSQL('email', '{{users}}');
            }
            alterColumn('{{users}}', 'email', "string(254)");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 174), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 175) {
            switch (Yii::app()->db->driverName) {
                case 'pgsql':
                    // Special treatment for Postgres as it is too dumb to convert a boolean to a number without explicit being told to do so
                    alterColumn('{{plugins}}', 'active', "INTEGER USING (active::integer)", false);
                    break;
                default:
                    alterColumn('{{plugins}}', 'active', "integer", false, '0');
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 175), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 176) {
            upgradeTokens176();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 176), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 177) {
            if (Yii::app()->getConfig('auth_webserver') === true) {
                // using auth webserver, now activate the plugin with default settings.
                if (!class_exists('Authwebserver', false)) {
                    $plugin = Plugin::model()->findByAttributes(array('name' => 'Authwebserver'));
                    if (!$plugin) {
                        $plugin = new Plugin();
                        $plugin->name = 'Authwebserver';
                        $plugin->active = 1;
                        $plugin->save();
                        $plugin = App()->getPluginManager()->loadPlugin('Authwebserver', $plugin->id);
                        $aPluginSettings = $plugin->getPluginSettings(true);
                        $aDefaultSettings = array();
                        foreach ($aPluginSettings as $key => $settings) {
                            if (is_array($settings) && array_key_exists('current', $settings)) {
                                $aDefaultSettings[$key] = $settings['current'];
                            }
                        }
                        $plugin->saveSettings($aDefaultSettings);
                    } else {
                        $plugin->active = 1;
                        $plugin->save();
                    }
                }
            }
            upgradeSurveys177();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 177), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 178) {
            if (Yii::app()->db->driverName == 'mysql' || Yii::app()->db->driverName == 'mysqli') {
                modifyPrimaryKey('questions', array('qid', 'language'));
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 178), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 179) {
            upgradeSurveys177();
            // Needs to be run again to make sure
            upgradeTokenTables179();
            alterColumn('{{participants}}', 'email', "string(254)", false);
            alterColumn('{{participants}}', 'firstname', "string(150)", false);
            alterColumn('{{participants}}', 'lastname', "string(150)", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 179), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 180) {
            $aUsers = User::model()->findAll();
            $aPerm = array('entity_id' => 0, 'entity' => 'global', 'uid' => 0, 'permission' => 'auth_db', 'create_p' => 0, 'read_p' => 1, 'update_p' => 0, 'delete_p' => 0, 'import_p' => 0, 'export_p' => 0);
            foreach ($aUsers as $oUser) {
                if (!Permission::model()->hasGlobalPermission('auth_db', 'read', $oUser->uid)) {
                    $oPermission = new Permission();
                    foreach ($aPerm as $k => $v) {
                        $oPermission->{$k} = $v;
                    }
                    $oPermission->uid = $oUser->uid;
                    $oPermission->save();
                }
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 180), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 181) {
            upgradeTokenTables181();
            upgradeSurveyTables181();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 181), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 183) {
            upgradeSurveyTables183();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 183), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 184) {
            fixKCFinder184();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 184), "stg_name='DBVersion'");
        }
        // LS 2.5 table start at 250
        if ($iOldDBVersion < 250) {
            createBoxes250();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 250), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 251) {
            upgradeSurveyTables251();
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 251), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 252) {
            Yii::app()->db->createCommand()->addColumn('{{questions}}', 'modulename', 'string');
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 252), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 253) {
            upgradeSurveyTables253();
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 253), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 254) {
            upgradeSurveyTables254();
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 254), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 255) {
            upgradeSurveyTables255();
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 255), "stg_name='DBVersion'");
        }
        $oTransaction->commit();
        // Activate schema caching
        $oDB->schemaCachingDuration = 3600;
        // Load all tables of the application in the schema
        $oDB->schema->getTables();
        // clear the cache of all loaded tables
        $oDB->schema->refresh();
    } catch (Exception $e) {
        Yii::app()->setConfig('Updating', false);
        $oTransaction->rollback();
        // Activate schema caching
        $oDB->schemaCachingDuration = 3600;
        // Load all tables of the application in the schema
        $oDB->schema->getTables();
        // clear the cache of all loaded tables
        $oDB->schema->refresh();
        echo '<br /><br />' . gT('An non-recoverable error happened during the update. Error details:') . "<p>" . htmlspecialchars($e->getMessage()) . '</p><br />';
        return false;
    }
    fixLanguageConsistencyAllSurveys();
    Yii::app()->setConfig('Updating', false);
    return true;
}
Example #17
0
 /**
  * Install a plugin.
  *
  * This will activate the plugin, then run the 'install' hook.
  *
  * @param Plugin $plugin Plugin to install.
  * @throws Omeka_Plugin_Exception | Omeka_Plugin_Loader_Exception
  * @return void
  */
 public function install(Plugin $plugin)
 {
     if (!$plugin->getDirectoryName()) {
         throw new Omeka_Plugin_Installer_Exception(__('Plugin must have a valid directory name before it can be installed.'));
     }
     try {
         $plugin->setActive(true);
         $plugin->setDbVersion($plugin->getIniVersion());
         $plugin->save();
         // Force the plugin to load.  Will throw exception if plugin cannot be loaded for some reason.
         if (!$plugin->isLoaded()) {
             $this->_loader->load($plugin, true);
         }
         //Now run the installer for the plugin
         $this->_broker->callHook('install', array('plugin_id' => $plugin->id), $plugin);
     } catch (Exception $e) {
         //If there was an error, remove the plugin from the DB so that we can retry the install
         $plugin->delete();
         throw $e;
     }
 }
 function update_plugins()
 {
     trace(__FILE__, 'update_plugins()');
     $plugins = array_var($_POST, 'plugins');
     //$plugins = array('invoices' => '1');
     if (is_null($plugins)) {
         $this->redirectTo('administration', 'plugins');
     }
     $reference = Plugins::getAllPlugins();
     trace(__FILE__, 'update_plugins() - getAllPlugins done');
     $errors = array();
     foreach ($plugins as $name => $yes_no) {
         //If it is not a plugin continue
         $plugin_file_path = APPLICATION_PATH . '/plugins/' . $name . '/init.php';
         trace(__FILE__, "update_plugins() - plugin_file_path=[{$plugin_file_path}]");
         if (!file_exists($plugin_file_path)) {
             continue;
         }
         trace(__FILE__, "update_plugins() - plugin_file_path=[{$plugin_file_path}] exists");
         // get existing id
         $id = $reference[$name];
         $nicename = ucwords(str_replace('_', ' ', $name));
         trace(__FILE__, "update_plugins() - id={$id} name={$name} nicename={$nicename}");
         if ($yes_no && '-' == $id) {
             trace(__FILE__, "update_plugins() - activating [{$name}]");
             try {
                 // Check if plugin exists in database
                 $plugin = Plugins::findOne(array('conditions' => array('`name` = ?', $name)));
                 trace(__FILE__, "update_plugins() - findOne");
                 if ($plugin == NULL) {
                     $plugin = new Plugin();
                 }
                 trace(__FILE__, "update_plugins() - setName");
                 $plugin->setName($name);
                 trace(__FILE__, "update_plugins() - setInstalled");
                 $plugin->setInstalled(true);
                 DB::beginWork();
                 trace(__FILE__, "update_plugins() - including [{$plugin_file_path}]");
                 // get the file loaded here
                 include $plugin_file_path;
                 // get activation routine ready
                 trace(__FILE__, "update_plugins() - activate: {$name}");
                 $activate = $name . '_activate';
                 if (function_exists($activate)) {
                     trace(__FILE__, "update_plugins() - calling: {$activate}");
                     $activate();
                 }
                 // save to db now
                 $plugin->save();
                 DB::commit();
             } catch (Exception $e) {
                 trace(__FILE__, 'update_plugins() - ' . $e->getMessage());
                 DB::rollback();
                 $errors[] = $nicename . ' (' . $e->getMessage() . ')';
             }
         } elseif (!$yes_no && '-' != $id) {
             try {
                 trace(__FILE__, "update_plugins() - deactivating [{$name}]");
                 $plugin = Plugins::findById($id);
                 DB::beginWork();
                 $deactivate = $name . '_deactivate';
                 if (function_exists($deactivate)) {
                     trace(__FILE__, "update_plugins() - calling {$deactivate}");
                     //Check if user choose to purge data
                     if ($plugins[$name . "_data"] == "0") {
                         trace(__FILE__, "update_plugins() - calling {$deactivate}(true)");
                         $deactivate(true);
                     } else {
                         $deactivate();
                     }
                 }
                 $plugin->setInstalled(false);
                 $plugin->save();
                 DB::commit();
             } catch (Exception $e) {
                 DB::rollback();
                 $errors[] = $nicename . ' (' . $e->getMessage() . ')';
             }
         }
     }
     if (count($errors)) {
         flash_error(lang('plugin activation failed', implode(", ", $errors)));
     } else {
         flash_success(lang('plugins updated'));
     }
     $this->redirectTo('administration', 'plugins');
 }
 /**
  * プラグインのステータスを更新する
  *
  * @return boolean
  * @access	protected
  */
 function _updatePluginStatus()
 {
     $db =& $this->_connectDb($this->_readDbSettingFromSession());
     $version = $this->getBaserVersion();
     App::import('Model', 'Plugin');
     $Plugin = new Plugin();
     $datas = $Plugin->find('all');
     if ($datas) {
         $result = true;
         foreach ($datas as $data) {
             $data['Plugin']['version'] = $version;
             $data['Plugin']['status'] = true;
             if (!$Plugin->save($data)) {
                 $result = false;
             }
         }
         return $result;
     } else {
         return false;
     }
 }
Example #20
0
 function index()
 {
     if (!$this->auth) {
         $this->error('401', 'Not authorized to perform this action.');
         return;
     }
     list($params, $id) = $this->parse_params(func_get_args());
     $plugins = $this->parse_plugins();
     $db_config = Shutter::get_db_configuration();
     switch ($this->method) {
         case 'delete':
             $p = new Plugin();
             $p->where('id', $id)->get();
             if ($p->exists()) {
                 $p->run_plugin_method('after_uninstall', $plugins);
                 $plugin = $p->init($plugins);
                 if ($plugin->database_fields) {
                     $this->load->dbforge();
                     foreach ($plugin->database_fields as $table => $fields) {
                         $table = $db_config['prefix'] . $table;
                         foreach ($fields as $column => $info) {
                             $this->dbforge->drop_column($table, $column);
                         }
                     }
                     $this->_clear_datamapper_cache();
                 }
                 $p->delete();
             }
             $this->_compile_plugins();
             exit;
             break;
         case 'post':
             $p = new Plugin();
             $p->path = $_POST['path'];
             $p->setup = $p->run_plugin_method('require_setup', $plugins) === false;
             if ($p->save()) {
                 $plugin = $p->init($plugins);
                 if ($plugin->database_fields) {
                     $this->load->dbforge();
                     foreach ($plugin->database_fields as $table => $fields) {
                         $table = $db_config['prefix'] . $table;
                         foreach ($fields as $column => $info) {
                             $this->dbforge->add_column($table, array($column => $info));
                         }
                     }
                     $this->_clear_datamapper_cache();
                 }
                 $p->run_plugin_method('after_install', $plugins);
             }
             $this->_compile_plugins();
             $this->redirect('/plugins');
             break;
         case 'put':
             unset($_POST['_method']);
             $data = serialize($_POST);
             $p = new Plugin();
             $p->where('id', $id)->get();
             $p->save_data($plugins, $_POST);
             $validate = $p->run_plugin_method('confirm_setup', $plugins, $data);
             if ($validate === true) {
                 $p->setup = 1;
                 $p->save();
                 $this->_compile_plugins();
                 exit;
             } else {
                 $this->error(400, $validate);
                 return;
             }
             break;
         default:
             $data = array('plugins' => $plugins);
             function sortByName($a, $b)
             {
                 return $a['name'] > $b['name'];
             }
             usort($data['plugins'], 'sortByName');
             $data['plugins'] = Shutter::filter('api.plugins', array($data['plugins']));
             $data['custom_sources'] = Shutter::$custom_sources;
             $this->set_response_data($data);
             break;
     }
 }
Example #21
0
 /**
  * Updates a plugin
  *
  * @param int $id The vacation ID
  * @param array $data
  * @return int The vacation ID
  */
 public function do_update($id, $data)
 {
     $user = $this->requireUser();
     if (!$user->isAdmin()) {
         throw new Exception('Non-administrative user "' . $user->getFQN() . '" cannot modify plugins.');
     }
     // Validate input data
     $validator = new KickstartValidator();
     $locale = Localizer::getInstance();
     $warnings = $validator->filterErrors($data, $this->initFilter($this->filter_basic, $locale));
     if ($warnings) {
         return array('result' => false, 'warnings' => $warnings);
     }
     $query = PluginQuery::create()->filterByAccount($user->getAccount());
     if ($id) {
         $query->filterById($id, Criteria::NOT_EQUAL);
         $plugin = PluginQuery::create()->filterByAccount($user->getAccount())->findOneById($id);
         if (!$plugin) {
             throw new Exception('Plugin not found; ID: ' . $id);
         }
     } else {
         $plugin = new Plugin();
     }
     // Check for duplicates
     if ($query->findOneByIdentifier($data['Name'])) {
         throw new Exception($locale->insert('error.taken', array('value' => '"' . $data['Name'] . '"')));
     }
     if (isset($data['Start'])) {
         $plugin->setStart(strtotime($data['Start'] . 'Z', 0));
         unset($data['Start']);
     }
     $plugin->fromArray($data);
     $plugin->setAccount($user->getAccount());
     $plugin->save();
     return $plugin->getId();
 }
Example #22
0
 /**
  * Show list of plugins
  *
  * @return void
  */
 public function actionIndex()
 {
     if (!Permission::model()->hasGlobalPermission('settings', 'read')) {
         Yii::app()->session['flashmessage'] = gT('Access denied!');
         $this->redirect($this->createUrl("/admin"));
     }
     $oPluginManager = App()->getPluginManager();
     // Scan the plugins folder.
     $aDiscoveredPlugins = $oPluginManager->scanPlugins();
     $aInstalledPlugins = $oPluginManager->getInstalledPlugins();
     $aInstalledNames = array_map(function ($installedPlugin) {
         return $installedPlugin->name;
     }, $aInstalledPlugins);
     // Install newly discovered plugins.
     foreach ($aDiscoveredPlugins as $discoveredPlugin) {
         if (!in_array($discoveredPlugin['pluginClass'], $aInstalledNames)) {
             $oPlugin = new Plugin();
             $oPlugin->name = $discoveredPlugin['pluginClass'];
             $oPlugin->active = 0;
             $oPlugin->save();
         }
     }
     $aoPlugins = Plugin::model()->findAll();
     $data = array();
     foreach ($aoPlugins as $oPlugin) {
         /* @var $plugin Plugin */
         if (array_key_exists($oPlugin->name, $aDiscoveredPlugins)) {
             $aPluginSettings = App()->getPluginManager()->loadPlugin($oPlugin->name, $oPlugin->id)->getPluginSettings(false);
             $data[] = array('id' => $oPlugin->id, 'name' => $aDiscoveredPlugins[$oPlugin->name]['pluginName'], 'description' => $aDiscoveredPlugins[$oPlugin->name]['description'], 'active' => $oPlugin->active, 'settings' => $aPluginSettings, 'new' => !in_array($oPlugin->name, $aInstalledNames));
         } else {
             // This plugin is missing, maybe the files were deleted but the record was not removed from the database
             // Now delete this record. Depending on the plugin the settings will be preserved
             App()->user->setFlash('pluginDelete' . $oPlugin->id, sprintf(gT("Plugin '%s' was missing and is removed from the database."), $oPlugin->name));
             $oPlugin->delete();
         }
     }
     echo $this->render('/plugins/index', compact('data'));
 }
Example #23
0
 /**
  * プラグインのステータスを更新する
  *
  * @return boolean
  * @access	protected
  */
 protected function _updatePluginStatus($dbConfig)
 {
     $db = $this->_getDataSource('baser', $dbConfig);
     $db->truncate('plugins');
     $version = getVersion();
     $Plugin = new Plugin();
     $corePlugins = Configure::read('BcApp.corePlugins');
     $result = true;
     $priority = intval($Plugin->getMax('priority')) + 1;
     foreach ($corePlugins as $corePlugin) {
         $data = array();
         include BASER_PLUGINS . $corePlugin . DS . 'config.php';
         $data['Plugin']['name'] = $corePlugin;
         $data['Plugin']['title'] = $title;
         $data['Plugin']['version'] = $version;
         $data['Plugin']['status'] = true;
         $data['Plugin']['db_inited'] = false;
         $data['Plugin']['priority'] = $priority;
         $Plugin->create($data);
         if (!$Plugin->save()) {
             $result = false;
         }
         $priority++;
     }
     return $result;
 }
Example #24
0
    } elseif (file_exists($baserPath)) {
        $path = $baserPath;
    }
    $data['Plugin']['name'] = $plugin;
    $data['Plugin']['status'] = false;
    if ($path) {
        include $path;
        if (isset($title)) {
            $data['Plugin']['title'] = $title;
        }
    }
    $version = $this->getBaserVersion($plugin);
    if ($version && !preg_match('/^Baser/', $version)) {
        $data['Plugin']['version'] = $version;
    }
    if (!$Plugin->save($data)) {
        $result = false;
    }
}
if ($result) {
    $this->setMessage('plugins テーブルの更新に成功しました。');
} else {
    $this->setMessage('plugins テーブルの更新に失敗しました。', true);
}
/**
 * スキーマ用の一時フォルダを作成する
 */
checkTmpFolders();
/**
 * プラグインの有効化を促すメッセージを追加
 */
Example #25
0
function install($pattern)
{
    if (is_git_url($pattern)) {
        // checkout git repository into tmp directory
        // ROOT_PATH . "plugins" . DIRECTORY_SEPARATOR
        print "Try loading the plugin from " . $pattern . "... \n";
        $tmp_name = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'tmp-' . time();
        exec('git clone ' . $pattern . ' ' . $tmp_name . ' 2>&1', $ret, $err);
        $pkg_info = $tmp_name . DIRECTORY_SEPARATOR . 'package.json';
        if (file_exists($pkg_info)) {
            try {
                $pkg_info = json_decode(file_get_contents($pkg_info), true);
            } catch (Error $e) {
                print 'Not a valid plugin: package.json could not be read.';
                return true;
            }
            if (!empty($pkg_info['name'])) {
                $plugin_path = ROOT_PATH . 'plugins' . DIRECTORY_SEPARATOR . $pkg_info['name'];
                if (!file_exists($plugin_path)) {
                    rename($tmp_name, $plugin_path);
                    $pattern = $pkg_info['name'];
                    // proceed with this id
                } else {
                    print 'Plugin ' . $pkg_info['name'] . ' is already installed';
                    return true;
                }
            } else {
                print 'No name specified in package.json.';
                return true;
            }
        } else {
            print 'No package.json found in repository';
            return true;
        }
    }
    _apply($pattern, function ($id) {
        $tmp = new Plugin();
        $tmp->setId($id);
        // check if plugin files exist
        if (!file_exists($tmp->getPath())) {
            global $plugin_urls;
            if ($plugin_urls) {
                if (isset($plugin_urls[$id])) {
                    print "Found " . $id . " in plugins.json.\n";
                    install($plugin_urls[$id]);
                    // try installing from git repository
                    return true;
                    // cancel apply loop
                }
            }
            print "No plugin found with that name. Skipping.\n";
            return true;
            // cancel apply loop
        }
        if (!file_exists($tmp->getPath() . 'package.json')) {
            print "Path exists, but no package.json found. Skipping.\n";
            return true;
            // cancel apply loop
        }
        // check if plugin is already installed
        $plugin = PluginQuery::create()->findPk($id);
        if ($plugin) {
            _loadPluginClass($plugin)->install();
            print "Re-installed plugin {$id}.\n";
        } else {
            $plugin = new Plugin();
            $plugin->setId($id);
            $plugin->save();
            _loadPluginClass($plugin)->install();
            print "Installed plugin {$id}.\n";
        }
        global $argv;
        if ($argv[count($argv) - 1] == '--private') {
            $plugin->setIsPrivate(true);
            $plugin->save();
            print "Set plugin {$id} to private.\n";
        }
    });
}
Example #26
0
require_once "../initialise_files.php";
include_once "sessioninc.php";
if (!empty($_GET['id']) && !empty($_GET['action'])) {
    $id = $_GET['id'];
    $action = $_GET['action'];
    $plugin = new Plugin();
    $plugin->id = $id;
    if ($action == 'install') {
        $plugin->enabled = 'Y';
        $plugin->plugin_check($id, 'Y');
    } else {
        $plugin->enabled = 'N';
        $plugin->plugin_check($id, 'N');
    }
    if ($plugin->save()) {
        $session->message("<div class='success'> Plugin has been updated successfully. </div>");
        redirect_to($_SERVER['PHP_SELF']);
        die;
    } else {
        $session->message("<div class='error'> Plugin has not been updated. </div>");
        redirect_to($_SERVER['PHP_SELF']);
        die;
    }
}
$plugin_arr = Plugin::find_all();
//print_r($plugin_arr);
$manage_lists = array();
if ($plugin_arr && is_array($plugin_arr)) {
    $i = 1;
    foreach ($plugin_arr as $list) {
	final public static function failInstall($plugin,$message=false) {
		if ( $message === false ) $message = self::$LAST_ERROR;
		unset(Plugin::$plugins[$plugin]);
		Plugin::save();
		Flash::set('error',$message);
		exit;
	}
Example #28
0
 /**
  * Show login screen and parse login data
  */
 public function index()
 {
     $this->_redirectIfLoggedIn();
     // Make sure after first run / update the authdb plugin is registered and active
     // it can not be deactivated
     if (!class_exists('Authdb', false)) {
         $plugin = Plugin::model()->findByAttributes(array('name' => 'Authdb'));
         if (!$plugin) {
             $plugin = new Plugin();
             $plugin->name = 'Authdb';
             $plugin->active = 1;
             $plugin->save();
             App()->getPluginManager()->loadPlugin('Authdb', $plugin->id);
         } else {
             $plugin->active = 1;
             $plugin->save();
         }
     }
     $beforeLogin = new PluginEvent('beforeLogin');
     $beforeLogin->set('identity', new LSUserIdentity('', ''));
     App()->getPluginManager()->dispatchEvent($beforeLogin);
     /* @var $identity LSUserIdentity */
     $identity = $beforeLogin->get('identity');
     if (!$beforeLogin->isStopped() && is_null(App()->getRequest()->getPost('login_submit'))) {
         if (!is_null($beforeLogin->get('default'))) {
             $aData['defaultAuth'] = $beforeLogin->get('default');
         } else {
             if (App()->getPluginManager()->isPluginActive(Yii::app()->getConfig('default_displayed_auth_method'))) {
                 $aData['defaultAuth'] = Yii::app()->getConfig('default_displayed_auth_method');
             } else {
                 $aData['defaultAuth'] = 'Authdb';
             }
         }
         $newLoginForm = new PluginEvent('newLoginForm');
         App()->getPluginManager()->dispatchEvent($newLoginForm);
         $aData['summary'] = $this->_getSummary('logout');
         $aData['pluginContent'] = $newLoginForm->getAllContent();
         $this->_renderWrappedTemplate('authentication', 'login', $aData);
     } else {
         // Handle getting the post and populating the identity there
         $authMethod = App()->getRequest()->getPost('authMethod', $identity->plugin);
         $identity->plugin = $authMethod;
         $event = new PluginEvent('afterLoginFormSubmit');
         $event->set('identity', $identity);
         App()->getPluginManager()->dispatchEvent($event, array($authMethod));
         $identity = $event->get('identity');
         // Now authenticate
         if ($identity->authenticate()) {
             FailedLoginAttempt::model()->deleteAttempts();
             App()->user->setState('plugin', $authMethod);
             $this->getController()->_GetSessionUserRights(Yii::app()->session['loginID']);
             Yii::app()->session['just_logged_in'] = true;
             Yii::app()->session['loginsummary'] = $this->_getSummary();
             $event = new PluginEvent('afterSuccessfulLogin');
             App()->getPluginManager()->dispatchEvent($event);
             $this->_doRedirect();
         } else {
             // Failed
             $event = new PluginEvent('afterFailedLoginAttempt');
             $event->set('identity', $identity);
             App()->getPluginManager()->dispatchEvent($event);
             $message = $identity->errorMessage;
             if (empty($message)) {
                 // If no message, return a default message
                 $message = gT('Incorrect username and/or password!');
             }
             App()->user->setFlash('error', $message);
             $this->getController()->redirect(array('/admin/authentication/sa/login'));
         }
     }
 }
 static function getPluginsFromFileSystem()
 {
     $plugins_path = array();
     foreach (glob(SITEPATH . "plugins/*/") as $dir) {
         $plugins_path[] = $dir;
     }
     foreach (glob(SITEPATH . "core_plugins/*/") as $dir) {
         $plugins_path[] = $dir;
     }
     foreach ($plugins_path as $path) {
         if (file_exists($path . "manifest.json")) {
             $json = file_get_contents($path . "manifest.json");
             $manifest = json_decode($json, true);
             $plugin_name = $manifest['name'];
             $plugin_label = $manifest['label'];
             $plugin_requires = isset($manifest['requires']) ? $manifest['requires'] : array();
             // check if this plugin exists in database and update it if it does
             $existing_plugin = getEntity(array("type" => "Plugin", "metadata_name" => "name", "metadata_value" => $plugin_name));
             if (!$existing_plugin) {
                 $existing_plugin = new Plugin();
                 $existing_plugin->name = $plugin_name;
                 $existing_plugin->requires = $plugin_requires;
                 $existing_plugin->label = $plugin_label;
             }
             $existing_plugin->save();
         }
     }
     new Cache("enabled_plugins_", false, "site");
     new Cache("enabled_plugins_reversed", false, "site");
 }