Example #1
0
function zero_upgrade()
{
    global $_TABLES, $_CONF, $_ZZ_CONF, $_DB_table_prefix;
    $currentVersion = DB_getItem($_TABLES['plugins'], 'pi_version', "pi_name='zero'");
    switch ($currentVersion) {
        case '0.0.5':
            $_SQL['widgets'] = "CREATE TABLE IF NOT EXISTS {$_TABLES['widgets']} (\n                widget_id mediumint(8) NOT NULL auto_increment,\n                widget_desc varchar(64) NOT NULL default '',\n                PRIMARY KEY (widget_id)\n                ) TYPE=MyISAM;";
            DB_query($_SQL['widgets'], 1);
        case '0.0.6':
            $_SQL['gadgets'] = "CREATE TABLE IF NOT EXISTS {$_TABLES['gadgets']} (\n                gadget_id mediumint(8) NOT NULL auto_increment,\n                gadget_desc varchar(64) NOT NULL default '',\n                PRIMARY KEY (gadget_id)\n                ) TYPE=MyISAM;";
            DB_query($_SQL['gadgets'], 1);
            // you should really list a case for each version you release, however
            // the default case is the catch-all, which just updates pi_version to
            // match the current code version
        // you should really list a case for each version you release, however
        // the default case is the catch-all, which just updates pi_version to
        // match the current code version
        case '1.0.0':
        case '1.1.0':
        case '1.1.1':
        case '1.1.2':
        default:
            DB_query("UPDATE {$_TABLES['plugins']} SET pi_version='{$_ZZ_CONF['pi_version']}',pi_gl_version='{$_ZZ_CONF['pi_gl_version']}' WHERE pi_name='zero' LIMIT 1");
            break;
    }
    // clear the template cache because this plugin may create changes
    CTL_clearCache();
    // if upgrade succeeded, the plugin version in the plugins table will match
    // the version of the currently installed plugin
    return DB_getItem($_TABLES['plugins'], 'pi_version', "pi_name='zero'") == $_ZZ_CONF['pi_version'];
}
Example #2
0
 function INSTALLER_install($A)
 {
     global $_TABLES;
     COM_errorLog("AutoInstall: **** Start Installation ****");
     if (!isset($A['installer']) or $A['installer']['version'] != INSTALLER_VERSION) {
         COM_errorLog('AutoInstall: Invalid or Unknown installer version');
         COM_errorLog("AutoInstall: **** END Installation ****");
         return 2;
     }
     if (!isset($A['plugin'])) {
         COM_errorLog("AutoInstall: Missing plugin description!");
         COM_errorLog("AutoInstall: **** END Installation ****");
         return 1;
     }
     if (!isset($A['plugin']['name'])) {
         COM_errorLog("AutoInstall: Missing plugin name!");
         COM_errorLog("AutoInstall: **** END Installation ****");
         return 1;
     }
     if (!COM_checkVersion(GVERSION, $A['plugin']['gl_ver'])) {
         COM_errorLog("AutoInstall: Plugin requires glFusion v" . $A['plugin']['gl_ver'] . " or greater");
         COM_errorLog("AutoInstall: **** END Installation ****");
         return 1;
     }
     $pluginName = $A['plugin']['name'];
     $vars = array('__groups' => array(), '__features' => array(), '__blocks' => array());
     $reverse = array();
     foreach ($A as $meta => $step) {
         if ($meta === 'installer') {
             // must use === when since 0 == 'anystring' is true
         } elseif ($meta === 'plugin') {
             if (!isset($step['name'])) {
                 COM_errorLog("AutoInstall: Missing plugin name!");
                 INSTALLER_fail($pluginName, $reverse);
                 COM_errorLog("AutoInstall: **** END Installation ****");
                 return 1;
             }
         } else {
             $function = "INSTALLER_install_{$step['type']}";
             if (function_exists($function)) {
                 $result = $function($step, $vars);
                 if (is_numeric($result)) {
                     INSTALLER_fail($pluginName, $reverse);
                     COM_errorLog("AutoInstall: **** END Installation ****");
                     return $result;
                 } else {
                     if (!empty($result)) {
                         $reverse[] = $result;
                     }
                 }
             } else {
                 $dump = var_dump($step);
                 COM_errorLog('Can\'t process step: ' . $dump);
                 INSTALLER_fail($pluginName, $reverse);
                 COM_errorLog("AutoInstall: **** END Installation ****");
                 return 1;
             }
         }
     }
     $plugin = $A['plugin'];
     $cfgFunction = 'plugin_load_configuration_' . $plugin['name'];
     // Load the online configuration records
     if (function_exists($cfgFunction)) {
         if (!$cfgFunction()) {
             COM_errorLog("AutoInstall: Failed to load the default configuration");
             INSTALLER_fail($pluginName, $reverse);
             COM_errorLog("AutoInstall: **** END Installation ****");
             return 1;
         }
     } else {
         COM_errorLog("AutoInstall: No default config found: " . $cfgFunction);
     }
     // Finally, register the plugin with glFusion
     COM_errorLog("AutoInstall: Registering {$plugin['display']} plugin with glFusion", 1);
     // silently delete an existing entry
     DB_delete($_TABLES['plugins'], 'pi_name', $plugin['name']);
     DB_query("INSERT INTO {$_TABLES['plugins']} (pi_name, pi_version, pi_gl_version, pi_homepage, pi_enabled) " . "VALUES ('{$plugin['name']}', '{$plugin['ver']}', '{$plugin['gl_ver']}', '{$plugin['url']}', 1)", 1);
     // run any post install routines
     $postInstallFunction = 'plugin_postinstall_' . $plugin['name'];
     if (function_exists($postInstallFunction)) {
         $postInstallFunction();
     } else {
         COM_errorLog("AutoInstall: No post installation routine found.");
     }
     COM_errorLog("AutoInstall: **** END Installation ****");
     CTL_clearCache();
     return 0;
 }
Example #3
0
/**
 * Re-orders all routes in increments of 10
 */
function reorderRoutes()
{
    global $_TABLES;
    $sql = "SELECT rid FROM {$_TABLES['routes']} ORDER BY priority";
    $result = DB_query($sql);
    $rids = array();
    while (($A = DB_fetchArray($result, false)) !== false) {
        $rids[] = intval($A['rid'], 10);
    }
    $priority = 100;
    $step = 10;
    foreach ($rids as $rid) {
        $sql = "UPDATE {$_TABLES['routes']} SET priority = " . DB_escapeString($priority) . " WHERE rid = " . DB_escapeString($rid);
        DB_query($sql);
        $priority += $step;
    }
    // Clear the cache once reordered so any updated urls can be refreshed
    // reorderRoutes is called by save and delete so it covers those instances as well
    CTL_clearCache();
}
Example #4
0
/**
* Toggle status of a plugin from enabled to disabled and back
*
* @param    string  $pi_name    name of the plugin
* @return   void
*
*/
function PLUGINS_toggleStatus($plugin_name_arr, $pluginarray)
{
    global $_TABLES, $_PLUGIN_INFO, $_DB_table_prefix;
    if (isset($pluginarray) && is_array($pluginarray)) {
        foreach ($pluginarray as $plugin => $junk) {
            $plugin = COM_applyFilter($plugin);
            if (isset($plugin_name_arr[$plugin])) {
                DB_query("UPDATE {$_TABLES['plugins']} SET pi_enabled = '1' WHERE pi_name = '" . DB_escapeString($plugin) . "'");
                $_PLUGIN_INFO[$plugin] = DB_getItem($_TABLES['plugins'], 'pi_version', "pi_name='" . DB_escapeString($plugin) . "'");
                PLG_enableStateChange($plugin, true);
            } else {
                $rc = PLG_enableStateChange($plugin, false);
                if ($rc != 99) {
                    DB_query("UPDATE {$_TABLES['plugins']} SET pi_enabled = '0' WHERE pi_name = '" . DB_escapeString($plugin) . "'");
                }
            }
        }
    }
    CTL_clearCache();
    return;
}
Example #5
0
/**
* Toggle status of a staticpage from enabled to disabled and back
*
* @param    array   $enabledstaticpages    array of sp_id's available
* @param    array   $spidarray             array of status (1/0)
* @return   void
*
*/
function PAGE_toggleStatus($enabledstaticpages, $sp_idarray)
{
    global $_TABLES, $_DB_table_prefix;
    if (isset($sp_idarray) && is_array($sp_idarray)) {
        foreach ($sp_idarray as $sp_id => $junk) {
            $sp_id = COM_applyFilter($sp_id);
            if (isset($enabledstaticpages[$sp_id])) {
                DB_query("UPDATE {$_TABLES['staticpage']} SET sp_status = '1' WHERE sp_id = '" . DB_escapeString($sp_id) . "'");
            } else {
                DB_query("UPDATE {$_TABLES['staticpage']} SET sp_status = '0' WHERE sp_id = '" . DB_escapeString($sp_id) . "'");
            }
        }
    }
    PLG_itemSaved($sp_id, 'staticpages');
    CTL_clearCache();
}
Example #6
0
/**
*   Upgrade to version 1.3.0
*   Many changes in this version, so a function was created to
*   hold them all.
*
*   @return boolean     True on success, False on failure
*/
function evlist_upgrade_1_3_0()
{
    global $_CONF, $_EV_CONF, $_TABLES, $_DB_dbms, $c, $CONF_EVLIST_DEFAULT;
    USES_evlist_class_event();
    $c->add('default_view', $CONF_EVLIST_DEFAULT['default_view'], 'select', 0, 1, 14, 90, true, 'evlist');
    $c->add('max_upcoming_days', $CONF_EVLIST_DEFAULT['max_upcoming_days'], 'text', 0, 1, 0, 100, true, 'evlist');
    // Combine users allowed to add events into one variable
    $can_add = 0;
    if ($EV_CONF['allow_anon_add'] > 0) {
        $can_add += EV_ANON_CAN_ADD;
    }
    if ($EV_CONF['allow_user_add'] > 0) {
        $can_add += EV_USER_CAN_ADD;
    }
    $c->add('can_add', $can_add, 'select', 0, 1, 15, 20, true, 'evlist');
    $c->del('allow_user_add', 'evlist');
    $c->del('allow_anon_add', 'evlist');
    // Add new options for plugin integration
    $c->add('use_locator', $CONF_EVLIST_DEFAULT['use_locator'], 'select', 0, 1, 0, 110, true, 'evlist');
    $c->add('use_weather', $CONF_EVLIST_DEFAULT['use_weather'], 'select', 0, 1, 0, 120, true, 'evlist');
    // Date & Time formats moved from the DB to simple $_CONF  variables
    $format = DB_getItem($_TABLES['evlist_dateformat'], 'format', "id='{$_EV_CONF['date_format']}'");
    if (empty($format)) {
        $format = '%a %b %d, %Y';
    }
    $c->set_default('date_format', $format, 'evlist');
    $c->set('date_format', $format, 'evlist');
    $format = DB_getItem($_TABLES['evlist_timeformat'], 'format', "id='{$_EV_CONF['date_format']}'");
    if (empty($format)) {
        $format = '%I:%M %p';
    }
    $c->set_default('time_format', $format, 'evlist');
    $c->set('time_format', $format, 'evlist');
    DB_query("DROP TABLE {$_TABLES['evlist_dateformat']}");
    DB_query("DROP TABLE {$_TABLES['evlist_timeformat']}");
    // Change feature name
    DB_query("UPDATE {$_TABLES['features']}\n                SET ft_name='evlist.admin' WHERE ft_name='evlist.edit'");
    // Add new "submit" feature & map to Root group
    DB_query("INSERT INTO {$_TABLES['features']} (ft_name, ft_descr)\n            VALUES ('evlist.submit', \n                    'Allowed to bypass the evList submission queue')", 1);
    if (!DB_error()) {
        $ft_id = (int) DB_insertId();
        if ($ft_id > 0) {
            DB_query("INSERT INTO {$_TABLES['access']} (acc_ft_id, acc_grp_id)\n                    VALUES('{$ft_id}', '1')");
        }
    }
    EVLIST_do_upgrade_sql('1.3.0');
    // Add the new fields to the event & submission tables
    /*$new_sql = "ADD det_id int(10) NOT NULL,
              ADD show_upcoming tinyint(1) unsigned NOT NULL DEFAULT '1',
              ADD cal_id int(10) unsigned NOT NULL DEFAULT '1',
              ADD options varchar(255)";
      DB_query("ALTER TABLE {$_TABLES['evlist_events']} $new_sql");
      DB_query("ALTER TABLE {$_TABLES['evlist_submissions']} $new_sql");*/
    // Create the new tables
    /*DB_query($_SQL['evlist_repeat']);
      DB_query($_SQL['evlist_calendars']);
      DB_query($_SQL['evlist_detail']);
      DB_query($DEFVALUES['evlist_calendars']);*/
    // Now split out the detail and create the repeats
    $result = DB_query("SELECT * FROM {$_TABLES['evlist_events']}");
    $error = 0;
    while ($A = DB_fetchArray($result, false)) {
        $A = array_map('DB_escapeString', $A);
        $sql = "INSERT INTO {$_TABLES['evlist_detail']} (\n                    ev_id, title, summary, full_description, url, location,\n                    street, city, province, country, postal, contact,\n                    email, phone\n                ) VALUES (\n                    '{$A['id']}', '{$A['title']}', '{$A['summary']}', \n                    '{$A['full_description']}', '{$A['url']}',\n                    '{$A['location']}', '{$A['street']}',\n                    '{$A['city']}', '{$A['province']}',\n                    '{$A['country']}', '{$A['postal']}',\n                    '{$A['contact']}', '{$A['email']}','{$A['phone']}'\n                )";
        DB_query($sql, 1);
        if (DB_error()) {
            $error = 1;
            break;
        } else {
            $DB_det_id = DB_insertID();
        }
        $rec_data = array();
        if ($A['recurring'] == 1) {
            $rec_data['type'] = $A['rec_option'];
            switch ($A['rec_option']) {
                case EV_RECUR_DAILY:
                case EV_RECUR_MONTHLY:
                case EV_RECUR_YEARLY:
                    list($stop, $skip) = explode(';', $A['rec_data']);
                    if (!empty($skip)) {
                        $rec_data['skip'] = (int) $skip;
                    }
                    break;
                case EV_RECUR_WEEKLY:
                    list($listdays, $stop) = explode(';', $A['rec_data']);
                    $rec_data['listdays'] = explode(',', $listdays);
                    break;
                case EV_RECUR_DOM:
                    list($interval, $weekday, $stop) = explode(';', $A['rec_data']);
                    $rec_data['weekday'] = $weekday;
                    $rec_data['interval'] = $interval;
                    break;
                case EV_RECUR_DATES:
                    $rec_data['custom'] = explode(',', $A['rec_data']);
                    $stop = 'XX';
                    // unused flag
                    break;
            }
            // switch recurring type
            // Check the stop date for validity and format it properly
            if ($stop != 'XX') {
                if (strtotime($stop) > strtotime('2037-01-01') || $stop < '1970-01-01') {
                    $stop = '2037-12-31';
                }
                list($y, $m, $d) = explode('-', $stop);
                $rec_data['stop'] = sprintf('%d-%02d-%02d', $y, $m, $d);
            }
        } else {
            // not a recurring event
            $rec_data['type'] = 0;
        }
        $DB_rec_data = DB_escapeString(serialize($rec_data));
        $sql = "UPDATE {$_TABLES['evlist_events']} SET\n                    rec_data = '{$DB_rec_data}',\n                    det_id = '{$DB_det_id}'\n                WHERE id='{$A['id']}'";
        DB_query($sql, 1);
        if (DB_error()) {
            $error = 1;
            break;
        }
        // Now that the updated info is saved to the event record,
        // use the evEvent class to create the repeats
        $Ev = new evEvent($A['id']);
        $Ev->UpdateRepeats();
    }
    // for each event record
    if ($error == 0) {
        // Now drop the no-longer-used fields
        $alter_sql = "DROP title, DROP summary, DROP full_description,\n                DROP date_start2, DROP date_end2,\n                DROP url, DROP location, DROP street, DROP city,\n                DROP province, DROP country, DROP postal, DROP contact,\n                DROP email, DROP phone";
        DB_query("ALTER TABLE {$_TABLES['evlist_events']} {$alter_sql}");
        DB_query("ALTER TABLE {$_TABLES['evlist_submissions']} {$alter_sql}");
        DB_query("ALTER TABLE {$_TABLES['evlist_remlookup']}\n                DROP id,\n                ADD rp_id int(10) unsigned NOT NULL default 0 AFTER eid,\n                DROP date_start,\n                DROP timestamp");
        // Add new options.  Set values to emulate current behavior.
        $options = array('contactlink' => 1);
        $opt_str = DB_escapeString(serialize($options));
        DB_query("UPDATE {$_TABLES['evlist_events']} SET options='{$opt_str}'");
        DB_query("UPDATE {$_TABLES['evlist_submissions']} SET options='{$opt_str}'");
    }
    CTL_clearCache();
    // Clear cache to activate new configuration items.
    return $error;
}
Example #7
0
/**
* Toggle status of a staticpage from enabled to disabled and back
*
* @param    array   $enabledstaticpages    array of sp_id's available
* @param    array   $spidarray             array of status (1/0)
* @return   void
*
*/
function CALENDAR_toggleStatus($enabledevents, $eidarray)
{
    global $_TABLES, $_DB_table_prefix;
    if (isset($eidarray) && is_array($eidarray)) {
        foreach ($eidarray as $eid => $junk) {
            $eid = COM_applyFilter($eid);
            if (isset($enabledevents[$eid])) {
                DB_query("UPDATE {$_TABLES['events']} SET status = '1' WHERE eid = '" . DB_escapeString($eid) . "'");
            } else {
                DB_query("UPDATE {$_TABLES['events']} SET status = '0' WHERE eid = '" . DB_escapeString($eid) . "'");
            }
        }
    }
    PLG_itemSaved($eid, 'calendar');
    CTL_clearCache();
    /* fixme - add logic to update personal events table as well */
    /* logic should enable/disable all personal_event 'children' */
}
Example #8
0
/**
* Copies and installs new style plugins
*
* Copies all files the proper place and runs the automated installer
* or upgrade.
*
* @return   string              Formatted HTML containing the page body
*
*/
function post_uploadProcess()
{
    global $_CONF, $_PLUGINS, $_TABLES, $pluginData, $LANG32, $_DB_dbms, $_DB_table_prefix;
    $retval = '';
    $upgrade = false;
    $masterErrorCount = 0;
    $masterErrorMsg = '';
    $pluginData = array();
    $pluginData['id'] = COM_applyFilter($_POST['pi_name']);
    $pluginData['name'] = $pluginData['id'];
    $pluginData['version'] = COM_applyFilter($_POST['pi_version']);
    $pluginData['url'] = COM_applyFilter($_POST['pi_url']);
    $pluginData['glfusionversion'] = COM_applyFilter($_POST['pi_gl_version']);
    $upgrade = COM_applyFilter($_POST['upgrade'], true);
    $tdir = COM_applyFilter($_POST['temp_dir']);
    $tdir = preg_replace('/[^a-zA-Z0-9\\-_\\.]/', '', $tdir);
    $tdir = str_replace('..', '', $tdir);
    $tmp = $_CONF['path_data'] . $tdir;
    $pluginData = array();
    $rc = _pi_parseXML($tmp);
    if ($rc == -1) {
        // no xml file found
        return _pi_errorBox($LANG32[74]);
    }
    clearstatcache();
    $permError = 0;
    $permErrorList = '';
    // copy to proper directories
    if (defined('DEMO_MODE')) {
        _pi_deleteDir($tmp);
        COM_setMessage(503);
        echo COM_refresh($_CONF['site_admin_url'] . '/plugins.php');
        exit;
    }
    if (function_exists('set_time_limit')) {
        @set_time_limit(30);
    }
    $rc = _pi_dir_copy($tmp . '/' . $pluginData['id'] . '/', $_CONF['path'] . 'plugins/' . $pluginData['id']);
    list($success, $failed, $size, $faillist) = explode(',', $rc);
    if ($failed > 0) {
        $permError++;
        $t = array();
        $t = explode('|', $faillist);
        if (is_array($t)) {
            foreach ($t as $failedFile) {
                $permErrorList .= sprintf($LANG32[45], $failedFile, $_CONF['path'] . 'plugins/' . $pluginData['id']);
            }
        }
    }
    if (function_exists('set_time_limit')) {
        @set_time_limit(30);
    }
    if (file_exists($tmp . '/' . $pluginData['id'] . '/admin/')) {
        $rc = _pi_dir_copy($tmp . '/' . $pluginData['id'] . '/admin/', $_CONF['path_html'] . 'admin/plugins/' . $pluginData['id']);
        list($success, $failed, $size, $faillist) = explode(',', $rc);
        if ($failed > 0) {
            $permError++;
            $t = array();
            $t = explode('|', $faillist);
            if (is_array($t)) {
                foreach ($t as $failedFile) {
                    $permErrorList .= sprintf($LANG32[45], $failedFile, $_CONF['path'] . 'plugins/' . $pluginData['id']);
                }
            }
        }
        _pi_deleteDir($_CONF['path'] . 'plugins/' . $pluginData['id'] . '/admin/');
    }
    if (function_exists('set_time_limit')) {
        @set_time_limit(30);
    }
    if (file_exists($tmp . '/' . $pluginData['id'] . '/public_html/')) {
        $rc = _pi_dir_copy($tmp . '/' . $pluginData['id'] . '/public_html/', $_CONF['path_html'] . $pluginData['id']);
        list($success, $failed, $size, $faillist) = explode(',', $rc);
        if ($failed > 0) {
            $permError++;
            $t = array();
            $t = explode('|', $faillist);
            if (is_array($t)) {
                foreach ($t as $failedFile) {
                    $permErrorList .= sprintf($LANG32[45], $failedFile, $_CONF['path'] . 'plugins/' . $pluginData['id']);
                }
            }
        }
        _pi_deleteDir($_CONF['path'] . 'plugins/' . $pluginData['id'] . '/public_html/');
    }
    if (function_exists('set_time_limit')) {
        @set_time_limit(30);
    }
    if (file_exists($tmp . '/' . $pluginData['id'] . '/themefiles/')) {
        // determine where to copy them, first check to see if layout was defined in xml
        if (isset($pluginData['layout']) && $pluginData['layout'] != '') {
            $destinationDir = $_CONF['path_html'] . 'layout/' . $pluginData['layout'] . '/';
            fusion_io_mkdir_p($destinationDir);
        } else {
            $destinationDir = $_CONF['path_html'] . 'layout/nouveau/' . $pluginData['id'] . '/';
        }
        $rc = _pi_dir_copy($tmp . '/' . $pluginData['id'] . '/themefiles/', $destinationDir);
        list($success, $failed, $size, $faillist) = explode(',', $rc);
        if ($failed > 0) {
            $permError++;
            $t = array();
            $t = explode('|', $faillist);
            if (is_array($t)) {
                foreach ($t as $failedFile) {
                    $permErrorList .= sprintf($LANG32[45], $failedFile, $_CONF['path'] . 'plugins/' . $pluginData['id']);
                }
            }
        }
        _pi_deleteDir($_CONF['path'] . 'plugins/' . $pluginData['id'] . '/themefiles/');
    }
    if (function_exists('set_time_limit')) {
        @set_time_limit(30);
    }
    if ($permError != 0) {
        $errorMessage = '<h2>' . $LANG32[42] . '</h2>' . $LANG32[43] . $permErrorList . '<br />' . $LANG32[44];
        _pi_deleteDir($tmp);
        return _pi_errorBox($errorMessage);
    }
    if (isset($pluginData['dataproxydriver']) && $pluginData['dataproxydriver'] != '') {
        if (file_exists($_CONF['path'] . 'plugins/dataproxy/drivers/')) {
            $src = $tmp . '/' . $pluginData['id'] . '/dataproxy/' . $pluginData['dataproxydriver'];
            $dest = $_CONF['path'] . 'plugins/dataproxy/drivers/' . $pluginData['dataproxydriver'];
            @copy($src, $dest);
        }
    }
    _pi_deleteDir($tmp);
    if (is_array($pluginData['renamedist'])) {
        foreach ($pluginData['renamedist'] as $fileToRename) {
            $rc = true;
            if (strncmp($fileToRename, 'admin', 5) == 0) {
                // we have a admin file to rename....
                $absoluteFileName = substr($fileToRename, 6);
                $lastSlash = strrpos($fileToRename, '/');
                if ($lastSlash === false) {
                    continue;
                }
                $pathTo = substr($fileToRename, 0, $lastSlash);
                if ($pathTo != '') {
                    $pathTo .= '/';
                }
                $lastSlash++;
                $fileNameDist = substr($fileToRename, $lastSlash);
                $lastSlash = strrpos($fileNameDist, '.');
                if ($lastSlash === false) {
                    continue;
                }
                $fileName = substr($fileNameDist, 0, $lastSlash);
                if (!file_exists($_CONF['path_html'] . 'admin/plugins/' . $pluginData['id'] . $pathTo . $fileName)) {
                    COM_errorLog("PLG-INSTALL: Renaming " . $fileNameDist . " to " . $_CONF['path_html'] . 'admin/plugins/' . $pluginData['id'] . $pathTo . $fileName);
                    $rc = @copy($_CONF['path_html'] . 'admin/plugins/' . $pluginData['id'] . $absoluteFileName, $_CONF['path_html'] . 'admin/plugins/' . $pluginData['id'] . $pathTo . $fileName);
                    if ($rc === false) {
                        COM_errorLog("PLG-INSTALL: Unable to copy " . $_CONF['path_html'] . 'admin/plugins/' . $pluginData['id'] . $absoluteFileName . " to " . $_CONF['path_html'] . 'admin/plugins/' . $pluginData['id'] . $pathTo . $fileName);
                        $masterErrorCount++;
                        $masterErrorMsg .= sprintf($LANG32[75], $_CONF['path_html'] . 'admin/plugins/' . $pluginData['id'] . $absoluteFileName, $_CONF['path_html'] . 'admin/plugins/' . $pluginData['id'] . $pathTo . $fileName);
                    }
                }
            } elseif (strncmp($fileToRename, 'public_html', 10) == 0) {
                // we have a public_html file to rename...
                $absoluteFileName = substr($fileToRename, 11);
                $lastSlash = strrpos($absoluteFileName, '/');
                if ($lastSlash !== false) {
                    $pathTo = substr($absoluteFileName, 0, $lastSlash);
                    if ($pathTo != '') {
                        $pathTo .= '/';
                    }
                } else {
                    $pathTo = '';
                }
                $lastSlash++;
                $fileNameDist = substr($absoluteFileName, $lastSlash);
                $lastSlash = strrpos($fileNameDist, '.');
                if ($lastSlash === false) {
                    continue;
                }
                $fileName = substr($fileNameDist, 0, $lastSlash);
                if (!file_exists($_CONF['path_html'] . $pluginData['id'] . $pathTo . $fileName)) {
                    COM_errorLog("PLG-INSTALL: Renaming " . $fileNameDist . " to " . $_CONF['path_html'] . $pluginData['id'] . $pathTo . $fileName);
                    $rc = @copy($_CONF['path_html'] . $pluginData['id'] . $absoluteFileName, $_CONF['path_html'] . $pluginData['id'] . $pathTo . $fileName);
                    if ($rc === false) {
                        COM_errorLog("PLG-INSTALL: Unable to copy " . $_CONF['path_html'] . $pluginData['id'] . $absoluteFileName . " to " . $_CONF['path_html'] . $pluginData['id'] . $pathTo . $fileName);
                        $masterErrorCount++;
                        $masterErrorMsg .= sprintf($LANG32[75], $_CONF['path_html'] . $pluginData['id'] . $absoluteFileName, $_CONF['path_html'] . $pluginData['id'] . $pathTo . $fileName);
                    }
                }
            } else {
                // must be some other file relative to the plugin/pluginname/ directory
                $absoluteFileName = $fileToRename;
                $lastSlash = strrpos($fileToRename, '/');
                $pathTo = substr($fileToRename, 0, $lastSlash);
                if ($pathTo != '') {
                    $pathTo .= '/';
                }
                $lastSlash++;
                $fileNameDist = substr($fileToRename, $lastSlash);
                $lastSlash = strrpos($fileNameDist, '.');
                if ($lastSlash === false) {
                    continue;
                }
                $fileName = substr($fileNameDist, 0, $lastSlash);
                if (!file_exists($_CONF['path'] . 'plugins/' . $pluginData['id'] . '/' . $pathTo . $fileName)) {
                    COM_errorLog("PLG-INSTALL: Renaming " . $fileNameDist . " to " . $_CONF['path'] . 'plugins/' . $pluginData['id'] . '/' . $pathTo . $fileName);
                    $rc = @copy($_CONF['path'] . 'plugins/' . $pluginData['id'] . '/' . $absoluteFileName, $_CONF['path'] . 'plugins/' . $pluginData['id'] . '/' . $pathTo . $fileName);
                    if ($rc === false) {
                        COM_errorLog("PLG-INSTALL: Unable to copy " . $_CONF['path'] . 'plugins/' . $pluginData['id'] . '/' . $absoluteFileName . " to " . $_CONF['path'] . 'plugins/' . $pluginData['id'] . '/' . $pathTo . $fileName);
                        $masterErrorCount++;
                        $masterErrorMsg .= sprintf($LANG32[75], $_CONF['path'] . 'plugins/' . $pluginData['id'] . '/' . $absoluteFileName, $_CONF['path'] . 'plugins/' . $pluginData['id'] . '/' . $pathTo . $fileName);
                    }
                }
            }
        }
    }
    // handle masterErrorCount here, if not 0, display error and ask use to manually install via the plugin admin screen.
    // all files have been copied, so all they really should need to do is fix the error above and then run.
    if ($masterErrorCount != 0) {
        $errorMessage = '<h2>' . $LANG32[42] . '</h2>' . $LANG32[43] . $masterErrorMsg . '<br />' . $LANG32[44];
        return _pi_errorBox($errorMessage);
    }
    if (function_exists('set_time_limit')) {
        @set_time_limit(30);
    }
    if ($upgrade == 0) {
        // fresh install
        USES_lib_install();
        $pi_name = $pluginData['id'];
        $pi_display_name = $pluginData['name'];
        $pi_version = $pluginData['version'];
        $gl_version = $pluginData['glfusionversion'];
        $pi_url = $pluginData['url'];
        if (file_exists($_CONF['path'] . 'plugins/' . $pluginData['id'] . '/autoinstall.php')) {
            require_once $_CONF['path'] . 'plugins/' . $pluginData['id'] . '/autoinstall.php';
            $ret = INSTALLER_install($INSTALL_plugin[$pi_name]);
            if ($ret == 0) {
                CTL_clearCache();
                COM_setMessage(44);
                echo COM_refresh($_CONF['site_admin_url'] . '/plugins.php');
                exit;
            } else {
                return _pi_errorBox($LANG32[54]);
            }
        } else {
            return _pi_errorBox($LANG32[55]);
        }
    } else {
        // upgrade - force refresh to load new functions.inc
        echo COM_refresh($_CONF['site_admin_url'] . '/plugin_upload.php?mode=upgrade&amp;pi=' . $pluginData['id']);
        exit;
    }
    CTL_clearCache();
    // show status (success or fail)
    return $retval;
}
Example #9
0
/**
*   Perform the upgrade starting at the current version.
*
*   @since  version 0.4.0
*   @return integer                 Error code, 0 for success
*/
function PAYPAL_do_upgrade()
{
    global $_TABLES, $_CONF, $_PP_CONF, $_PP_DEFAULTS, $PP_UPGRADE, $_PLUGIN_INFO;
    if (isset($_PLUGIN_INFO[$_PP_CONF['pi_name']])) {
        $current_ver = $_PLUGIN_INFO[$_PP_CONF['pi_name']];
    } else {
        return false;
    }
    // Get the config instance, several upgrades might need it
    $c = config::get_instance();
    if (!COM_checkVersion($current_ver, '0.2')) {
        // upgrade to 0.2.2
        $current_ver = '0.2.2';
        if (!PAYPAL_do_upgrade_sql($current_ver)) {
            return false;
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.4.0')) {
        // upgrade to 0.4.0
        $current_ver = '0.4.0';
        if (!PAYPAL_do_upgrade_sql($current_ver)) {
            return false;
        }
        if (!plugin_initconfig_paypal()) {
            return false;
        }
        // Migrate existing categories to the new category table
        $r = DB_query("SELECT DISTINCT category\n                FROM {$_TABLES['paypal.products']}\n                WHERE category <> '' and category IS NOT NULL");
        if (DB_error()) {
            COM_errorLog("Could not retrieve old categories", 1);
            return false;
        }
        if (DB_numRows($r) > 0) {
            while ($A = DB_fetchArray($r, false)) {
                DB_query("INSERT INTO {$_TABLES['paypal.categories']}\n                        (cat_name)\n                    VALUES ('{$A['category']}')");
                if (DB_error()) {
                    COM_errorLog("Could not add new category {$A['category']}", 1);
                    return false;
                }
                $cats[$A['category']] = DB_insertID();
            }
            // Now populate the cross-reference table
            $r = DB_query("SELECT id, category\n                    FROM {$_TABLES['paypal.products']}");
            if (DB_error()) {
                COM_errorLog("Error retrieving category data from products", 1);
                return false;
            }
            if (DB_numRows($r) > 0) {
                while ($A = DB_fetchArray($r, false)) {
                    DB_query("UPDATE {$_TABLES['paypal.products']}\n                        SET cat_id = '{$cats[$A['category']]}'\n                        WHERE id = '{$A['id']}'");
                    if (DB_error()) {
                        COM_errorLog("Error updating prodXcat table", 1);
                        return false;
                    }
                }
            }
            DB_query("ALTER TABLE {$_TABLES['paypal.products']}\n                    DROP category");
        }
        // Add buttons to the product records or they won't be shown.
        // Old paypal version always has buy_now and add_cart buttons.
        $buttons = serialize(array('buy_now' => '', 'add_cart' => ''));
        DB_query("UPDATE {$_TABLES['paypal.products']} \n                SET buttons='{$buttons}',\n                dt_add = UNIX_TIMESTAMP()");
        // Finally, rename any existing config.php file since we now use
        // the online configuration.
        $pi_path = $_CONF['path'] . '/plugins/' . $_PP_CONF['pi_name'];
        if (is_file($pi_path . '/config.php')) {
            COM_errorLog("Renaming old config.php file to {$pi_path}/config.old.php", 1);
            if (!rename($pi_path . '/config.php', $pi_path . '/config.old.php')) {
                COM_errorLog("Failed to rename old config.php file.  Manual intervention needed", 1);
            }
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.4.1')) {
        // upgrade to 0.4.1
        $current_ver = '0.4.1';
        if (!PAYPAL_do_upgrade_sql($current_ver)) {
            return false;
        }
        if ($c->group_exists($_PP_CONF['pi_name'])) {
            $c->add('blk_random_limit', $_PP_DEFAULTS['blk_random_limit'], 'text', 0, 30, 2, 40, true, $_PP_CONF['pi_name']);
            $c->add('blk_featured_limit', $_PP_DEFAULTS['blk_featured_limit'], 'text', 0, 30, 2, 50, true, $_PP_CONF['pi_name']);
            $c->add('blk_popular_limit', $_PP_DEFAULTS['blk_popular_limit'], 'text', 0, 30, 2, 60, true, $_PP_CONF['pi_name']);
            $c->add('fs_debug', NULL, 'fieldset', 0, 50, NULL, 0, true, $_PP_CONF['pi_name']);
            $c->add('debug', $_PP_DEFAULTS['debug'], 'select', 0, 50, 2, 10, true, $_PP_CONF['pi_name']);
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.4.2')) {
        // upgrade to 0.4.2
        $current_ver = '0.4.2';
        if (!PAYPAL_do_upgrade_sql($current_ver)) {
            return false;
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.4.3')) {
        // upgrade to 0.4.3
        // this adds a field that was possibly missing in the initial
        // installation, but could have been added in the 0.4.1 update. So,
        // an error is to be expected and ignored
        $current_ver = '0.4.3';
        if (!PAYPAL_do_upgrade_sql($current_ver, true)) {
            return false;
        }
        if ($c->group_exists($_PP_CONF['pi_name'])) {
            $c->add('def_expiration', $_PP_DEFAULTS['def_expiration'], 'text', 0, 30, 0, 40, true, $_PP_CONF['pi_name']);
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.4.4')) {
        $current_ver = '0.4.4';
        // Remove individual block selections and combine into one
        $displayblocks = 0;
        if ($_PP_CONF['leftblocks'] == 1) {
            $displayblocks += 1;
        }
        if ($_PP_CONF['rightblocks'] == 1) {
            $displayblocks += 2;
        }
        $c->del('leftblocks', 'paypal');
        $c->del('rightblocks', 'paypal');
        $c->add('displayblocks', $displayblocks, 'select', 0, 0, 13, 210, true, $_PP_CONF['pi_name']);
        $c->add('debug_ipn', $_PP_DEFAULTS['debug_ipn'], 'select', 0, 50, 2, 20, true, $_PP_CONF['pi_name']);
        if (!PAYPAL_do_upgrade_sql($current_ver)) {
            return false;
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.4.5')) {
        $current_ver = '0.4.5';
        // Add notification email override
        $c->add('admin_email_addr', $_PP_DEFAULTS['admin_email_addr'], 'text', 0, 0, 0, 40, true, $_PP_CONF['pi_name']);
        if (!PAYPAL_do_upgrade_sql($current_ver)) {
            return false;
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.4.5')) {
        $current_ver = '0.4.5';
        // Move the buy_now buttons into a separate table
        $sql = "SELECT id, buttons FROM {$_TABLES['paypal.products']}";
        $res = DB_query($sql, 1);
        while ($A = DB_fetchArray($res, false)) {
            $id = $A['id'];
            $btns = @unserialize($A['buttons']);
            if ($btns && isset($btns['buy_now'])) {
                $button = DB_escapeString($btns['buy_now']);
            } else {
                $button = '';
            }
            DB_query("INSERT INTO {$_TABLES['paypal.buttons']} VALUES\n                ('{$id}', 'paypal', '{$button}')", 1);
        }
        if (!PAYPAL_do_upgrade_sql($current_ver)) {
            return false;
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.5.0')) {
        $current_ver = '0.5.0';
        // Perform the main database upgrades
        // The first few lines get the schema updated for elements that
        // may have been missed (0.4.4 wasn't updated properly).
        // Errors need to be ignored for these.
        DB_query("ALTER TABLE {$_TABLES['paypal.products']}\n                ADD options text after show_popular", 1);
        DB_query("ALTER TABLE {$_TABLES['paypal.purchases']}\n                ADD token varchar(40) after price", 1);
        if (!PAYPAL_do_upgrade_sql($current_ver)) {
            return false;
        }
        // Move the global PayPal-specific configurations into the config table
        $receiver_email = DB_escapeString($_PP_CONF['receiver_email'][0]);
        $gwconfig = array('bus_prod_email' => $receiver_email, 'bus_test_email' => $receiver_email, 'micro_prod_email' => $receiver_email, 'micro_test_email' => $receiver_email, 'micro_threshold' => 10, 'prod_url' => 'https://www.paypal.com', 'sandbox_url' => 'https://www.sandbox.paypal.com', 'test_mode' => (int) $_PP_CONF['testing'], 'prv_key' => DB_escapeString($_PP_CONF['prv_key']), 'pub_key' => DB_escapeString($_PP_CONF['pub_key']), 'pp_cert' => DB_escapeString($_PP_CONF['pp_cert']), 'pp_cert_id' => DB_escapeString($_PP_CONF['pp_cert_id']), 'micro_cert_id' => DB_escapeString($_PP_CONF['pp_cert_id']), 'encrypt' => (int) $_PP_CONF['encrypt_buttons']);
        $db_config = DB_escapeString(@serialize($gwconfig));
        $services = array('buy_now' => 1, 'pay_now' => 1, 'checkout' => 1, 'donation' => 1, 'subscribe' => 1, 'external' => 1);
        $db_services = DB_escapeString(@serialize($services));
        $sql = "INSERT INTO {$_TABLES['paypal.gateways']}\n                (id, orderby, enabled, description, config, services)\n                VALUES\n                ('paypal', 10, 1, 'Paypal Website Payments Standard',\n                    '{$db_config}', '{$db_services}'),\n                ('amazon', 20, 0, 'Amazon SimplePay', '', '{$db_services}')";
        //echo $sql;die;
        // ... and remove Paypal-specific configs from the main config system
        $c->del('receiver_email', 'paypal');
        $c->del('testing', 'paypal');
        $c->del('paypal_url', 'paypal');
        $c->del('prod_url', 'paypal');
        $c->del('use_css_menus', 'paypal');
        // Just not used any more
        $c->del('encrypt_buttons', 'paypal');
        $c->del('prv_key', 'paypal');
        $c->del('pub_key', 'paypal');
        $c->del('pp_cert', 'paypal');
        $c->del('pp_cert_id', 'paypal');
        // Add new plugin config items
        $c->add('fs_addresses', NULL, 'fieldset', 0, 60, NULL, 0, true, $_PP_CONF['pi_name']);
        $c->add('get_street', $_PP_DEFAULTS['get_street'], 'select', 0, 60, 14, 10, true, $_PP_CONF['pi_name']);
        $c->add('get_city', $_PP_DEFAULTS['get_city'], 'select', 0, 60, 14, 20, true, $_PP_CONF['pi_name']);
        $c->add('get_state', $_PP_DEFAULTS['get_state'], 'select', 0, 60, 14, 30, true, $_PP_CONF['pi_name']);
        $c->add('get_country', $_PP_DEFAULTS['get_country'], 'select', 0, 60, 14, 40, true, $_PP_CONF['pi_name']);
        $c->add('get_postal', $_PP_DEFAULTS['get_postal'], 'select', 0, 60, 14, 50, true, $_PP_CONF['pi_name']);
        $c->add('weight_unit', $_PP_DEFAULTS['weight_unit'], 'select', 0, 0, 15, 230, true, $_PP_CONF['pi_name']);
        $c->add('ena_cart', $PP_DEFAULTS['ena_cart'], 'select', 0, 0, 2, 220, true, $_PP_CONF['pi_name']);
        DB_query("UPDATE {$_TABLES['conf_values']}\n                SET sort_order=80\n                WHERE name='tmpdir'\n                AND group_name='paypal'");
        DB_query($sql, 1);
        if (DB_error()) {
            COM_errorLog("Error Executing SQL: {$sql}", 1);
        }
        // Convert saved buttons in the product records to simple text strings
        // indicating the type of button to use.  Don't save the button in the
        // new cache table; that will be done when the button is needed.
        DB_query("UPDATE {$_TABLES['paypal.products']} SET buttons='buy_now'");
        // Create order records and associate with the existing purchase table.
        // We create our own sid to try and use the original purchase date.
        // Since this function runs so fast, there could still be duplicate
        // sid's so we check for an existing sid before trying to use it.
        // If that happens, the order_id will just be a current sid.
        $sql = "SELECT * FROM {$_TABLES['paypal.purchases']}";
        $res = DB_query($sql);
        if ($res && DB_numRows($res) > 0) {
            USES_paypal_class_order();
            while ($A = DB_fetchArray($res, false)) {
                $dt_tm = explode(' ', $A['purchase_date']);
                list($y, $m, $d) = explode('-', $dt_tm[0]);
                list($h, $i, $s) = explode(':', $dt_tm[1]);
                $sid = $y . $m . $d . $h . $i . $s;
                $order_id = $sid . mt_rand(0, 999);
                while (DB_count($_TABLES['paypal.orders'], 'order_id', $order_id) > 0) {
                    $order_id = COM_makeSid();
                }
                // Discovered that the "price" field isn't filled in for the
                // purchase table.  Read the IPN data and use mc_gross.
                $IPN = DB_getItem($_TABLES['paypal.ipnlog'], 'ipn_data', "txn_id = '" . DB_escapeString($A['txn_id']) . "'");
                $price = 0;
                if (!empty($IPN)) {
                    $data = @unserialize($IPN);
                    if ($data && isset($data['mc_gross'])) {
                        $price = (double) $data['mc_gross'];
                        if (isset($data['tax'])) {
                            $tax = (double) $data['tax'];
                            $price -= $tax;
                        } else {
                            $tax = 0;
                        }
                        if (isset($data['shipping'])) {
                            $shipping = (double) $data['shipping'];
                            $price -= $shipping;
                        } else {
                            $shipping = 0;
                        }
                        if (isset($data['handling'])) {
                            $handling = (double) $data['handling'];
                            $price -= $handling;
                        } else {
                            $handling = 0;
                        }
                    }
                }
                $ord = new ppOrder($order_id);
                $ord->uid = $A['user_id'];
                $ord->order_date = DB_escapeString($A['purchase_date']);
                $ord->status = PP_STATUS_PAID;
                $ord->pmt_method = 'paypal';
                $ord->pmt_txn_id = $A['txn_id'];
                $ord->tax = $tax;
                $ord->shipping = $shipping;
                $ord->handling = $handling;
                $order_id = $ord->Save();
                // Also, split out the item number from any attributes.
                // Starting with 0.5.0 we store the actual item number
                // and options separately.
                // * PAYPAL_explode_opts() not available in this version *
                list($item_num, $options) = explode('|', $A['product_id']);
                if (!$options) {
                    $options = '';
                }
                DB_query("UPDATE {$_TABLES['paypal.purchases']} SET\n                        order_id = '" . DB_escapeString($order_id) . "',\n                        price = '{$price}',\n                        product_id = '" . DB_escapeString($item_num) . "',\n                        options = '" . DB_escapeString($options) . "'\n                    WHERE txn_id = '{$A['txn_id']}'");
            }
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.5.2')) {
        $current_ver = '0.5.2';
        $error = PAYPAL_do_upgrade_sql($current_ver);
        if ($error) {
            return $error;
        }
        $c->add('centerblock', $_PP_DEFAULTS['centerblock'], 'select', 0, 0, 2, 215, true, $_PP_CONF['pi_name']);
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.5.4')) {
        $current_ver = '0.5.4';
        // Addes the currency table and formatting functions
        if (!PAYPAL_do_upgrade_sql($current_ver)) {
            return false;
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.5.6')) {
        $current_ver = '0.5.6';
        // SQL updates in 0.5.4 weren't included in new installation, so check
        // if they're done and add them to the upgrade process if not.
        $res = DB_query("SHOW TABLES LIKE '{$_TABLES['paypal.currency']}'", 1);
        if (!$res || DB_numRows($res) < 1) {
            // Add the table
            $PP_UPGRADE['0.5.6'][] = $PP_UPGRADE['0.5.4'][0];
            // Populate with data
            $PP_UPGRADE['0.5.6'][] = $PP_UPGRADE['0.5.4'][1];
        }
        $res = DB_query("SHOW COLUMNS FROM {$_TABLES['paypal.products']}\n                        LIKE 'sale_price'", 1);
        if (!$res || DB_numRows($res) < 1) {
            // Add the field to the products table
            $PP_UPGRADE['0.5.6'][] = $PP_UPGRADE['0.5.4'][2];
        }
        if (!PAYPAL_do_upgrade_sql('0.5.6')) {
            return false;
        }
        // Add new product defaults for onhand tracking
        $c->add('def_track_onhand', $_PP_DEFAULTS['def_track_onhand'], 'select', 0, 30, 2, 50, true, $_PP_CONF['pi_name']);
        $c->add('def_oversell', $_PP_DEFAULTS['def_oversell'], 'select', 0, 30, 16, 60, true, $_PP_CONF['pi_name']);
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.5.7')) {
        $current_ver = '0.5.7';
        $gid = (int) DB_getItem($_TABLES['groups'], 'grp_id', "grp_name='{$_PP_CONF['pi_name']} Admin'");
        if ($gid < 1) {
            $gid = 1;
        }
        // default to Root if paypal group not found
        DB_query("INSERT INTO {$_TABLES['vars']}\n                SET name='paypal_gid', value={$gid}");
        $c->add('product_tpl_ver', $_PP_DEFAULTS['product_tpl_ver'], 'select', 0, 30, 2, 70, true, $_PP_CONF['pi_name']);
        $c->add('list_tpl_ver', $_PP_DEFAULTS['list_tpl_ver'], 'select', 0, 30, 0, 80, true, $_PP_CONF['pi_name']);
        $c->add('cache_max_age', $_PP_DEFAULTS['cache_max_age'], 'text', 0, 40, 2, 40, true, $_PP_CONF['pi_name']);
        // Create cache directory
        if (!is_dir($_PP_DEFAULTS['tmpdir'] . 'cache')) {
            @mkdir($_PP_DEFAULTS['tmpdir'] . 'cache', '0755', true);
        }
        if (!PAYPAL_do_upgrade_sql($current_ver)) {
            return false;
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.5.8')) {
        $current_ver = '0.5.8';
        // Add terms and conditions link
        $c->add('tc_link', $_PP_DEFAULTS['tc_link'], 'text', 0, 40, 2, 50, true, $_PP_CONF['pi_name']);
        // Upgrade sql changes from owner/group/member/anon perms to group id
        // First update the group_id based on the perms.
        $sql = "SELECT cat_id,group_id,perm_group,perm_members,perm_anon\n                FROM {$_TABLES['paypal.categories']}";
        $res = DB_query($sql, 1);
        while ($A = DB_fetchArray($res, false)) {
            if ($A['perm_anon'] >= 2) {
                $grp_id = 2;
            } elseif ($A['perm_members'] >= 2) {
                $grp_id = 13;
            } else {
                $grp_id = $A['group_id'];
            }
            if ($A['group_id'] != $grp_id) {
                $grp_id = (int) $grp_id;
                DB_query("UPDATE {$_TABLES['paypal.categories']}\n                        SET group_id = {$grp_id}\n                        WHERE cat_id = {$A['cat_id']}");
            }
        }
        // Remove Amazon Simplepay gateway file to prevent re-enabling
        @unlink(PAYPAL_PI_PATH . '/classes/gateways/amazon.class.php');
        if (!PAYPAL_do_upgrade_sql($current_ver, true)) {
            return false;
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    if (!COM_checkVersion($current_ver, '0.5.9')) {
        $current_ver = '0.5.9';
        // Add shop phone and email conf values, fix subgroup ID for shop info
        $c->add('shop_phone', '', 'text', 10, 100, 0, 30, true, $_PP_CONF['pi_name']);
        $c->add('shop_email', $_PP_DEFAULTS['shop_email'], 'text', 10, 100, 0, 40, true, $_PP_CONF['pi_name']);
        // Create default path for downloads (even if not used)
        @mkdir($_CONF['path'] . 'data/' . $_PP_CONF['pi_name'] . '/files', true);
        // Remove stray .htaccess file that interferes with plugin removal
        @unlink(PAYPAL_PI_PATH . '/files/.htaccess');
        if (!PAYPAL_do_upgrade_sql('0.5.9')) {
            return false;
        }
        if (!PAYPAL_do_set_version($current_ver)) {
            return false;
        }
    }
    CTL_clearCache($_PP_CONF['pi_name']);
    COM_errorLog("Successfully updated the {$_PP_CONF['pi_display_name']} Plugin", 1);
    return true;
}
Example #10
0
/**
* Config Option has changed. (use plugin api)
*
* @return   nothing
*
*/
function plugin_configchange_template($group, $changes = array())
{
    global $_TABLES, $_CONF;
    if ($group == 'Core' and (in_array('cache_templates', $changes) or in_array('template_comments', $changes) or in_array('language', $changes) or in_array('language_files', $changes) or in_array('languages', $changes) or in_array('url_rewrite', $changes) or in_array('url_routing', $changes))) {
        // To be safe clear cache on enabling and disabling of cache
        // If template comments disabled or enabled clear all cached templates
        // Also clear on config language changes since some cache instances may get messed up going from a single language to multi language setup
        // Clear cache on change of URL Rewrite and URL Rewriting
        CTL_clearCache();
    } elseif ($group == 'Core' and (in_array('sortmethod', $changes) or in_array('showstorycount', $changes) or in_array('showsubmissioncount', $changes) or in_array('hide_home_link', $changes))) {
        // If Topics Block options changed then delete it's cache
        $cacheInstance = 'topicsblock__';
        CACHE_remove_instance($cacheInstance);
    } elseif ($group == 'Core' and (in_array('newstoriesinterval', $changes) or in_array('newcommentsinterval', $changes) or in_array('newtrackbackinterval', $changes) or in_array('hidenewstories', $changes) or in_array('hidenewcomments', $changes) or in_array('hidenewtrackbacks', $changes) or in_array('hidenewplugins', $changes) or in_array('title_trim_length', $changes) or in_array('whatsnew_cache_time', $changes))) {
        // Probably not really necessary but clear cache if enabled on these other settings that can have cache files
        // These are from the What's New Block
        if ($_CONF['whatsnew_cache_time'] > 0) {
            $cacheInstance = 'whatsnew__';
            // remove all whatsnew instances
            CACHE_remove_instance($cacheInstance);
        }
    }
}
Example #11
0
/**
* Save a autotag permissions to the database
*
* @param    string  $autotag_id     ID of autotag permission to save
* @param    array   $perms          Permissions / usage array
* @return   string                  HTML refresh or error message
*
*/
function ATP_save($autotag_id, $perms)
{
    global $_CONF, $_TABLES, $_USER, $LANG_ACCESS, $VERBOSE;
    $tagUsage = PLG_collectAutotagUsage();
    $autoTags = PLG_collectTags();
    foreach ($autoTags as $autotag_name => $namespace) {
        if ($autotag_name != $autotag_id) {
            continue;
        }
        foreach ($tagUsage as $usage) {
            $allowed = 0;
            $needle = $autotag_name . '.' . $usage['namespace'] . '.' . $usage['usage'];
            $pointer = array_search($needle, $perms);
            if ($pointer !== FALSE) {
                $allowed = 1;
            }
            $final[$needle] = array('usage_id' => $needle, 'autotag_name' => $autotag_name, 'autotag_namespace' => $namespace, 'usage_namespace' => $usage['namespace'], 'usage_operation' => $usage['usage'], 'usage_allowed' => $allowed);
        }
    }
    // remove all the old entries for this autotag
    $sql = "DELETE FROM {$_TABLES['autotag_usage']} WHERE autotag_id='" . DB_escapeString($autotag_id) . "'";
    DB_query($sql);
    // check to see if we exist in the main table
    $sql = "SELECT * FROM {$_TABLES['autotag_perm']} WHERE autotag_id='" . DB_escapeString($autotag_id) . "'";
    $result = DB_query($sql);
    if (DB_numRows($result) < 1) {
        $sql = "INSERT INTO {$_TABLES['autotag_perm']} (autotag_id,autotag_namespace,autotag_name) VALUES ";
        $sql .= "('" . DB_escapeString($autotag_id) . "','" . DB_escapeString($autoTags[$autotag_id]) . "','" . DB_escapeString($autotag_id) . "')";
        DB_query($sql);
    }
    foreach ($final as $key) {
        $sql = "INSERT INTO {$_TABLES['autotag_usage']} (autotag_id,autotag_allowed,usage_namespace,usage_operation) VALUES ('" . DB_escapeString($key['autotag_name']) . "'," . (int) $key['usage_allowed'] . ",'" . DB_escapeString($key['usage_namespace']) . "','" . DB_escapeString($key['usage_operation']) . "')";
        DB_query($sql);
    }
    CTL_clearCache();
    $url = $_CONF['site_admin_url'] . '/autotag.php?msg=36';
    echo COM_refresh($url);
    exit;
}
Example #12
0
/**
* Check if user has valid session
*
* Checks to see if the session cookie is set and validates it
* If no session cookie, then check for remember me settings
*
* If no valid session is found - one will be created
*
* @return       array   user data array or null if anonymous user
*
*/
function SESS_sessionCheck()
{
    global $_CONF, $_TABLES, $_USER, $_SYSTEM;
    unset($_USER);
    $userdata = array();
    // initialize the standard user record data
    $userdata['uid'] = 1;
    $userdata['theme'] = $_CONF['theme'];
    $userdata['tzid'] = $_CONF['timezone'];
    $userdata['language'] = $_CONF['language'];
    $_USER = $userdata;
    $userid = 0;
    $mintime = time() - $_CONF['session_cookie_timeout'];
    $request_ip = !empty($_SERVER['REMOTE_ADDR']) ? htmlspecialchars($_SERVER['REMOTE_ADDR']) : '';
    if (isset($_COOKIE[$_CONF['cookie_session']]) && strlen($_COOKIE[$_CONF['cookie_session']]) < 33) {
        $sessid = COM_applyFilter($_COOKIE[$_CONF['cookie_session']]);
        // get userid from the session id (must look in database) - 0 means no active session or we
        // have an IP mismatch
        $userid = (int) SESS_getUserIdFromSession($sessid, $_CONF['session_cookie_timeout'], $request_ip);
        if ($userid > 1) {
            // found a valid session record and user id
            $userdata = SESS_getUserDataFromId($userid);
            if ($userdata !== false) {
                $status = $userdata['status'];
                if ($status == USER_ACCOUNT_ACTIVE || $status == USER_ACCOUNT_AWAITING_ACTIVATION) {
                    $_USER = $userdata;
                }
            } else {
                $userid = 0;
            }
        }
    }
    // we only get here if no valid session was found (either user or anonymous)
    if ($userid == 0) {
        $userid = SESS_checkRememberMe();
        if ($userid > 1) {
            $userdata = SESS_getUserDataFromId($userid);
            // Check user status
            if ($userdata !== false) {
                $status = $userdata['status'];
                if ($status == USER_ACCOUNT_ACTIVE || $status == USER_ACCOUNT_AWAITING_ACTIVATION) {
                    $_USER = $userdata;
                    // Create new session and write cookie
                    $sessid = SESS_newSession($userid, $request_ip, $_CONF['session_cookie_timeout']);
                    if ($sessid === false) {
                        die('ERROR: Unable to create session');
                    }
                }
            } else {
                $userid == 0;
            }
        }
        if ($userid == 0) {
            $sql = "SELECT md5_sess_id, start_time FROM {$_TABLES['sessions']} WHERE " . "(remote_ip = '" . DB_escapeString($request_ip) . "') AND (start_time > {$mintime}) AND (uid = 1)";
            $result = DB_query($sql);
            if ($result && DB_numRows($result) > 0) {
                $row = DB_fetchArray($result);
                $sessid = $row['md5_sess_id'];
                if ($row['start_time'] + 60 < time()) {
                    SESS_updateSessionTime($sessid);
                }
            } else {
                $sessid = SESS_newSession(1, $request_ip, $_CONF['session_cookie_timeout']);
                if ($sessid === false) {
                    die('ERROR: Unable to create session');
                }
            }
        }
    }
    if (empty($sessid)) {
        $sessid = _createID();
    }
    session_id($sessid);
    session_start();
    $count = SESS_getVar('session.counter');
    $count++;
    SESS_setVar('session.counter', $count);
    $gc_check = $count % 10;
    // failsafe
    if ($_CONF['allow_user_themes'] == 0) {
        $_USER['theme'] = $_CONF['theme'];
    }
    if ($_USER['tzid'] == '') {
        $_USER['tzid'] = $_CONF['timezone'];
    }
    if ($gc_check == 0) {
        $expirytime = (string) (time() - $_CONF['session_cookie_timeout']);
        $result = DB_query("SELECT uid FROM {$_TABLES['sessions']} WHERE start_time < {$expirytime} AND uid > 1", 1);
        while ($D = DB_fetchArray($result) != FALSE) {
            CTL_clearCache('mbmenu_' . $D['uid']);
        }
        $deleteSQL = "DELETE FROM {$_TABLES['sessions']} WHERE (start_time < {$expirytime})";
        $delresult = DB_query($deleteSQL, 1);
    }
    return $_USER;
}
Example #13
0
/**
*   Post-installation activity.
*   Create the repeating event records for the sample data that was loaded.
*/
function X_plugin_postinstall_evlist()
{
    global $_TABLES, $_CONF, $_EV_CONF;
    require_once $_CONF['path'] . '/plugins/evlist/functions.inc';
    // Now create the repeat records for the default events
    USES_evlist_class_event();
    $sql = "SELECT id FROM {$_TABLES['evlist_events']}";
    $res = DB_query($sql);
    $Ev = new evEvent();
    while ($A = DB_fetchArray($res, false)) {
        $Ev->Read($A['id']);
        $Ev->UpdateRepeats();
    }
    // Clear the template cache since we've introduced some new css.
    // Might not be needed outside of testing where the plugin is repeatedly
    // installed & removed, but doesn't hurt.
    CTL_clearCache();
}
Example #14
0
/**
* Copies and installs new style plugins
*
* Copies all files the proper place and runs the automated installer
* or upgrade.
*
* @return   string              Formatted HTML containing the page body
*
*/
function post_uploadProcess()
{
    global $_CONF, $_PLUGINS, $_TABLES, $autotagData, $LANG32, $_DB_dbms, $_DB_table_prefix;
    $retval = '';
    $upgrade = false;
    $masterErrorCount = 0;
    $masterErrorMsg = '';
    $autotagData = array();
    $autotagData['id'] = COM_applyFilter($_POST['pi_name']);
    $autotagData['name'] = $autotagData['id'];
    $autotagData['version'] = COM_applyFilter($_POST['pi_version']);
    $autotagData['glfusionversion'] = COM_applyFilter($_POST['pi_gl_version']);
    $tdir = COM_applyFilter($_POST['temp_dir']);
    $tdir = preg_replace('/[^a-zA-Z0-9\\-_\\.]/', '', $tdir);
    $tdir = str_replace('..', '', $tdir);
    $tmp = $_CONF['path_data'] . $tdir;
    $autotagData = array();
    $rc = _at_parseXML($tmp);
    if ($rc == -1) {
        // no xml file found
        return _at_errorBox($LANG32[74]);
    }
    clearstatcache();
    $permError = 0;
    $permErrorList = '';
    // copy to proper directories
    if (defined('DEMO_MODE')) {
        _pi_deleteDir($tmp);
        echo COM_refresh($_CONF['site_admin_url'] . '/autotag.php?msg=503');
        exit;
    }
    if (function_exists('set_time_limit')) {
        @set_time_limit(30);
    }
    $autotagData['id'] = preg_replace('/[^a-zA-Z0-9\\-_\\.]/', '', $autotagData['id']);
    $rc = _pi_file_copy($tmp . '/' . $autotagData['id'] . '.class.php', $_CONF['path_system'] . 'autotags/');
    if ($rc === false) {
        $errorMessage = '<h2>' . $LANG32[42] . '</h2>' . $LANG32[43] . $permErrorList . '<br />' . $LANG32[44];
        _pi_deleteDir($tmp);
        return _at_errorBox($errorMessage);
    }
    // copy template files, if any
    if (isset($autotagData['template']) && is_array($autotagData['template'])) {
        foreach ($autotagData['template'] as $filename) {
            $rc = _pi_file_copy($tmp . '/' . $filename, $_CONF['path_system'] . 'autotags/');
            if ($rc === false) {
                @unlink($_CONF['path_system'] . $autotagData['id'] . '.class.php');
                $errorMessage = '<h2>' . $LANG32[42] . '</h2>' . $LANG32[43] . $permErrorList . '<br />' . $LANG32[44];
                _pi_deleteDir($tmp);
                return _at_errorBox($errorMessage);
            }
        }
    }
    $tag = DB_escapeString($autotagData['id']);
    $desc = DB_escapeString($autotagData['description']);
    $is_enabled = 1;
    $is_function = 1;
    $replacement = '';
    DB_query("REPLACE INTO {$_TABLES['autotags']} (tag,description,is_enabled,is_function,replacement) VALUES ('" . $tag . "','" . $desc . "'," . $is_enabled . "," . $is_function . ",'')");
    _pi_deleteDir($tmp);
    CTL_clearCache();
    // show status (success or fail)
    return $retval;
}
Example #15
0
function SP_toggleStatus($enabledstaticpages, $sp_idarray)
{
    global $_TABLES, $_DB_table_prefix;
    if (!_sec_checkToken(1)) {
        $retval['statusMessage'] = 'Invalid security token. Please refresh the page.';
        $retval['errorCode'] = 1;
    } else {
        if (isset($sp_idarray) && is_array($sp_idarray)) {
            foreach ($sp_idarray as $sp_id => $junk) {
                $sp_id = COM_applyFilter($sp_id);
                if (isset($enabledstaticpages[$sp_id])) {
                    DB_query("UPDATE {$_TABLES['staticpage']} SET sp_status = '1' WHERE sp_id = '" . DB_escapeString($sp_id) . "'");
                } else {
                    DB_query("UPDATE {$_TABLES['staticpage']} SET sp_status = '0' WHERE sp_id = '" . DB_escapeString($sp_id) . "'");
                }
            }
        }
        PLG_itemSaved($sp_id, 'staticpages');
        CTL_clearCache();
        $retval['statusMessage'] = 'StaticPage state has been toggled.';
        $retval['errorCode'] = 0;
        $return["json"] = json_encode($retval);
        echo json_encode($return);
    }
}
Example #16
0
            if ($_POST['delPostMigrate'] == 1) {
                DB_query("DELETE FROM {$_TABLES['storysubmission']} WHERE sid='" . DB_escapeString($sid) . "'");
            }
        } else {
            $topic = DB_getItem($_TABLES['stories'], "tid", "sid='" . DB_escapeString($sid) . "'");
            $sql = DB_query("SELECT sid,tid,date,uid,title,introtext,bodytext,hits from {$_TABLES['stories']} WHERE sid='" . DB_escapeString($sid) . "'");
            list($sid, $tid, $storydate, $uid, $subject, $introtext, $bodytext, $hits) = DB_fetchArray($sql);
            $num_posts = _ff_migratetopic($forum, $sid, $tid, $storydate, $uid, $subject, $introtext, $bodytext, $hits) + $num_posts;
            $num_stories++;
            if (isset($_POST['delPostMigrate']) && $_POST['delPostMigrate'] == 1) {
                migrate_deletestory($sid);
            }
        }
    }
    gf_resyncforum($forum);
    CTL_clearCache();
    echo COM_refresh($_CONF['site_admin_url'] . "/plugins/forum/migrate.php?num_stories=" . $num_stories . "&num_posts=" . $num_posts);
    exit;
}
function _ff_migratetopic($forum, $sid, $tid, $storydate, $uid, $subject, $introtext, $bodytext, $hits)
{
    global $_TABLES;
    $num_posts = 0;
    $comment = $introtext . $bodytext;
    $comment = prepareStringForDB($comment);
    $subject = prepareStringForDB($subject);
    $postmode = "html";
    $name = DB_getITEM($_TABLES['users'], 'username', "uid=" . (int) $uid);
    $email = DB_getITEM($_TABLES['users'], 'email', "uid=" . (int) $uid);
    $website = DB_getITEM($_TABLES['users'], 'homepage', "uid=" . (int) $uid);
    $datetime = explode(" ", $storydate);
Example #17
0
/**
* Delete a block
*
* @param    string  $bid    id of block to delete
* @return   string          HTML redirect or error message
*
*/
function BLOCK_delete($bid)
{
    global $_CONF, $_TABLES, $_USER;
    $result = DB_query("SELECT tid,owner_id,type,group_id,perm_owner,perm_group,perm_members,perm_anon FROM {$_TABLES['blocks']} WHERE bid ='{$bid}'");
    $A = DB_fetchArray($result);
    if ($A['type'] == 'gldefault') {
        return COM_refresh($_CONF['site_admin_url'] . '/block.php');
    }
    $access = SEC_hasAccess($A['owner_id'], $A['group_id'], $A['perm_owner'], $A['perm_group'], $A['perm_members'], $A['perm_anon']);
    if ($access < 3 || BLOCK_hasTopicAccess($A['tid']) < 3) {
        COM_accessLog("User {$_USER['username']} tried to illegally delete block {$bid}.");
        return COM_refresh($_CONF['site_admin_url'] . '/block.php');
    }
    DB_delete($_TABLES['blocks'], 'bid', $bid);
    CTL_clearCache();
    return COM_refresh($_CONF['site_admin_url'] . '/block.php?msg=12');
}