Example #1
0
function MG_haveEXIF($mid)
{
    global $_CONF, $_MG_CONF, $_TABLES, $LANG_MG04;
    $count = 0;
    $exifItems = 0;
    $result = DB_query("SELECT media_filename,media_mime_ext,media_exif FROM {$_TABLES['mg_media']} WHERE media_id='" . addslashes($mid) . "'");
    list($media_filename, $media_mime_ext, $media_exif) = DB_fetchArray($result);
    if ($media_exif == 0) {
        return 0;
    }
    if ($media_filename == '') {
        return 0;
    }
    $exif = array();
    if ($_MG_CONF['discard_original'] == 1) {
        $exif = ExifProcessor($_MG_CONF['path_mediaobjects'] . 'disp/' . $media_filename[0] . '/' . $media_filename . '.jpg');
    } else {
        $exif = ExifProcessor($_MG_CONF['path_mediaobjects'] . 'orig/' . $media_filename[0] . '/' . $media_filename . '.' . $media_mime_ext);
    }
    if (count($exif) == 0) {
        DB_change($_TABLES['mg_media'], 'media_exif', 0, 'media_id', addslashes($mid));
        return 0;
    }
    return count($exif);
}
 /**
  * Disables a specified user
  *
  * @param    int $uid
  **/
 protected function disableUser($uid)
 {
     global $_TABLES, $_USER;
     $this->result = PLG_SPAM_ACTION_DELETE;
     DB_change($_TABLES['users'], 'status', USER_ACCOUNT_DISABLED, 'uid', $uid);
     SPAMX_log("User {$_USER['username']} banned for profile spam.");
 }
 function execute($comment)
 {
     global $result, $_CONF, $_TABLES, $LANG_SX00;
     $result = 128;
     // update count of deleted spam posts
     DB_change($_TABLES['vars'], 'value', 'value + 1', 'name', 'spamx.counter', '', true);
     SPAMX_log($LANG_SX00['spamdeleted']);
     return 1;
 }
 /**
  * Execute
  *
  * @param  string $comment
  * @return int
  */
 public function execute($comment)
 {
     global $result, $_CONF, $_TABLES, $LANG_SX00, $_USER;
     $url = COM_getCurrentURL();
     if (strpos($url, 'usersettings.php') !== false) {
         $this->result = PLG_SPAM_ACTION_DELETE;
         DB_change($_TABLES['users'], 'status', USER_ACCOUNT_DISABLED, 'uid', $_USER['uid']);
         SPAMX_log("User {$_USER['username']} banned for profile spam.");
     }
     return 1;
 }
Example #5
0
/**
* Replace the old $_STATES array with a free-form text field
*
*/
function calendar_update_move_states()
{
    global $_TABLES, $_STATES;
    if (isset($_STATES) && is_array($_STATES)) {
        $tables = array($_TABLES['events'], $_TABLES['eventsubmission'], $_TABLES['personal_events']);
        foreach ($_STATES as $key => $state) {
            foreach ($tables as $table) {
                DB_change($table, 'state', DB_escapeString($state), 'state', DB_escapeString($key));
            }
        }
    }
}
Example #6
0
function MG_approveSubmission($media_id)
{
    global $_CONF, $_TABLES, $LANG_MG01;
    $mid = addslashes($media_id);
    $owner_uid = DB_getItem($_TABLES['mg_mediaqueue'], 'media_user_id', "media_id='" . $mid . "'");
    DB_delete($_TABLES['mg_mediaqueue'], 'media_id', $mid);
    $album_id = DB_getItem($_TABLES['mg_media_album_queue'], 'album_id', "media_id='" . $mid . "'");
    DB_save($_TABLES['mg_media_albums'], 'album_id, media_id, media_order', "{$album_id}, '{$mid}', 0");
    require_once $_CONF['path'] . 'plugins/mediagallery/include/sort.php';
    MG_SortMedia($album_id);
    DB_delete($_TABLES['mg_media_album_queue'], 'media_id', $mid);
    $sql = "SELECT media_filename, media_type " . "FROM {$_TABLES['mg_media']} WHERE media_id='" . $mid . "'";
    $result = DB_query($sql);
    list($media_filename, $media_type) = DB_fetchArray($result);
    $media_count = DB_getItem($_TABLES['mg_albums'], 'media_count', 'album_id=' . $album_id);
    $media_count++;
    DB_change($_TABLES['mg_albums'], 'media_count', $media_count, 'album_id', $album_id);
    MG_updateAlbumLastUpdate($album_id);
    $album_cover = DB_getItem($_TABLES['mg_albums'], 'album_cover', 'album_id=' . $album_id);
    if ($album_cover == -1 && $media_type == 0) {
        DB_change($_TABLES['mg_albums'], 'album_cover_filename', $media_filename, 'album_id', $album_id);
    }
    // email the owner / uploader that the item has been approved.
    COM_clearSpeedlimit(600, 'mgapprove');
    $last = COM_checkSpeedlimit('mgapprove');
    if ($last == 0) {
        $result2 = DB_query("SELECT username, fullname, email FROM {$_TABLES['users']} WHERE uid='" . $owner_uid . "'");
        list($username, $fullname, $email) = DB_fetchArray($result2);
        if ($email != '') {
            $subject = $LANG_MG01['upload_approved'];
            $body = $LANG_MG01['upload_approved'];
            $body .= '<br' . XHTML . '><br' . XHTML . '>';
            $body .= $LANG_MG01['thanks_submit'];
            $body .= '<br' . XHTML . '><br' . XHTML . '>';
            $body .= $_CONF['site_name'] . '<br' . XHTML . '>';
            $body .= $_CONF['site_url'] . '<br' . XHTML . '>';
            $to = array();
            $from = array();
            $to = COM_formatEmailAddress($username, $email);
            $from = COM_formatEmailAddress($_CONF['site_name'], $_CONF['site_mail']);
            if (!COM_mail($to, $subject, $body, $from, true)) {
                COM_errorLog("Media Gallery Error - Unable to send queue notification email");
            }
            COM_updateSpeedlimit('mgapprove');
        }
    }
    // PLG_itemSaved($media_id, 'mediagallery');
    // COM_rdfUpToDateCheck();
    // COM_olderStuff();
    return;
}
Example #7
0
function MG_saveUser()
{
    global $_CONF, $_MG_CONF, $_TABLES, $_USER, $LANG_MG00, $LANG_MG01;
    $uid = COM_applyFilter($_POST['uid'], true);
    $quota = COM_applyFilter($_POST['quota'], true) * 1048576;
    $active = COM_applyFilter($_POST['active'], true);
    $result = DB_query("SELECT uid FROM {$_TABLES['mg_userprefs']} WHERE uid=" . $uid);
    $nRows = DB_numRows($result);
    if ($nRows > 0) {
        DB_change($_TABLES['mg_userprefs'], 'quota', $quota, 'uid', $uid);
        DB_change($_TABLES['mg_userprefs'], 'active', $active, 'uid', $uid);
    } else {
        DB_query("INSERT INTO {$_TABLES['mg_userprefs']} SET uid=" . $uid . ", quota=" . $quota . ",active=" . $active, 1);
    }
    echo COM_refresh($_MG_CONF['admin_url'] . 'quotareport.php');
    exit;
}
/**
 * Add passwords for OAuth and OpenID users
 *
 */
function update_UsersFor180()
{
    global $_CONF, $_TABLES;
    require_once $_CONF['path_system'] . 'lib-security.php';
    $passwords = array();
    $sql = "SELECT uid FROM {$_TABLES['users']} WHERE (remoteservice IS NOT NULL OR remoteservice != '') AND passwd = ''";
    $result = DB_query($sql);
    $nrows = DB_numRows($result);
    for ($i = 0; $i < $nrows; $i++) {
        $A = DB_fetchArray($result);
        /* Formerlly USER_changePassword */
        $passwd['normal'] = rand();
        $passwd['normal'] = md5($passwd['normal']);
        $passwd['normal'] = substr($passwd['normal'], 1, 8);
        $passwd['encrypted'] = SEC_encryptPassword($passwd['normal'], '', HashFunction::md5, 1);
        /* use default md5 only */
        if ($A['uid'] > 1) {
            DB_change($_TABLES['users'], 'passwd', $passwd['encrypted'], 'uid', $A['uid']);
        }
    }
}
Example #9
0
function POLLS_saveVote_AJAX($pid, $aid)
{
    global $_CONF, $_PO_CONF, $_TABLES, $LANG_POLLS;
    $retval = array('html' => '', 'statusMessage' => '');
    if (POLLS_ipAlreadyVoted($pid)) {
        $retval['statusMessage'] = 'You have already voted on this poll';
        $retval['html'] = POLLS_pollResults($pid, 400, '', '', 2);
    } else {
        setcookie('poll-' . $pid, implode('-', $aid), time() + $_PO_CONF['pollcookietime'], $_CONF['cookie_path'], $_CONF['cookiedomain'], $_CONF['cookiesecure']);
        DB_change($_TABLES['polltopics'], 'voters', "voters + 1", 'pid', DB_escapeString($pid), '', true);
        $answers = count($aid);
        for ($i = 0; $i < $answers; $i++) {
            DB_change($_TABLES['pollanswers'], 'votes', "votes + 1", array('pid', 'qid', 'aid'), array(DB_escapeString($pid), $i, COM_applyFilter($aid[$i], true)), '', true);
        }
        DB_save($_TABLES['pollvoters'], 'ipaddress,date,pid', "'" . DB_escapeString($_SERVER['REMOTE_ADDR']) . "'," . time() . ",'" . DB_escapeString($pid) . "'");
    }
    $eMsg = $LANG_POLLS['savedvotemsg'] . ' "' . DB_getItem($_TABLES['polltopics'], 'topic', "pid = '" . DB_escapeString($pid) . "'") . '"';
    $retval['statusMessage'] = $eMsg;
    $retval['html'] = POLLS_pollResults($pid, 400, '', '', 2);
    return $retval;
}
Example #10
0
*/
require_once '../lib-common.php';
if (!in_array('links', $_PLUGINS)) {
    echo COM_refresh($_CONF['site_url'] . '/index.php');
    exit;
}
// MAIN
$url = '';
COM_setArgNames(array('what', 'item'));
$what = COM_getArgument('what');
if ($what == 'link') {
    $item = COM_applyFilter(COM_getArgument('item'));
    if (!empty($item)) {
        // Hack: due to PLG_afterSaveSwitch settings, we may get
        // an attached &msg - strip it off
        $i = explode('&', $item);
        $item = $i[0];
    }
    if (!empty($item)) {
        $url = DB_getItem($_TABLES['links'], 'url', "lid = '{$item}'");
        if (!empty($url)) {
            DB_change($_TABLES['links'], 'hits', 'hits + 1', 'lid', $item, '', true);
        }
    }
}
if (empty($url)) {
    $url = $_CONF['site_url'];
}
header('HTTP/1.1 301 Moved');
header('Location: ' . $url);
header('Connection: close');
Example #11
0
/**
*  Disables all plugins with unresolved dependencies
*  and resolves the load order for all enabled plugins.
*
* @return   bool    True or False, depending on whether it was
*                   necessary to alter the load order of a plugin
* @since            Geeklog 1.8.0
*/
function PLG_resolveDependencies()
{
    global $_PLUGINS, $_TABLES;
    $retval = '';
    $flag = true;
    // false means that all dependencies are resolved
    while ($flag) {
        // loop until ALL dependencies are satisfied
        $flag = false;
        // set this if any plugin has been disabled during the loop
        foreach ($_PLUGINS as $key => $pi_name) {
            if (!PLG_checkDependencies($pi_name)) {
                // plugin has unresolved dependencies
                // disable plugin;
                $flag = true;
                // disabling a plugin can break the dependencies of a plugin that has already been checked, remember to loop again
                PLG_enableStateChange($pi_name, false);
                DB_change($_TABLES['plugins'], 'pi_enabled', 0, 'pi_name', $pi_name);
                PLG_pluginStateChange($pi_name, 'disabled');
                unset($_PLUGINS[$key]);
            }
        }
    }
    // automatically resolve load order for enabled plugins
    $index = 2000;
    // how far through the load order to push back plugins
    $maxqueries = 50;
    // just in case...
    $globalflag = false;
    // remember if we change the load order of any plugin
    $flag = true;
    // set true if we need another pass in the while loop
    while ($flag && $maxqueries) {
        // Now check if the load order is correct
        $flag = false;
        // get the load orders of all enabled plugins
        $q = DB_query("SELECT pi_name, pi_load FROM {$_TABLES['plugins']} WHERE pi_enabled='1'");
        $plo = array();
        // Plugins Load Order
        while ($a = DB_fetchArray($q)) {
            $plo[] = $a;
        }
        $params = array();
        foreach ($plo as $key => $value) {
            // for each available plugin
            $maxqueries--;
            $params = PLG_getParams($value['pi_name']);
            // get dependencies
            if (isset($params['requires']) && is_array($params['requires'])) {
                // if any
                foreach ($params['requires'] as $rkey => $rvalue) {
                    // process each dependency
                    if (isset($rvalue['plugin'])) {
                        // get the load order of the required plugin
                        foreach ($plo as $new_key => $new_value) {
                            if ($new_value['pi_name'] == $rvalue['plugin']) {
                                $dep_load = $new_value['pi_load'];
                                break;
                            }
                        }
                        if ($dep_load > $value['pi_load']) {
                            // incorrect load order
                            // move down the order
                            DB_query("UPDATE {$_TABLES['plugins']} SET pi_load = '{$index}' WHERE pi_name = '{$value['pi_name']}'");
                            $index++;
                            $flag = true;
                            $globalflag = true;
                        }
                    }
                }
            }
        }
    }
    reorderplugins();
    if ($globalflag == false) {
        return true;
        // no change
    } else {
        return false;
        // something changed
    }
}
Example #12
0
function _userSetnewpwd()
{
    global $_CONF, $_TABLES, $_USER, $LANG04;
    $retval = '';
    if (empty($_POST['passwd']) || $_POST['passwd'] != $_POST['passwd_conf']) {
        echo COM_refresh($_CONF['site_url'] . '/users.php?mode=newpwd&amp;uid=' . COM_applyFilter($_POST['uid'], true) . '&amp;rid=' . COM_applyFilter($_POST['rid']));
    } else {
        $uid = COM_applyFilter($_POST['uid'], true);
        $reqid = COM_sanitizeID(COM_applyFilter($_POST['rid']));
        if (!empty($uid) && is_numeric($uid) && $uid > 1 && !empty($reqid) && strlen($reqid) == 16) {
            $uid = (int) $uid;
            $safereqid = DB_escapeString($reqid);
            $valid = DB_count($_TABLES['users'], array('uid', 'pwrequestid'), array($uid, $safereqid));
            if ($valid == 1) {
                $passwd = SEC_encryptPassword($_POST['passwd']);
                DB_change($_TABLES['users'], 'passwd', DB_escapeString($passwd), "uid", $uid);
                DB_delete($_TABLES['sessions'], 'uid', $uid);
                DB_change($_TABLES['users'], 'pwrequestid', "NULL", 'uid', $uid);
                echo COM_refresh($_CONF['site_url'] . '/users.php?msg=53');
            } else {
                // request invalid or expired
                $retval .= COM_showMessage(54, '', '', 1, 'error');
                $retval .= getpasswordform();
            }
        } else {
            // this request doesn't make sense - ignore it
            echo COM_refresh($_CONF['site_url']);
        }
    }
}
Example #13
0
/**
 * Check to see if we can authenticate this user with a remote server
 * A user has not managed to login localy, but has an @ in their user
 * name and we have enabled distributed authentication. Firstly, try to
 * see if we have cached the module that we used to authenticate them
 * when they signed up (i.e. they've actualy changed their password
 * elsewhere and we need to synch.) If not, then try to authenticate
 * them with /every/ authentication module. If this suceeds, create
 * a user for them.
 *
 * @param  string $loginname Their username
 * @param  string $passwd    The password entered
 * @param  string $service   The service portion of $username
 * @param  string $uid       OUTPUT parameter, pass it by ref to get uid back.
 * @return int     user status, -1 for fail.
 */
function SEC_remoteAuthentication(&$loginname, $passwd, $service, &$uid)
{
    global $_CONF, $_TABLES;
    /* First try a local cached login */
    $remoteusername = DB_escapeString($loginname);
    $remoteservice = DB_escapeString($service);
    $result = DB_query("SELECT passwd, status, uid FROM {$_TABLES['users']} WHERE remoteusername='******' AND remoteservice='{$remoteservice}'");
    $tmp = DB_error();
    $nrows = DB_numRows($result);
    if ($tmp == 0 && $nrows == 1) {
        $U = DB_fetchArray($result);
        $uid = $U['uid'];
        $mypass = $U['passwd'];
        // also used to see if the user existed later.
        if ($mypass == SEC_encryptPassword($passwd)) {
            /* Valid password for cached user, return status */
            return $U['status'];
        }
    }
    $service = COM_sanitizeFilename($service);
    $servicefile = $_CONF['path_system'] . 'classes/authentication/' . $service . '.auth.class.php';
    if (file_exists($servicefile)) {
        require_once $servicefile;
        $authmodule = new $service();
        if ($authmodule->authenticate($loginname, $passwd)) {
            /* check to see if they have logged in before: */
            if (empty($mypass)) {
                // no such user, create them
                // Check to see if their remoteusername is unique locally
                $checkName = DB_getItem($_TABLES['users'], 'username', "username='******'");
                if (!empty($checkName)) {
                    // no, call custom function.
                    if (function_exists('CUSTOM_uniqueRemoteUsername')) {
                        $loginname = CUSTOM_uniqueRemoteUsername($loginname, $service);
                    }
                }
                USER_createAccount($loginname, $authmodule->email, $passwd, $authmodule->fullname, $authmodule->homepage, $remoteusername, $remoteservice);
                $uid = DB_getItem($_TABLES['users'], 'uid', "remoteusername = '******' AND remoteservice='{$remoteservice}'");
                // Store full remote account name:
                DB_query("UPDATE {$_TABLES['users']} SET remoteusername='******', remoteservice='{$remoteservice}', status=3 WHERE uid='{$uid}'");
                // Add to remote users:
                $remote_grp = DB_getItem($_TABLES['groups'], 'grp_id', "grp_name='Remote Users'");
                DB_query("INSERT INTO {$_TABLES['group_assignments']} (ug_main_grp_id,ug_uid) VALUES ({$remote_grp}, {$uid})");
                return 3;
                // Remote auth precludes usersubmission,
                // and integrates user activation, see?
            } else {
                // user existed, update local password:
                DB_change($_TABLES['users'], 'passwd', SEC_encryptPassword($passwd), array('remoteusername', 'remoteservice'), array($remoteusername, $remoteservice));
                // and return their status
                return DB_getItem($_TABLES['users'], 'status', "remoteusername='******' AND remoteservice='{$remoteservice}'");
            }
        } else {
            return -1;
        }
    } else {
        return -1;
    }
}
Example #14
0
/**
 * Submit static page. The page is updated if it exists, or a new one is created
 *
 * @param   array   args     Contains all the data provided by the client
 * @param   string  &output  OUTPUT parameter containing the returned text
 * @param   string  &svc_msg OUTPUT parameter containing any service messages
 * @return  int		     Response code as defined in lib-plugins.php
 */
function service_submit_staticpages($args, &$output, &$svc_msg)
{
    global $_CONF, $_TABLES, $_USER, $LANG_ACCESS, $LANG12, $LANG_STATIC, $_GROUPS, $_SP_CONF;
    if (!$_CONF['disable_webservices']) {
        require_once $_CONF['path_system'] . 'lib-webservices.php';
    }
    $output = '';
    if (!SEC_hasRights('staticpages.edit')) {
        $output = COM_siteHeader('menu', $LANG_STATIC['access_denied']);
        $output .= COM_startBlock($LANG_STATIC['access_denied'], '', COM_getBlockTemplate('_msg_block', 'header'));
        $output .= $LANG_STATIC['access_denied_msg'];
        $output .= COM_endBlock(COM_getBlockTemplate('_msg_block', 'footer'));
        $output .= COM_siteFooter();
        return PLG_RET_AUTH_FAILED;
    }
    $gl_edit = false;
    if (isset($args['gl_edit'])) {
        $gl_edit = $args['gl_edit'];
    }
    if ($gl_edit) {
        // This is EDIT mode, so there should be an sp_old_id
        if (empty($args['sp_old_id'])) {
            if (!empty($args['id'])) {
                $args['sp_old_id'] = $args['id'];
            } else {
                return PLG_RET_ERROR;
            }
            if (empty($args['sp_id'])) {
                $args['sp_id'] = $args['sp_old_id'];
            }
        }
    } else {
        if (empty($args['sp_id']) && !empty($args['id'])) {
            $args['sp_id'] = $args['id'];
        }
    }
    if (empty($args['sp_title']) && !empty($args['title'])) {
        $args['sp_title'] = $args['title'];
    }
    if (empty($args['sp_content']) && !empty($args['content'])) {
        $args['sp_content'] = $args['content'];
    }
    if (isset($args['category']) && is_array($args['category']) && !empty($args['category'][0])) {
        $args['sp_tid'] = $args['category'][0];
    }
    if (!isset($args['owner_id'])) {
        $args['owner_id'] = $_USER['uid'];
    }
    if (empty($args['group_id'])) {
        $args['group_id'] = SEC_getFeatureGroup('staticpages.edit', $_USER['uid']);
    }
    $args['sp_id'] = COM_sanitizeID($args['sp_id']);
    if (!$gl_edit) {
        if (strlen($args['sp_id']) > STATICPAGE_MAX_ID_LENGTH) {
            $slug = '';
            if (isset($args['slug'])) {
                $slug = $args['slug'];
            }
            if (function_exists('WS_makeId')) {
                $args['sp_id'] = WS_makeId($slug, STATICPAGE_MAX_ID_LENGTH);
            } else {
                $args['sp_id'] = COM_makeSid();
            }
        }
    }
    // Apply filters to the parameters passed by the webservice
    if ($args['gl_svc']) {
        $par_str = array('mode', 'sp_id', 'sp_old_id', 'sp_tid', 'sp_format', 'postmode');
        $par_num = array('sp_hits', 'owner_id', 'group_id', 'sp_where', 'sp_php', 'commentcode');
        foreach ($par_str as $str) {
            if (isset($args[$str])) {
                $args[$str] = COM_applyBasicFilter($args[$str]);
            } else {
                $args[$str] = '';
            }
        }
        foreach ($par_num as $num) {
            if (isset($args[$num])) {
                $args[$num] = COM_applyBasicFilter($args[$num], true);
            } else {
                $args[$num] = 0;
            }
        }
    }
    // START: Staticpages defaults
    if (empty($args['sp_format'])) {
        $args['sp_format'] = 'allblocks';
    }
    if (empty($args['sp_tid'])) {
        $args['sp_tid'] = 'all';
    }
    if ($args['sp_where'] < 0 || $args['sp_where'] > 3) {
        $args['sp_where'] = 0;
    }
    if ($args['sp_php'] < 0 || $args['sp_php'] > 2) {
        $args['sp_php'] = 0;
    }
    if ($args['commentcode'] < -1 || $args['commentcode'] > 1) {
        $args['commentcode'] = $_CONF['comment_code'];
    }
    if ($args['gl_svc']) {
        // Permissions
        if (!isset($args['perm_owner'])) {
            $args['perm_owner'] = $_SP_CONF['default_permissions'][0];
        } else {
            $args['perm_owner'] = COM_applyBasicFilter($args['perm_owner'], true);
        }
        if (!isset($args['perm_group'])) {
            $args['perm_group'] = $_SP_CONF['default_permissions'][1];
        } else {
            $args['perm_group'] = COM_applyBasicFilter($args['perm_group'], true);
        }
        if (!isset($args['perm_members'])) {
            $args['perm_members'] = $_SP_CONF['default_permissions'][2];
        } else {
            $args['perm_members'] = COM_applyBasicFilter($args['perm_members'], true);
        }
        if (!isset($args['perm_anon'])) {
            $args['perm_anon'] = $_SP_CONF['default_permissions'][3];
        } else {
            $args['perm_anon'] = COM_applyBasicFilter($args['perm_anon'], true);
        }
        if (!isset($args['sp_onmenu'])) {
            $args['sp_onmenu'] = '';
        } elseif ($args['sp_onmenu'] == 'on' && empty($args['sp_label'])) {
            $svc_msg['error_desc'] = 'Menu label missing';
            return PLG_RET_ERROR;
        }
        if (empty($args['sp_content'])) {
            $svc_msg['error_desc'] = 'No content';
            return PLG_RET_ERROR;
        }
        if (empty($args['sp_inblock']) && $_SP_CONF['in_block'] == '1') {
            $args['sp_inblock'] = 'on';
        }
        if (empty($args['sp_centerblock'])) {
            $args['sp_centerblock'] = '';
        }
        if (empty($args['draft_flag']) && $_SP_CONF['draft_flag'] == '1') {
            $args['draft_flag'] = 'on';
        }
        if (empty($args['template_flag'])) {
            $args['template_flag'] = '';
        }
        if (empty($args['template_id'])) {
            $args['template_id'] = '';
        }
    }
    // END: Staticpages defaults
    $sp_id = $args['sp_id'];
    $sp_title = $args['sp_title'];
    $sp_page_title = $args['sp_page_title'];
    $sp_content = $args['sp_content'];
    $sp_hits = $args['sp_hits'];
    $sp_format = $args['sp_format'];
    $sp_onmenu = $args['sp_onmenu'];
    $sp_label = '';
    if (!empty($args['sp_label'])) {
        $sp_label = $args['sp_label'];
    }
    $meta_description = $args['meta_description'];
    $meta_keywords = $args['meta_keywords'];
    $commentcode = $args['commentcode'];
    $owner_id = $args['owner_id'];
    $group_id = $args['group_id'];
    $perm_owner = $args['perm_owner'];
    $perm_group = $args['perm_group'];
    $perm_members = $args['perm_members'];
    $perm_anon = $args['perm_anon'];
    $sp_php = $args['sp_php'];
    $sp_nf = '';
    if (!empty($args['sp_nf'])) {
        $sp_nf = $args['sp_nf'];
    }
    $sp_old_id = $args['sp_old_id'];
    $sp_centerblock = $args['sp_centerblock'];
    $draft_flag = $args['draft_flag'];
    $template_flag = $args['template_flag'];
    $template_id = $args['template_id'];
    $sp_help = '';
    if (!empty($args['sp_help'])) {
        $sp_help = $args['sp_help'];
    }
    $sp_tid = $args['sp_tid'];
    $sp_where = $args['sp_where'];
    $sp_inblock = $args['sp_inblock'];
    $postmode = $args['postmode'];
    if ($gl_edit && !empty($args['gl_etag'])) {
        // First load the original staticpage to check if it has been modified
        $o = array();
        $s = array();
        $r = service_get_staticpages(array('sp_id' => $sp_old_id, 'gl_svc' => true), $o, $s);
        if ($r == PLG_RET_OK) {
            if ($args['gl_etag'] != $o['updated']) {
                $svc_msg['error_desc'] = 'A more recent version of the staticpage is available';
                return PLG_RET_PRECONDITION_FAILED;
            }
        } else {
            $svc_msg['error_desc'] = 'The requested staticpage no longer exists';
            return PLG_RET_ERROR;
        }
    }
    // Check for unique page ID
    $duplicate_id = false;
    $delete_old_page = false;
    if (DB_count($_TABLES['staticpage'], 'sp_id', $sp_id) > 0) {
        if ($sp_id != $sp_old_id) {
            $duplicate_id = true;
        }
    } elseif (!empty($sp_old_id)) {
        if ($sp_id != $sp_old_id) {
            $delete_old_page = true;
        }
    }
    if ($duplicate_id) {
        $output .= COM_siteHeader('menu', $LANG_STATIC['staticpageeditor']);
        $output .= COM_errorLog($LANG_STATIC['duplicate_id'], 2);
        if (!$args['gl_svc']) {
            $output .= staticpageeditor($sp_id);
        }
        $output .= COM_siteFooter();
        $svc_msg['error_desc'] = 'Duplicate ID';
        return PLG_RET_ERROR;
    } elseif (!empty($sp_title) && !empty($sp_content)) {
        if (empty($sp_hits)) {
            $sp_hits = 0;
        }
        if ($sp_onmenu == 'on') {
            $sp_onmenu = 1;
        } else {
            $sp_onmenu = 0;
        }
        if ($sp_nf == 'on') {
            $sp_nf = 1;
        } else {
            $sp_nf = 0;
        }
        if ($sp_centerblock == 'on') {
            $sp_centerblock = 1;
        } else {
            $sp_centerblock = 0;
        }
        if ($sp_inblock == 'on') {
            $sp_inblock = 1;
        } else {
            $sp_inblock = 0;
        }
        if ($draft_flag == 'on') {
            $draft_flag = 1;
        } else {
            $draft_flag = 0;
        }
        if ($template_flag == 'on') {
            $template_flag = 1;
        } else {
            $template_flag = 0;
        }
        // Remove any autotags the user doesn't have permission to use
        $sp_content = PLG_replaceTags($sp_content, '', true);
        // Clean up the text
        if ($_SP_CONF['censor'] == 1) {
            $sp_content = COM_checkWords($sp_content);
            $sp_title = COM_checkWords($sp_title);
        }
        if ($_SP_CONF['filter_html'] == 1) {
            $sp_content = COM_checkHTML($sp_content, 'staticpages.edit');
        }
        $sp_title = strip_tags($sp_title);
        $sp_page_title = strip_tags($sp_page_title);
        $sp_label = strip_tags($sp_label);
        $meta_description = strip_tags($meta_description);
        $meta_keywords = strip_tags($meta_keywords);
        $sp_content = addslashes($sp_content);
        $sp_title = addslashes($sp_title);
        $sp_page_title = addslashes($sp_page_title);
        $sp_label = addslashes($sp_label);
        $meta_description = addslashes($meta_description);
        $meta_keywords = addslashes($meta_keywords);
        // If user does not have php edit perms, then set php flag to 0.
        if ($_SP_CONF['allow_php'] != 1 || !SEC_hasRights('staticpages.PHP')) {
            $sp_php = 0;
        }
        // If marked as a template then set id to nothing and other default settings
        if ($template_flag == 1) {
            $template_id = '';
            $sp_onmenu = 0;
            $sp_label = "";
            $sp_centerblock = 0;
            $sp_php = 0;
            $sp_inblock = 0;
            $sp_nf = 0;
            $sp_hits = 0;
            $meta_description = "";
            $meta_keywords = "";
        } else {
            // See if it was a template before, if so and option changed, remove use from other pages
            if (DB_getItem($_TABLES['staticpage'], 'template_flag', "sp_id = '{$sp_old_id}'") == 1) {
                $sql = "UPDATE {$_TABLES['staticpage']} SET template_id = '' WHERE template_id = '{$sp_old_id}'";
                $result = DB_query($sql);
            }
            if ($template_id != '') {
                // If using a template, make sure php disabled
                $sp_php = 0;
                // Double check template id exists and is still a template
                $perms = SP_getPerms();
                if (!empty($perms)) {
                    $perms = ' AND ' . $perms;
                }
                if (DB_getItem($_TABLES['staticpage'], 'COUNT(sp_id)', "sp_id = '{$template_id}' AND template_flag = 1 AND (draft_flag = 0)" . $perms) == 0) {
                    $template_id = '';
                }
            }
        }
        // make sure there's only one "entire page" static page per topic
        if ($sp_centerblock == 1 && $sp_where == 0) {
            $sql = "UPDATE {$_TABLES['staticpage']} SET sp_centerblock = 0 WHERE (sp_centerblock = 1) AND (sp_where = 0) AND (sp_tid = '{$sp_tid}') AND (draft_flag = 0)";
            // if we're in a multi-language setup, we need to allow one "entire
            // page" centerblock for 'all' or 'none' per language
            if (!empty($_CONF['languages']) && !empty($_CONF['language_files']) && ($sp_tid == 'all' || $sp_tid == 'none')) {
                $ids = explode('_', $sp_id);
                if (count($ids) > 1) {
                    $lang_id = array_pop($ids);
                    $sql .= " AND sp_id LIKE '%\\_{$lang_id}'";
                }
            }
            DB_query($sql);
        }
        $formats = array('allblocks', 'blankpage', 'leftblocks', 'noblocks');
        if (!in_array($sp_format, $formats)) {
            $sp_format = 'allblocks';
        }
        if (!$args['gl_svc']) {
            list($perm_owner, $perm_group, $perm_members, $perm_anon) = SEC_getPermissionValues($perm_owner, $perm_group, $perm_members, $perm_anon);
        }
        // Retrieve created date
        $datecreated = DB_getItem($_TABLES['staticpage'], 'created', "sp_id = '{$sp_id}'");
        if ($datecreated == '') {
            $datecreated = date('Y-m-d H:i:s');
        }
        DB_save($_TABLES['staticpage'], 'sp_id,sp_title,sp_page_title, sp_content,created,modified,sp_hits,sp_format,sp_onmenu,sp_label,commentcode,meta_description,meta_keywords,template_flag,template_id,draft_flag,owner_id,group_id,' . 'perm_owner,perm_group,perm_members,perm_anon,sp_php,sp_nf,sp_centerblock,sp_help,sp_tid,sp_where,sp_inblock,postmode', "'{$sp_id}','{$sp_title}','{$sp_page_title}','{$sp_content}','{$datecreated}',NOW(),{$sp_hits},'{$sp_format}',{$sp_onmenu},'{$sp_label}','{$commentcode}','{$meta_description}','{$meta_keywords}',{$template_flag},'{$template_id}',{$draft_flag},{$owner_id},{$group_id}," . "{$perm_owner},{$perm_group},{$perm_members},{$perm_anon},'{$sp_php}','{$sp_nf}',{$sp_centerblock},'{$sp_help}','{$sp_tid}',{$sp_where}," . "'{$sp_inblock}','{$postmode}'");
        if ($delete_old_page && !empty($sp_old_id)) {
            // If a template and the id changed, update any staticpages that use it
            if ($template_flag == 1) {
                $sql = "UPDATE {$_TABLES['staticpage']} SET template_id = '{$sp_id}' WHERE template_id = '{$sp_old_id}'";
                $result = DB_query($sql);
            }
            DB_delete($_TABLES['staticpage'], 'sp_id', $sp_old_id);
        }
        if (empty($sp_old_id) || $sp_id == $sp_old_id) {
            if (!$template_flag) {
                PLG_itemSaved($sp_id, 'staticpages');
            } else {
                // If template then have to notify of all pages that use this template that a change to the page happened
                $sql = "SELECT sp_id FROM {$_TABLES['staticpage']} WHERE template_id = '{$sp_id}'";
                $result = DB_query($sql);
                while ($A = DB_fetchArray($result)) {
                    PLG_itemSaved($A['sp_id'], 'staticpages');
                }
            }
        } else {
            DB_change($_TABLES['comments'], 'sid', addslashes($sp_id), array('sid', 'type'), array(addslashes($sp_old_id), 'staticpages'));
            if (!$template_flag) {
                PLG_itemSaved($sp_id, 'staticpages', $sp_old_id);
            } else {
                // If template then have to notify of all pages that use this template that a change to the page happened
                $sql = "SELECT sp_id FROM {$_TABLES['staticpage']} WHERE template_id = '{$sp_id}'";
                $result = DB_query($sql);
                while ($A = DB_fetchArray($result)) {
                    PLG_itemSaved($A['sp_id'], 'staticpages');
                }
            }
        }
        $url = COM_buildURL($_CONF['site_url'] . '/staticpages/index.php?page=' . $sp_id);
        $output .= PLG_afterSaveSwitch($_SP_CONF['aftersave'], $url, 'staticpages', 19);
        $svc_msg['id'] = $sp_id;
        return PLG_RET_OK;
    } else {
        $output .= COM_siteHeader('menu', $LANG_STATIC['staticpageeditor']);
        $output .= COM_errorLog($LANG_STATIC['no_title_or_content'], 2);
        if (!$args['gl_svc']) {
            $output .= staticpageeditor($sp_id);
        }
        $output .= COM_siteFooter();
        return PLG_RET_ERROR;
    }
}
Example #15
0
function MG_watermarkBatchProcess($album_id, $mid)
{
    global $_CONF, $_MG_CONF, $_TABLES;
    $sql = "SELECT media_id,media_watermarked,media_type,media_filename,media_mime_ext " . "FROM {$_TABLES['mg_media']} WHERE media_id='" . addslashes($mid) . "'";
    $result = DB_query($sql);
    $nRows = DB_numRows($result);
    if ($nRows > 0) {
        $row = DB_fetchArray($result);
        if ($row['media_watermarked'] == 1 || $row['media_type'] != 0) {
            return;
        }
        if ($_MG_CONF['discard_original'] == 1) {
            $origImage = $_MG_CONF['path_mediaobjects'] . 'disp/' . $row['media_filename'][0] . '/' . $row['media_filename'] . '.jpg';
            $rc = MG_watermark($origImage, $album_id, 1);
        } else {
            $origImage = $_MG_CONF['path_mediaobjects'] . 'orig/' . $row['media_filename'][0] . '/' . $row['media_filename'] . '.' . $row['media_mime_ext'];
            $rc = MG_watermark($origImage, $album_id, 1);
            if ($rc == true) {
                $origImage = '';
                foreach ($_MG_CONF['validExtensions'] as $ext) {
                    if (file_exists($_MG_CONF['path_mediaobjects'] . 'disp/' . $row['media_filename'][0] . '/' . $row['media_filename'] . $ext)) {
                        $origImage = $_MG_CONF['path_mediaobjects'] . 'disp/' . $row['media_filename'][0] . '/' . $row['media_filename'] . $ext;
                        break;
                    }
                }
                if ($origImage != '') {
                    $rc = MG_watermark($origImage, $album_id, 0);
                }
            }
        }
        // update the database to show they have been watermarked...
        if ($rc == true) {
            DB_change($_TABLES['mg_media'], 'media_watermarked', 1, 'media_id', addslashes($mid));
        }
    }
    return;
}
Example #16
0
/**
 * Change a topic's ID in various places
 *
 * @param    string $tid new Topic ID
 * @parem    string $old_tid current Topic ID
 * @return   void
 */
function changetopicid($tid, $old_tid)
{
    global $_TABLES;
    DB_change($_TABLES['topic_assignments'], 'tid', $tid, 'tid', $old_tid);
    DB_change($_TABLES['topics'], 'parent_id', $tid, 'parent_id', $old_tid);
    DB_change($_TABLES['syndication'], 'header_tid', $tid, 'header_tid', $old_tid);
    $result = DB_query("SELECT uid,tids,etids FROM {$_TABLES['userindex']} WHERE tids LIKE '%{$old_tid}%' OR etids LIKE '%{$old_tid}%'");
    $num_users = DB_numRows($result);
    for ($i = 0; $i < $num_users; $i++) {
        $changed = false;
        list($uid, $tids, $etids) = DB_fetchArray($result);
        // check list of excluded topics
        $t = explode(' ', $tids);
        if (count($t) > 0) {
            $found = array_search($old_tid, $t);
            if ($found !== false) {
                $t[$found] = $tid;
                $tids = implode(' ', $t);
                $changed = true;
            }
        }
        // check topics for the Daily Digest
        if (!empty($etids) && $etids !== '-') {
            $e = explode(' ', $etids);
            if (count($e) > 0) {
                $found = array_search($old_tid, $e);
                if ($found !== false) {
                    $e[$found] = $tid;
                    $etids = implode(' ', $e);
                    $changed = true;
                }
            }
        }
        if ($changed) {
            // etids can be both NULL and "", so special handling required
            if ($etids === null) {
                DB_change($_TABLES['userindex'], 'tids', $tids, 'uid', $uid);
            } else {
                DB_query("UPDATE {$_TABLES['userindex']} SET tids = '{$tids}', etids = '{$etids}' WHERE uid = {$uid}");
            }
        }
    }
}
Example #17
0
/**
* Handle uploaded plugin
*
* @return   string      HTML: redirect or main plugin screen + error message
*
*/
function plugin_upload()
{
    global $_CONF, $_TABLES;
    $retval = '';
    $path_admin = $_CONF['path_html'] . substr($_CONF['site_admin_url'], strlen($_CONF['site_url']) + 1) . '/';
    $upload_success = false;
    // If an error occured while uploading the file.
    $error_msg = plugin_getUploadError($_FILES['plugin']);
    if (!empty($error_msg)) {
        $retval .= plugin_main($error_msg);
    } else {
        require_once $_CONF['path_system'] . 'classes/unpacker.class.php';
        $plugin_file = $_CONF['path_data'] . $_FILES['plugin']['name'];
        // Name the plugin file
        $archive = new unpacker($_FILES['plugin']['tmp_name'], $_FILES['plugin']['type']);
        $tmp = $archive->getlist();
        // Grab the contents of the tarball to see what the plugin name is
        $dirname = preg_replace('/\\/.*$/', '', $tmp[0]['filename']);
        if (empty($dirname)) {
            // If $dirname is blank it's probably because the user uploaded a non Tarball file.
            $retval = COM_refresh($_CONF['site_admin_url'] . '/plugins.php?msg=100');
        } else {
            $pi_did_exist = false;
            // plugin directory already existed
            $pi_had_entry = false;
            // plugin had an entry in the database
            $pi_was_enabled = false;
            // plugin was enabled
            if (file_exists($_CONF['path'] . 'plugins/' . $dirname)) {
                $pi_did_exist = true;
                // plugin directory already exists
                $pstatus = DB_query("SELECT pi_name, pi_enabled FROM {$_TABLES['plugins']} WHERE pi_name = '{$dirname}'");
                $A = DB_fetchArray($pstatus);
                if (isset($A['pi_name'])) {
                    $pi_had_entry = true;
                    $pi_was_enabled = $A['pi_enabled'] == 1;
                }
                if ($pi_was_enabled) {
                    // disable temporarily while we move the files around
                    DB_change($_TABLES['plugins'], 'pi_enabled', 0, 'pi_name', $dirname);
                }
                require_once 'System.php';
                $plugin_dir = $_CONF['path'] . 'plugins/' . $dirname;
                if (file_exists($plugin_dir . '.previous')) {
                    @System::rm('-rf ' . $plugin_dir . '.previous');
                }
                if (file_exists($plugin_dir)) {
                    rename($plugin_dir, $plugin_dir . '.previous');
                }
                $public_dir = $_CONF['path_html'] . $dirname;
                if (file_exists($public_dir . '.previous')) {
                    @System::rm('-rf ' . $public_dir . '.previous');
                }
                if (file_exists($public_dir)) {
                    rename($public_dir, $public_dir . '.previous');
                }
                $admin_dir = $path_admin . 'plugins/' . $dirname;
                if (file_exists($admin_dir . '.previous')) {
                    @System::rm('-rf ' . $admin_dir . '.previous');
                }
                if (file_exists($admin_dir)) {
                    rename($admin_dir, $admin_dir . '.previous');
                }
            }
            /**
             * Install the plugin
             * This doesn't work if the public_html & public_html/admin/plugins directories aren't 777
             */
            // Extract the tarball to data so we can get the $pi_name name from admin/install.php
            $archive->unpack($_CONF['path'] . 'data/', array($dirname . '/admin/install.php'));
            $plugin_inst = $_CONF['path'] . 'data/' . $dirname . '/admin/install.php';
            $fdata = '';
            $fhandle = @fopen($plugin_inst, 'r');
            if ($fhandle) {
                $fdata = fread($fhandle, filesize($plugin_inst));
                fclose($fhandle);
            }
            // Remove the plugin from data/
            require_once 'System.php';
            @System::rm('-rf ' . $_CONF['path'] . 'data/' . $dirname);
            /**
             * One time I wanted to install a muffler on my car and
             * needed to match up the outside diameter of the car's
             * exhaust pipe to the inside diameter of the muffler.
             * Unfortunately, when I went to the auto parts store they
             * didn't have a coupling adapter that would perfectly
             * match the two pipes, only a bunch of smaller adapters.
             * I ended up using about 4 small adapters to step down
             * one size at a time to the size of the muffler's input.
             *
             * It's kind of like this regular expression:
             *
             */
            $fdata = preg_replace('/\\n/', '', $fdata);
            $fdata = preg_replace('/ /', '', $fdata);
            $pi_name = preg_replace('/^.*\\$pi\\_name=\'/', '', $fdata);
            $pi_name = preg_replace('/\'.*$/', '', $pi_name);
            // Some plugins don't have $pi_name set in their install.php file,
            // This means our regex won't work and we should just use $dirname
            if (preg_match('/\\<\\?php/', $pi_name) || preg_match('/--/', $pi_name)) {
                $pi_name = $dirname;
            } elseif (empty($pi_name)) {
                $pi_name = $dirname;
            }
            // Extract the uploaded archive to the plugins directory
            $upload_success = $archive->unpack($_CONF['path'] . 'plugins/');
            $plg_path = $_CONF['path'] . 'plugins/' . $pi_name . '/';
            if ($upload_success) {
                if (file_exists($plg_path . 'public_html')) {
                    rename($plg_path . 'public_html', $_CONF['path_html'] . $pi_name);
                }
                if (file_exists($plg_path . 'admin')) {
                    rename($plg_path . 'admin', $path_admin . 'plugins/' . $pi_name);
                }
            }
            unset($archive);
            // Collect some garbage
            // cleanup when uploading a new version
            if ($pi_did_exist) {
                $plugin_dir = $_CONF['path'] . 'plugins/' . $dirname;
                if (file_exists($plugin_dir . '.previous')) {
                    @System::rm('-rf ' . $plugin_dir . '.previous');
                }
                $public_dir = $_CONF['path_html'] . $dirname;
                if (file_exists($public_dir . '.previous')) {
                    @System::rm('-rf ' . $public_dir . '.previous');
                }
                $admin_dir = $path_admin . 'plugins/' . $dirname;
                if (file_exists($admin_dir . '.previous')) {
                    @System::rm('-rf ' . $admin_dir . '.previous');
                }
                if ($pi_was_enabled) {
                    DB_change($_TABLES['plugins'], 'pi_enabled', 1, 'pi_name', $dirname);
                }
            }
            $msg_with_plugin_name = false;
            if ($pi_did_exist) {
                if ($pi_was_enabled) {
                    // check if we have to perform an update
                    $pi_version = DB_getItem($_TABLES['plugins'], 'pi_version', "pi_name = '{$dirname}'");
                    $code_version = PLG_chkVersion($dirname);
                    if (!empty($code_version) && $code_version != $pi_version) {
                        /**
                         * At this point, we would have to call PLG_upgrade().
                         * However, we've loaded the plugin's old functions.inc
                         * (in lib-common.php). We can't load the new one here
                         * now since that would result in duplicate function
                         * definitions. Solution: Trigger a reload (with the new
                         * functions.inc) and continue there.
                         */
                        $url = $_CONF['site_admin_url'] . '/plugins.php' . '?mode=continue_upgrade' . '&amp;codeversion=' . urlencode($code_version) . '&amp;piversion=' . urlencode($pi_version) . '&amp;plugin=' . urlencode($dirname);
                        echo COM_refresh($url);
                        exit;
                    } else {
                        $msg = 98;
                        // successfully uploaded
                    }
                } else {
                    $msg = 98;
                    // successfully uploaded
                }
            } elseif (file_exists($plg_path . 'autoinstall.php')) {
                // if the plugin has an autoinstall.php, install it now
                if (plugin_autoinstall($pi_name)) {
                    PLG_pluginStateChange($pi_name, 'installed');
                    $msg = 44;
                    // successfully installed
                } else {
                    $msg = 72;
                    // an error occured while installing the plugin
                }
            } else {
                $msg = 98;
                // successfully uploaded
            }
            $url = $_CONF['site_admin_url'] . '/plugins.php?msg=' . $msg;
            if ($msg_with_plugin_name) {
                $url .= '&amp;plugin=' . $dirname;
            }
            $retval = COM_refresh($url);
        }
    }
    return $retval;
}
Example #18
0
// +---------------------------------------------------------------------------+
require_once '../lib-common.php';
if (!in_array('banner', $_PLUGINS)) {
    echo COM_refresh($_CONF['site_url'] . '/index.php');
    exit;
}
// MAIN
$url = '';
COM_setArgNames(array('what', 'item'));
$what = COM_getArgument('what');
if ($what == 'banner') {
    $item = COM_applyFilter(COM_getArgument('item'));
    if (!empty($item)) {
        // Hack: due to PLG_afterSaveSwitch settings, we may get
        // an attached &msg - strip it off
        $i = explode('&', $item);
        $item = $i[0];
    }
    if (!empty($item)) {
        $url = DB_getItem($_TABLES['banner'], 'url', "bid = '{$item}' AND (publishstart IS NULL OR publishstart < NOW()) and (publishend IS NULL OR publishend > NOW())");
        if (!empty($url)) {
            DB_change($_TABLES['banner'], 'hits', 'hits + 1', 'bid', $item, '', true);
        }
    }
}
if (empty($url)) {
    $url = $_CONF['site_url'];
}
header('HTTP/1.1 301 Moved');
header('Location: ' . $url);
header('Connection: close');
Example #19
0
/**
 * Plugin function that is called after comment form is submitted.
 * Needs to at least save the comment and check return value.
 * Add any additional logic your plugin may need to perform on comments.
 *
 * $title       comment title
 * $comment     comment text
 * $id          Item id to which $cid belongs
 * $pid         comment parent
 * $postmode    'html' or 'text'
 *
 */
function _mg_savecomment($title, $comment, $id, $pid, $postmode)
{
    global $_CONF, $_MG_CONF, $_TABLES, $LANG03;
    $retval = '';
    $title = strip_tags($title);
    $pid = COM_applyFilter($pid, true);
    $postmode = COM_applyFilter($postmode);
    $ret = CMT_saveComment($title, $comment, $id, $pid, 'mediagallery', $postmode);
    if ($ret > 0) {
        $retval = '';
        if (SESS_isSet('glfusion.commentpresave.error')) {
            $retval = COM_showMessageText(SESS_getVar('glfusion.commentpresave.error'), '', true);
            SESS_unSet('glfusion.commentpresave.error');
        }
        $retval .= CMT_commentform($title, $comment, $id, $pid, 'mediagallery', $LANG03[14], $postmode);
        return $retval;
    } else {
        $comments = DB_count($_TABLES['comments'], array('sid', 'type'), array(DB_escapeString($id), 'mediagallery'));
        DB_change($_TABLES['mg_media'], 'media_comments', $comments, 'media_id', DB_escapeString($id));
        return COM_refresh($_MG_CONF['site_url'] . "/media.php?s={$id}#comments");
    }
}
Example #20
0
/**
 * Continues a session - handles timeout, looping, etc.
 *
 * @parm    char    session id to continue
 * @parm    int     number of items to process per run
 *                  0 indicates initial run
 * @return  char    HTML of status screen
 */
function MG_continueSession($session_id, $item_limit, $refresh_rate)
{
    global $_CONF, $_MG_CONF, $_TABLES, $_USER, $LANG_MG00, $LANG_MG01, $LANG_MG02;
    $retval = '';
    $cycle_start_time = time();
    $temp_time = array();
    $timer_expired = false;
    $num_rows = 0;
    $session_id = COM_applyFilter($session_id);
    // Pull the session status info
    $sql = "SELECT * FROM {$_TABLES['mg_sessions']} " . "WHERE session_id='" . addslashes($session_id) . "'";
    $result = DB_query($sql, 1);
    if (DB_error()) {
        COM_errorLog("MediaGallery:  Error - Unable to retrieve batch session data");
        return '';
    }
    $nRows = DB_numRows($result);
    if ($nRows > 0) {
        $session = DB_fetchArray($result);
    } else {
        COM_errorLog("MediaGallery: Error - Unable to find batch session id");
        return '';
        // no session found
    }
    // security check - make sure we are continuing a session that we own...
    if ($session['session_uid'] != $_USER['uid'] && !SEC_hasRights('mediagallery.admin')) {
        return COM_showMessageText($LANG_MG00['access_denied_msg']);
    }
    // Setup timer information
    $time_limit = $_MG_CONF['def_time_limit'];
    @set_time_limit($time_limit + 20);
    // get execution time
    $max_execution_time = ini_get('max_execution_time');
    if ($time_limit > $max_execution_time) {
        $time_limit = $max_execution_time;
    }
    $label = COM_stripslashes($session['session_description']);
    // Pull the detail data from the sessions_items table...
    $sql = "SELECT * FROM {$_TABLES['mg_session_items']} " . "WHERE session_id='" . addslashes($session_id) . "' " . "AND status=0 LIMIT " . $item_limit;
    $result = DB_query($sql);
    while (($row = DB_fetchArray($result)) && $timer_expired == false) {
        // used for calculating loop duration and changing the timer condition
        $start_temp_time = time();
        $function = 'mg_batch_session_' . $session['session_action'];
        if (function_exists($function)) {
            $function($row);
            DB_change($_TABLES['mg_session_items'], 'status', 1, 'id', $row['id']);
        }
        // calculate time for each loop iteration
        $temp_time[$num_rows] = time() - $start_temp_time;
        // get the max
        $timer_time = max($temp_time);
        $num_rows++;
        // check if timer is about to expire
        if (time() - $cycle_start_time >= $time_limit - $timer_time) {
            $timer_expired_secs = time() - $cycle_start_time;
            $timer_expired = true;
        }
    }
    // end the timer
    $cycle_end_time = time();
    // find how much time the last cycle took
    $last_cycle_time = $cycle_end_time - $cycle_start_time;
    $T = COM_newTemplate(MG_getTemplatePath(0));
    $T->set_file('batch', 'batch_progress.thtml');
    $processing_messages = '';
    if ($timer_expired) {
        $processing_messages = '<p>' . sprintf($LANG_MG01['timer_expired'], $timer_expired_secs) . '</p>';
    }
    $sql = "SELECT COUNT(*) AS processed " . "FROM {$_TABLES['mg_session_items']} " . "WHERE session_id='" . addslashes($session_id) . "' AND status=1";
    $result = DB_query($sql);
    $row = DB_fetchArray($result);
    $session_items_processed = $row['processed'];
    $sql = "SELECT COUNT(*) AS processing " . "FROM {$_TABLES['mg_session_items']} " . "WHERE session_id='" . addslashes($session_id) . "'";
    $result = DB_query($sql);
    $row = DB_fetchArray($result);
    $session_items_processing = $row['processing'];
    $items_remaining = $session_items_processing - $session_items_processed;
    if ($items_remaining > 0) {
        if ($item_limit == 0) {
            $processing_messages .= '<p>' . $LANG_MG01['begin_processing'] . '</p>';
            $item_limit = $_MG_CONF['def_item_limit'];
        } else {
            $processing_messages .= '<p>' . sprintf($LANG_MG01['processing_next_items'], $item_limit) . '</p>';
        }
        $form_action = $_MG_CONF['site_url'] . '/batch.php?mode=continue&amp;sid=' . $session_id . '&amp;refresh=' . $refresh_rate . '&amp;limit=' . $item_limit;
        $next_button = $LANG_MG01['next'];
        // create the meta tag for refresh
        $T->set_var("META", '<meta http-equiv="refresh" content="' . $refresh_rate . ';url=' . $form_action . '"' . XHTML . '>');
    } else {
        if ($item_limit == 0) {
            echo COM_refresh($session['session_origin']);
            exit;
        }
        $next_button = $LANG_MG01['finished'];
        $processing_messages .= '<p>' . $LANG_MG01['all_done'] . '</p>';
        $T->set_var("META", '');
        $refresh_rate = -1;
        $form_action = $session['session_origin'];
        $result = DB_query("SELECT * FROM {$_TABLES['mg_session_log']} " . "WHERE session_id='" . addslashes($session_id) . "'");
        while ($row = DB_fetchArray($result)) {
            $processing_messages .= '<p>' . $row['session_log'] . '</p>';
        }
        MG_endSession($session_id);
    }
    $session_percent = $session_items_processed / $session_items_processing * 100;
    $session_time = $cycle_end_time - $session['session_start_time'];
    $T->set_var(array('L_BATCH_PROCESS' => $label, 'L_BATCH' => $LANG_MG01['batch_sessions'], 'L_NEXT' => $next_button, 'L_PROCESSING' => $LANG_MG01['processing'], 'L_CANCEL' => $LANG_MG01['cancel'], 'L_PROCESSING_DETAILS' => $LANG_MG01['processing_details'], 'L_STATUS' => $LANG_MG01['status'], 'L_TOTAL_ITEMS' => $LANG_MG01['total_items'], 'L_ITEMS_PROCESSED' => $LANG_MG01['processed_items'], 'L_ITEMS_REMAINING' => $LANG_MG01['items_remaining'], 'L_POSTS_LAST_CYCLE' => $LANG_MG01['items_last_cycle'], 'L_TIME_LIMIT' => $LANG_MG01['time_limit'], 'L_REFRESH_RATE' => $LANG_MG01['refresh_rate'], 'L_ITEM_RATE' => $LANG_MG01['item_rate'], 'L_ACTIVE_PARAMETERS' => $LANG_MG01['batch_parameters'], 'L_ITEMS_PER_CYCLE' => $LANG_MG01['items_per_cycle'], 'TOTAL_ITEMS' => $session_items_processing, 'ITEMS_PROCESSED' => $session_items_processed, 'ITEMS_REMAINING' => $session_items_processing - $session_items_processed, 'ITEM_RATE' => sprintf($LANG_MG01['seconds_per_item'], round(@($last_cycle_time / $num_rows))), 'PROCESSING_MESSAGES' => $processing_messages, 'SESSION_PERCENT' => round($session_percent, 2) . ' %', 'POST_LIMIT' => $num_rows, 'ITEM_LIMIT' => $item_limit, 'TIME_LIMIT' => $time_limit, 'REFRESH_RATE' => $refresh_rate, 'S_BATCH_ACTION' => $form_action));
    $retval .= $T->finish($T->parse('output', 'batch'));
    return $retval;
}
Example #21
0
/**
* Syndication import function. Imports headline data to a portal block.
*
* Rewritten December 19th 2004 by Michael Jervis (mike AT fuckingbrit DOT com).
* Now utilises a Factory Pattern to open a URL and automaticaly retreive a feed
* object populated with feed data. Then import it into the portal block.
*
* @param    string  $bid            Block ID
* @param    string  $rdfurl         URL to get content from
* @param    int     $maxheadlines   Maximum number of headlines to display
* @return   void
* @see function COM_rdfCheck
*
*/
function COM_rdfImport($bid, $rdfurl, $maxheadlines = 0)
{
    global $_CONF, $_TABLES, $LANG21;
    // Import the feed handling classes:
    require_once $_CONF['path_system'] . '/classes/syndication/parserfactory.class.php';
    require_once $_CONF['path_system'] . '/classes/syndication/feedparserbase.class.php';
    $result = DB_query("SELECT rdf_last_modified, rdf_etag FROM {$_TABLES['blocks']} WHERE bid = {$bid}");
    list($last_modified, $etag) = DB_fetchArray($result);
    // Load the actual feed handlers:
    $factory = new FeedParserFactory($_CONF['path_system'] . '/classes/syndication/');
    $factory->userAgent = 'Geeklog/' . VERSION;
    if (!empty($last_modified) && !empty($etag)) {
        $factory->lastModified = $last_modified;
        $factory->eTag = $etag;
    }
    // Aquire a reader:
    $feed = $factory->reader($rdfurl, $_CONF['default_charset']);
    if ($feed) {
        /* We have located a reader, and populated it with the information from
         * the syndication file. Now we will sort out our display, and update
         * the block.
         */
        if ($maxheadlines == 0) {
            if (!empty($_CONF['syndication_max_headlines'])) {
                $maxheadlines = $_CONF['syndication_max_headlines'];
            } else {
                $maxheadlines = count($feed->articles);
            }
        }
        $update = date('Y-m-d H:i:s');
        $last_modified = '';
        if (!empty($factory->lastModified)) {
            $last_modified = addslashes($factory->lastModified);
        }
        $etag = '';
        if (!empty($factory->eTag)) {
            $etag = addslashes($factory->eTag);
        }
        if (empty($last_modified) || empty($etag)) {
            DB_query("UPDATE {$_TABLES['blocks']} SET rdfupdated = '{$update}', rdf_last_modified = NULL, rdf_etag = NULL WHERE bid = '{$bid}'");
        } else {
            DB_query("UPDATE {$_TABLES['blocks']} SET rdfupdated = '{$update}', rdf_last_modified = '{$last_modified}', rdf_etag = '{$etag}' WHERE bid = '{$bid}'");
        }
        $charset = COM_getCharset();
        // format articles for display
        $readmax = min($maxheadlines, count($feed->articles));
        for ($i = 0; $i < $readmax; $i++) {
            if (empty($feed->articles[$i]['title'])) {
                $feed->articles[$i]['title'] = $LANG21[61];
            }
            if ($charset == 'utf-8') {
                $title = $feed->articles[$i]['title'];
            } else {
                $title = utf8_decode($feed->articles[$i]['title']);
            }
            if ($feed->articles[$i]['link'] != '') {
                $content = COM_createLink($title, $feed->articles[$i]['link']);
            } elseif ($feed->articles[$i]['enclosureurl'] != '') {
                $content = COM_createLink($title, $feed->articles[$i]['enclosureurl']);
            } else {
                $content = $title;
            }
            $articles[] = $content;
        }
        // build a list
        $content = COM_makeList($articles, 'list-feed');
        $content = str_replace(array("\r", "\n"), '', $content);
        if (strlen($content) > 65000) {
            $content = $LANG21[68];
        }
        // Standard theme based function to put it in the block
        $result = DB_change($_TABLES['blocks'], 'content', addslashes($content), 'bid', $bid);
    } else {
        if ($factory->errorStatus !== false) {
            // failed to aquire info, 0 out the block and log an error
            COM_errorLog("Unable to aquire feed reader for {$rdfurl}", 1);
            COM_errorLog($factory->errorStatus[0] . ' ' . $factory->errorStatus[1] . ' ' . $factory->errorStatus[2]);
            $content = addslashes($LANG21[4]);
            DB_query("UPDATE {$_TABLES['blocks']} SET content = '{$content}', rdf_last_modified = NULL, rdf_etag = NULL WHERE bid = {$bid}");
        }
    }
}
Example #22
0
/**
* Set Geeklog version number in siteconfig.php and in the database
*
* @param   string  $siteconfig_path    path to siteconfig.php
* @return  void
*
*/
function INST_setVersion($siteconfig_path)
{
    global $_TABLES, $LANG_INSTALL;
    clearstatcache();
    $siteconfig_file = fopen($siteconfig_path, 'rb');
    $siteconfig_data = fread($siteconfig_file, filesize($siteconfig_path));
    fclose($siteconfig_file);
    $siteconfig_data = preg_replace('/define\\s*\\(\'VERSION\',[^;]*;/', "define('VERSION', '" . VERSION . "');", $siteconfig_data);
    $siteconfig_file = @fopen($siteconfig_path, 'wb');
    if (!fwrite($siteconfig_file, $siteconfig_data)) {
        exit($LANG_INSTALL[26] . ' ' . $LANG_INSTALL[28]);
    }
    fclose($siteconfig_file);
    // for the database version, get rid of any appendices ('sr1' etc.)
    $version = VERSION;
    $v = explode('.', VERSION);
    if (count($v) == 3) {
        $v[2] = (int) $v[2];
        $version = implode('.', $v);
    }
    $version = DB_escapeString($version);
    DB_change($_TABLES['vars'], 'value', $version, 'name', 'database_version');
}
Example #23
0
    exit;
}
$sql = "SELECT * FROM {$_TABLES['mg_media']} WHERE media_id='" . addslashes($mid) . "'";
$result = DB_query($sql);
while ($A = DB_fetchArray($result)) {
    $filename = $A['media_original_filename'];
    if (empty($filename)) {
        $filename = $A['media_filename'] . '.' . $A['media_mime_ext'];
    }
    $mime_type = $A['mime_type'];
    if ($mime_type == 'application/octet-stream' && strtolower($A['media_mime_ext']) == 'pdf') {
        $mime_type = 'application/pdf';
    }
    if (!SEC_hasRights('mediagallery.admin')) {
        $media_views = $A['media_views'] + 1;
        DB_change($_TABLES['mg_media'], 'media_views', $media_views, 'media_id', addslashes($mid));
    }
    $path = MG_getFilePath('orig', $A['media_filename'], $A['media_mime_ext']);
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
    header("Cache-Control: private", false);
    header("Content-type:" . $mime_type);
    header("Content-Disposition: attachment; filename=\"" . $filename . "\";");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize($path));
    $fp = fopen($path, 'r');
    if ($fp != NULL) {
        while (!feof($fp)) {
            $buf = fgets($fp, 8192);
            echo $buf;
Example #24
0
/**
* Saves the user's information back to the database
*
* @param    array   $A  User's data
* @return   string      HTML error message or meta redirect
*
*/
function saveuser($A)
{
    global $_CONF, $_TABLES, $_USER, $LANG04, $LANG24, $_US_VERBOSE;
    if ($_US_VERBOSE) {
        COM_errorLog('**** Inside saveuser in usersettings.php ****', 1);
    }
    $reqid = DB_getItem($_TABLES['users'], 'pwrequestid', "uid = {$_USER['uid']}");
    if ($reqid != $A['uid']) {
        DB_change($_TABLES['users'], 'pwrequestid', "NULL", 'uid', $_USER['uid']);
        COM_accessLog("An attempt was made to illegally change the account information of user {$_USER['uid']}.");
        return COM_refresh($_CONF['site_url'] . '/index.php');
    }
    if (!isset($A['cooktime'])) {
        // If not set or possibly removed from template - set to default
        $A['cooktime'] = $_CONF['default_perm_cookie_timeout'];
    } else {
        $A['cooktime'] = COM_applyFilter($A['cooktime'], true);
    }
    // If empty or invalid - set to user default
    // So code after this does not fail the user password required test
    if ($A['cooktime'] < 0) {
        // note that == 0 is allowed!
        $A['cooktime'] = $_USER['cookietimeout'];
    }
    // to change the password, email address, or cookie timeout,
    // we need the user's current password
    $current_password = DB_getItem($_TABLES['users'], 'passwd', "uid = {$_USER['uid']}");
    if (!empty($A['passwd']) || $A['email'] != $_USER['email'] || $A['cooktime'] != $_USER['cookietimeout']) {
        if (empty($A['old_passwd']) || SEC_encryptPassword($A['old_passwd']) != $current_password) {
            return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=83');
        } elseif ($_CONF['custom_registration'] && function_exists('CUSTOM_userCheck')) {
            $ret = CUSTOM_userCheck($A['username'], $A['email']);
            if (!empty($ret)) {
                // Need a numeric return for the default message handler
                // - if not numeric use default message
                if (!is_numeric($ret['number'])) {
                    $ret['number'] = 400;
                }
                return COM_refresh("{$_CONF['site_url']}/usersettings.php?msg={$ret['number']}");
            }
        }
    } elseif ($_CONF['custom_registration'] && function_exists('CUSTOM_userCheck')) {
        $ret = CUSTOM_userCheck($A['username'], $A['email']);
        if (!empty($ret)) {
            // Need a numeric return for the default message handler
            // - if not numeric use default message
            if (!is_numeric($ret['number'])) {
                $ret['number'] = 400;
            }
            return COM_refresh("{$_CONF['site_url']}/usersettings.php?msg={$ret['number']}");
        }
    }
    // no need to filter the password as it's encoded anyway
    if ($_CONF['allow_username_change'] == 1) {
        $A['new_username'] = COM_applyFilter($A['new_username']);
        if (!empty($A['new_username']) && $A['new_username'] != $_USER['username']) {
            $A['new_username'] = addslashes($A['new_username']);
            if (DB_count($_TABLES['users'], 'username', $A['new_username']) == 0) {
                if ($_CONF['allow_user_photo'] == 1) {
                    $photo = DB_getItem($_TABLES['users'], 'photo', "uid = {$_USER['uid']}");
                    if (!empty($photo)) {
                        $newphoto = preg_replace('/' . $_USER['username'] . '/', $A['new_username'], $photo, 1);
                        $imgpath = $_CONF['path_images'] . 'userphotos/';
                        if (rename($imgpath . $photo, $imgpath . $newphoto) === false) {
                            $display = COM_siteHeader('menu', $LANG04[21]);
                            $display .= COM_errorLog('Could not rename userphoto "' . $photo . '" to "' . $newphoto . '".');
                            $display .= COM_siteFooter();
                            return $display;
                        }
                        DB_change($_TABLES['users'], 'photo', addslashes($newphoto), "uid", $_USER['uid']);
                    }
                }
                DB_change($_TABLES['users'], 'username', $A['new_username'], "uid", $_USER['uid']);
            } else {
                return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=51');
            }
        }
    }
    // a quick spam check with the unfiltered field contents
    $profile = '<h1>' . $LANG04[1] . ' ' . $_USER['username'] . '</h1>' . '<p>' . COM_createLink($A['homepage'], $A['homepage']) . '<br' . XHTML . '>' . $A['location'] . '<br' . XHTML . '>' . $A['sig'] . '<br' . XHTML . '>' . $A['about'] . '<br' . XHTML . '>' . $A['pgpkey'] . '</p>';
    $result = PLG_checkforSpam($profile, $_CONF['spamx']);
    if ($result > 0) {
        COM_displayMessageAndAbort($result, 'spamx', 403, 'Forbidden');
    }
    $A['email'] = COM_applyFilter($A['email']);
    $A['email_conf'] = COM_applyFilter($A['email_conf']);
    $A['homepage'] = COM_applyFilter($A['homepage']);
    // basic filtering only
    $A['fullname'] = strip_tags(COM_stripslashes($A['fullname']));
    $A['location'] = strip_tags(COM_stripslashes($A['location']));
    $A['sig'] = strip_tags(COM_stripslashes($A['sig']));
    $A['about'] = strip_tags(COM_stripslashes($A['about']));
    $A['pgpkey'] = strip_tags(COM_stripslashes($A['pgpkey']));
    if (!COM_isEmail($A['email'])) {
        return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=52');
    } else {
        if ($A['email'] !== $A['email_conf']) {
            return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=78');
        } else {
            if (emailAddressExists($A['email'], $_USER['uid'])) {
                return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=56');
            } else {
                if (!empty($A['passwd'])) {
                    if ($A['passwd'] == $A['passwd_conf'] && SEC_encryptPassword($A['old_passwd']) == $current_password) {
                        $passwd = SEC_encryptPassword($A['passwd']);
                        DB_change($_TABLES['users'], 'passwd', "{$passwd}", "uid", $_USER['uid']);
                        if ($A['cooktime'] > 0) {
                            $cooktime = $A['cooktime'];
                        } else {
                            $cooktime = -1000;
                        }
                        SEC_setCookie($_CONF['cookie_password'], $passwd, time() + $cooktime);
                    } elseif (SEC_encryptPassword($A['old_passwd']) != $current_password) {
                        return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=68');
                    } elseif ($A['passwd'] != $A['passwd_conf']) {
                        return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=67');
                    }
                }
                if ($_US_VERBOSE) {
                    COM_errorLog('cooktime = ' . $A['cooktime'], 1);
                }
                if ($A['cooktime'] <= 0) {
                    $cooktime = 1000;
                    SEC_setCookie($_CONF['cookie_name'], $_USER['uid'], time() - $cooktime);
                } else {
                    SEC_setCookie($_CONF['cookie_name'], $_USER['uid'], time() + $A['cooktime']);
                }
                if ($_CONF['allow_user_photo'] == 1) {
                    $delete_photo = '';
                    if (isset($A['delete_photo'])) {
                        $delete_photo = $A['delete_photo'];
                    }
                    $filename = handlePhotoUpload($delete_photo);
                }
                if (!empty($A['homepage'])) {
                    $pos = MBYTE_strpos($A['homepage'], ':');
                    if ($pos === false) {
                        $A['homepage'] = 'http://' . $A['homepage'];
                    } else {
                        $prot = substr($A['homepage'], 0, $pos + 1);
                        if ($prot != 'http:' && $prot != 'https:') {
                            $A['homepage'] = 'http:' . substr($A['homepage'], $pos + 1);
                        }
                    }
                    $A['homepage'] = addslashes($A['homepage']);
                }
                $A['fullname'] = addslashes($A['fullname']);
                $A['email'] = addslashes($A['email']);
                $A['location'] = addslashes($A['location']);
                $A['sig'] = addslashes($A['sig']);
                $A['about'] = addslashes($A['about']);
                $A['pgpkey'] = addslashes($A['pgpkey']);
                if (!empty($filename)) {
                    if (!file_exists($_CONF['path_images'] . 'userphotos/' . $filename)) {
                        $filename = '';
                    }
                }
                DB_query("UPDATE {$_TABLES['users']} SET fullname='{$A['fullname']}',email='{$A['email']}',homepage='{$A['homepage']}',sig='{$A['sig']}',cookietimeout={$A['cooktime']},photo='{$filename}' WHERE uid={$_USER['uid']}");
                DB_query("UPDATE {$_TABLES['userinfo']} SET pgpkey='{$A['pgpkey']}',about='{$A['about']}',location='{$A['location']}' WHERE uid={$_USER['uid']}");
                // Call custom registration save function if enabled and exists
                if ($_CONF['custom_registration'] and function_exists('CUSTOM_userSave')) {
                    CUSTOM_userSave($_USER['uid']);
                }
                PLG_userInfoChanged($_USER['uid']);
                if ($_US_VERBOSE) {
                    COM_errorLog('**** Leaving saveuser in usersettings.php ****', 1);
                }
                return COM_refresh($_CONF['site_url'] . '/users.php?mode=profile&amp;uid=' . $_USER['uid'] . '&amp;msg=5');
            }
        }
    }
}
Example #25
0
function MG_mediaResetViews($album_id, $media_id, $mqueue)
{
    global $_MG_CONF, $_TABLES;
    DB_change($_TABLES['mg_media'], 'media_views', 0, 'media_id', addslashes($media_id));
    $retval = MG_mediaEdit($album_id, $media_id, $_MG_CONF['site_url'] . '/admin.php?mode=media&amp;album_id=' . $album_id, $mqueue);
    return $retval;
}
Example #26
0
            $T->parse('uRow', 'UserRow', true);
            $rowcounter++;
            $counter++;
        }
    }
    $T->set_var(array('site_admin_url' => $_MG_CONF['admin_url'], 'used' => $usedquery, 'quota' => $quotaquery, 'lang_go' => $LANG_MG03['go'], 'lang_quota' => $LANG_MG01['quota'], 'lang_used' => $LANG_MG01['used'], 'lang_batch_update' => $LANG_MG01['batch_quota_update'], 'lang_update' => $LANG_MG01['update'], 'pagenav' => COM_printPageNavigation($_MG_CONF['admin_url'] . 'quotareport.php', $page + 1, ceil($total_records / 50))));
    $retval .= $T->finish($T->parse('output', 'report'));
    return $retval;
}
if (isset($_POST['mode'])) {
    $mode = COM_applyFilter($_POST['mode']);
    $bquota = COM_applyFilter($_POST['bquota'], true);
    $bquota = $bquota * 1048576;
    $numItems = count($_POST['uid']);
    for ($i = 0; $i < $numItems; $i++) {
        DB_change($_TABLES['mg_userprefs'], 'quota', $bquota, 'uid', $_POST['uid'][$i]);
        if (DB_error()) {
            $sql = "INSERT INTO {$_TABLES['mg_userprefs']} (uid, active, display_rows, display_columns, mp3_player, playback_mode, tn_size, quota, member_gallery) " . "VALUES (" . $uid . ",1,0,0,-1,-1,-1," . $bquota . ",0)";
            DB_query($sql, 1);
        }
    }
}
$page = isset($_GET['page']) ? COM_applyFilter($_GET['page'], true) : 0;
if ($page <= 0) {
    $page = 0;
} else {
    $page--;
}
$quota = isset($_POST['quota']) ? COM_applyFilter($_POST['quota'], true) : 0;
$used = isset($_POST['used']) ? COM_applyFilter($_POST['used'], true) : 0;
$T = new Template($_MG_CONF['template_path']);
Example #27
0
/**
 * Submit static page. The page is updated if it exists, or a new one is created
 *
 * @param   array   args     Contains all the data provided by the client
 * @param   string  &output  OUTPUT parameter containing the returned text
 * @param   string  &svc_msg OUTPUT parameter containing any service messages
 * @return  int		     Response code as defined in lib-plugins.php
 */
function service_submit_staticpages($args, &$output, &$svc_msg)
{
    global $_CONF, $_TABLES, $_USER, $LANG_ACCESS, $LANG12, $LANG_STATIC, $LANG_LOGIN, $_GROUPS, $_SP_CONF;
    $output = '';
    if (!SEC_hasRights('staticpages.edit')) {
        $output = COM_siteHeader('menu', $LANG_STATIC['access_denied']);
        $output .= COM_showMessageText($LANG_STATIC['access_denied_msg'], $LANG_STATIC['access_denied'], true);
        $output .= COM_siteFooter();
        return PLG_RET_AUTH_FAILED;
    }
    if (defined('DEMO_MODE')) {
        $output = COM_siteHeader('menu');
        $output .= COM_showMessageText('Option disabled in Demo Mode', 'Option disabled in Demo Mode', true);
        $output .= COM_siteFooter();
        return PLG_REG_AUTH_FAILED;
    }
    $gl_edit = false;
    if (isset($args['gl_edit'])) {
        $gl_edit = $args['gl_edit'];
    }
    if ($gl_edit) {
        // This is EDIT mode, so there should be an sp_old_id
        if (empty($args['sp_old_id'])) {
            if (!empty($args['id'])) {
                $args['sp_old_id'] = $args['id'];
            } else {
                return PLG_RET_ERROR;
            }
            if (empty($args['sp_id'])) {
                $args['sp_id'] = $args['sp_old_id'];
            }
        }
    } else {
        if (empty($args['sp_id']) && !empty($args['id'])) {
            $args['sp_id'] = $args['id'];
        }
    }
    if (empty($args['sp_uid'])) {
        $args['sp_uid'] = $_USER['uid'];
    }
    if (empty($args['sp_title']) && !empty($args['title'])) {
        $args['sp_title'] = $args['title'];
    }
    if (empty($args['sp_content']) && !empty($args['content'])) {
        $args['sp_content'] = $args['content'];
    }
    if (isset($args['category']) && is_array($args['category']) && !empty($args['category'][0])) {
        $args['sp_tid'] = $args['category'][0];
    }
    if (!isset($args['owner_id'])) {
        $args['owner_id'] = $_USER['uid'];
    }
    if (empty($args['group_id'])) {
        $args['group_id'] = SEC_getFeatureGroup('staticpages.edit', $_USER['uid']);
    }
    $args['sp_id'] = COM_sanitizeID($args['sp_id']);
    if (!$gl_edit) {
        if (strlen($args['sp_id']) > STATICPAGE_MAX_ID_LENGTH) {
            if (function_exists('WS_makeId')) {
                $args['sp_id'] = WS_makeId($slug, STATICPAGE_MAX_ID_LENGTH);
            } else {
                $args['sp_id'] = COM_makeSid();
            }
        }
    }
    // Apply filters to the parameters passed by the webservice
    if ($args['gl_svc']) {
        $par_str = array('mode', 'sp_id', 'sp_old_id', 'sp_tid', 'sp_format', 'postmode');
        $par_num = array('sp_uid', 'sp_hits', 'owner_id', 'group_id', 'sp_where', 'sp_php', 'commentcode', 'sp_search', 'sp_status');
        foreach ($par_str as $str) {
            if (isset($args[$str])) {
                $args[$str] = COM_applyBasicFilter($args[$str]);
            } else {
                $args[$str] = '';
            }
        }
        foreach ($par_num as $num) {
            if (isset($args[$num])) {
                $args[$num] = COM_applyBasicFilter($args[$num], true);
            } else {
                $args[$num] = 0;
            }
        }
    }
    // START: Staticpages defaults
    if ($args['sp_status'] != 1) {
        $args['sp_status'] = 0;
    }
    if (empty($args['sp_format'])) {
        $args['sp_format'] = 'allblocks';
    }
    if (empty($args['sp_tid'])) {
        $args['sp_tid'] = 'all';
    }
    if ($args['sp_where'] < 0 || $args['sp_where'] > 4) {
        $args['sp_where'] = 0;
    }
    if ($args['sp_php'] < 0 || $args['sp_php'] > 2) {
        $args['sp_php'] = 0;
    }
    if ($args['commentcode'] < -1 || $args['commentcode'] > 1) {
        $args['commentcode'] = $_CONF['comment_code'];
    }
    if ($args['sp_search'] != 1) {
        $args['sp_search'] = 0;
    }
    if ($args['gl_svc']) {
        // Permissions
        if (!isset($args['perm_owner'])) {
            $args['perm_owner'] = $_SP_CONF['default_permissions'][0];
        } else {
            $args['perm_owner'] = COM_applyBasicFilter($args['perm_owner'], true);
        }
        if (!isset($args['perm_group'])) {
            $args['perm_group'] = $_SP_CONF['default_permissions'][1];
        } else {
            $args['perm_group'] = COM_applyBasicFilter($args['perm_group'], true);
        }
        if (!isset($args['perm_members'])) {
            $args['perm_members'] = $_SP_CONF['default_permissions'][2];
        } else {
            $args['perm_members'] = COM_applyBasicFilter($args['perm_members'], true);
        }
        if (!isset($args['perm_anon'])) {
            $args['perm_anon'] = $_SP_CONF['default_permissions'][3];
        } else {
            $args['perm_anon'] = COM_applyBasicFilter($args['perm_anon'], true);
        }
        if (!isset($args['sp_onmenu'])) {
            $args['sp_onmenu'] = '';
        } else {
            if ($args['sp_onmenu'] == 'on' && empty($args['sp_label'])) {
                $svc_msg['error_desc'] = 'Menu label missing';
                return PLG_RET_ERROR;
            }
        }
        if (empty($args['sp_content'])) {
            $svc_msg['error_desc'] = 'No content';
            return PLG_RET_ERROR;
        }
        if (empty($args['sp_inblock']) && $_SP_CONF['in_block'] == '1') {
            $args['sp_inblock'] = 'on';
        }
        if (empty($args['sp_centerblock'])) {
            $args['sp_centerblock'] = '';
        }
    }
    // END: Staticpages defaults
    $sp_id = $args['sp_id'];
    $sp_status = $args['sp_status'];
    $sp_uid = $args['sp_uid'];
    $sp_title = $args['sp_title'];
    $sp_content = $args['sp_content'];
    $sp_hits = $args['sp_hits'];
    $sp_format = $args['sp_format'];
    $sp_onmenu = $args['sp_onmenu'];
    $sp_label = '';
    if (!empty($args['sp_label'])) {
        $sp_label = $args['sp_label'];
    }
    $commentcode = $args['commentcode'];
    $owner_id = $args['owner_id'];
    $group_id = $args['group_id'];
    $perm_owner = $args['perm_owner'];
    $perm_group = $args['perm_group'];
    $perm_members = $args['perm_members'];
    $perm_anon = $args['perm_anon'];
    $sp_php = $args['sp_php'];
    $sp_nf = '';
    if (!empty($args['sp_nf'])) {
        $sp_nf = $args['sp_nf'];
    }
    $sp_old_id = $args['sp_old_id'];
    $sp_centerblock = $args['sp_centerblock'];
    $sp_help = '';
    if (!empty($args['sp_help'])) {
        $sp_help = $args['sp_help'];
    }
    $sp_tid = $args['sp_tid'];
    $sp_where = $args['sp_where'];
    $sp_inblock = $args['sp_inblock'];
    $postmode = $args['postmode'];
    $sp_search = $args['sp_search'];
    if ($gl_edit && !empty($args['gl_etag'])) {
        // First load the original staticpage to check if it has been modified
        $o = array();
        $s = array();
        $r = service_get_staticpages(array('sp_id' => $sp_old_id, 'gl_svc' => true), $o, $s);
        if ($r == PLG_RET_OK) {
            if ($args['gl_etag'] != $o['updated']) {
                $svc_msg['error_desc'] = 'A more recent version of the staticpage is available';
                return PLG_RET_PRECONDITION_FAILED;
            }
        } else {
            $svc_msg['error_desc'] = 'The requested staticpage no longer exists';
            return PLG_RET_ERROR;
        }
    }
    // Check for unique page ID
    $duplicate_id = false;
    $delete_old_page = false;
    if (DB_count($_TABLES['staticpage'], 'sp_id', $sp_id) > 0) {
        if ($sp_id != $sp_old_id) {
            $duplicate_id = true;
        }
    } elseif (!empty($sp_old_id)) {
        if ($sp_id != $sp_old_id) {
            $delete_old_page = true;
        }
    }
    if ($duplicate_id) {
        $output .= COM_siteHeader('menu', $LANG_STATIC['staticpageeditor']);
        $output .= COM_errorLog($LANG_STATIC['duplicate_id'], 2);
        if (!$args['gl_svc']) {
            $output .= PAGE_edit($sp_id);
        }
        $output .= COM_siteFooter();
        $svc_msg['error_desc'] = 'Duplicate ID';
        return PLG_RET_ERROR;
    } elseif (!empty($sp_title) && !empty($sp_content)) {
        if (empty($sp_hits)) {
            $sp_hits = 0;
        }
        if ($sp_onmenu == 'on') {
            $sp_onmenu = 1;
        } else {
            $sp_onmenu = 0;
        }
        if ($sp_nf == 'on') {
            $sp_nf = 1;
        } else {
            $sp_nf = 0;
        }
        if ($sp_centerblock == 'on') {
            $sp_centerblock = 1;
        } else {
            $sp_centerblock = 0;
        }
        if ($sp_inblock == 'on') {
            $sp_inblock = 1;
        } else {
            $sp_inblock = 0;
        }
        // Clean up the text
        if ($_SP_CONF['censor'] == 1) {
            $sp_content = COM_checkWords($sp_content);
            $sp_title = COM_checkWords($sp_title);
        }
        if ($_SP_CONF['filter_html'] == 1) {
            $sp_content = COM_checkHTML($sp_content, 'staticpages.edit');
        }
        $sp_title = strip_tags($sp_title);
        $sp_label = strip_tags($sp_label);
        $sp_content = DB_escapeString($sp_content);
        $sp_title = DB_escapeString($sp_title);
        $sp_label = DB_escapeString($sp_label);
        // If user does not have php edit perms, then set php flag to 0.
        if ($_SP_CONF['allow_php'] != 1 || !SEC_hasRights('staticpages.PHP')) {
            $sp_php = 0;
        }
        // make sure there's only one "entire page" static page per topic
        if ($sp_centerblock == 1 && $sp_where == 0) {
            $sql = "UPDATE {$_TABLES['staticpage']} SET sp_centerblock = 0 WHERE sp_centerblock = 1 AND sp_where = 0 AND sp_tid = '" . DB_escapeString($sp_tid) . "'";
            // multi-language configuration - allow one entire page
            // centerblock for all or none per language
            if (!empty($_CONF['languages']) && !empty($_CONF['language_files']) && ($sp_tid == 'all' || $sp_tid == 'none')) {
                $ids = explode('_', $sp_id);
                if (count($ids) > 1) {
                    $lang_id = array_pop($ids);
                    $sql .= " AND sp_id LIKE '%\\_" . DB_escapeString($lang_id) . "'";
                }
            }
            DB_query($sql);
        }
        $formats = array('allblocks', 'blankpage', 'leftblocks', 'rightblocks', 'noblocks');
        if (!in_array($sp_format, $formats)) {
            $sp_format = 'allblocks';
        }
        if (!$args['gl_svc']) {
            list($perm_owner, $perm_group, $perm_members, $perm_anon) = SEC_getPermissionValues($perm_owner, $perm_group, $perm_members, $perm_anon);
        }
        DB_save($_TABLES['staticpage'], 'sp_id,sp_status,sp_uid,sp_title,sp_content,sp_date,sp_hits,sp_format,sp_onmenu,sp_label,commentcode,owner_id,group_id,' . 'perm_owner,perm_group,perm_members,perm_anon,sp_php,sp_nf,sp_centerblock,sp_help,sp_tid,sp_where,sp_inblock,postmode,sp_search', "'{$sp_id}',{$sp_status}, {$sp_uid},'{$sp_title}','{$sp_content}',NOW(),{$sp_hits},'{$sp_format}',{$sp_onmenu},'{$sp_label}','{$commentcode}',{$owner_id},{$group_id}," . "{$perm_owner},{$perm_group},{$perm_members},{$perm_anon},'{$sp_php}','{$sp_nf}',{$sp_centerblock},'{$sp_help}','{$sp_tid}',{$sp_where}," . "'{$sp_inblock}','{$postmode}',{$sp_search}");
        if ($delete_old_page && !empty($sp_old_id)) {
            DB_delete($_TABLES['staticpage'], 'sp_id', $sp_old_id);
            DB_change($_TABLES['comments'], 'sid', DB_escapeString($sp_id), array('sid', 'type'), array(DB_escapeString($sp_old_id), 'staticpages'));
            PLG_itemDeleted($sp_old_id, 'staticpages');
        }
        PLG_itemSaved($sp_id, 'staticpages');
        $url = COM_buildURL($_CONF['site_url'] . '/page.php?page=' . $sp_id);
        $output .= PLG_afterSaveSwitch($_SP_CONF['aftersave'], $url, 'staticpages');
        $svc_msg['id'] = $sp_id;
        return PLG_RET_OK;
    } else {
        $output .= COM_siteHeader('menu', $LANG_STATIC['staticpageeditor']);
        $output .= COM_errorLog($LANG_STATIC['no_title_or_content'], 2);
        if (!$args['gl_svc']) {
            $output .= PAGE_edit($sp_id);
        }
        $output .= COM_siteFooter();
        return PLG_RET_ERROR;
    }
}
Example #28
0
/**
 * article: delete a comment
 *
 * @param   int    $cid Comment to be deleted
 * @param   string $id  Item id to which $cid belongs
 * @return  mixed   false for failure, HTML string (redirect?) for success
 */
function plugin_deletecomment_article($cid, $id)
{
    global $_CONF, $_TABLES, $_USER;
    $retval = '';
    $has_editPermissions = SEC_hasRights('story.edit');
    $result = DB_query("SELECT owner_id,group_id,perm_owner,perm_group,perm_members,perm_anon " . "FROM {$_TABLES['stories']} WHERE sid = '{$id}'");
    $A = DB_fetchArray($result);
    if ($has_editPermissions && SEC_hasAccess($A['owner_id'], $A['group_id'], $A['perm_owner'], $A['perm_group'], $A['perm_members'], $A['perm_anon']) == 3) {
        CMT_deleteComment($cid, $id, 'article');
        $comments = DB_count($_TABLES['comments'], 'sid', $id);
        DB_change($_TABLES['stories'], 'comments', $comments, 'sid', $id);
        // Comment count in Older Stories block may have changed so delete cache
        $cacheInstance = 'olderstories__';
        // remove all olderstories instances
        CACHE_remove_instance($cacheInstance);
        COM_redirect(COM_buildUrl($_CONF['site_url'] . "/article.php?story={$id}") . '#comments');
    } else {
        COM_errorLog("User {$_USER['username']} (IP: {$_SERVER['REMOTE_ADDR']}) " . "tried to illegally delete comment {$cid} from {$id}");
        COM_redirect($_CONF['site_url'] . '/index.php');
    }
    return $retval;
}
Example #29
0
 /**
  * Set Geeklog version number in siteconfig.php and in the database
  *
  * @param   string $siteConfigFilePath path to siteconfig.php
  */
 private function setVersion($siteConfigFilePath)
 {
     global $_TABLES;
     $siteConfigData = @file_get_contents($siteConfigFilePath);
     $siteConfigData = preg_replace('/define\\s*\\(\'VERSION\',[^;]*;/', "define('VERSION', '" . self::GL_VERSION . "');", $siteConfigData);
     if (@file_put_contents($siteConfigFilePath, $siteConfigData) === false) {
         exit($this->LANG['INSTALL'][26] . ' ' . $this->LANG['INSTALL'][28]);
     }
     // for the database version, get rid of any appendices ('sr1' etc.)
     $version = self::GL_VERSION;
     $v = explode('.', self::GL_VERSION);
     if (count($v) === 3) {
         $v[2] = (int) $v[2];
         $version = implode('.', $v);
     }
     $version = DB_escapeString($version);
     DB_change($_TABLES['vars'], 'value', $version, 'name', 'database_version');
 }
Example #30
0
/**
* Saves a poll
*
* Saves a poll topic and potential answers to the database
*
* @param    string  $pid            Poll topic ID
* @param    string  $old_pid        Previous poll topic ID
* @param    array   $Q              Array of poll questions
* @param    string  $mainpage       Checkbox: poll appears on homepage
* @param    string  $topic          The text for the topic
* @param    string  $meta_description
* @param    string  $meta_keywords
* @param    int     $statuscode     (unused)
* @param    string  $open           Checkbox: poll open for voting
* @param    string  $hideresults    Checkbox: hide results until closed
* @param    int     $commentcode    Indicates if users can comment on poll
* @param    array   $A              Array of possible answers
* @param    array   $V              Array of vote per each answer
* @param    array   $R              Array of remark per each answer
* @param    int     $owner_id       ID of poll owner
* @param    int     $group_id       ID of group poll belongs to
* @param    int     $perm_owner     Permissions the owner has on poll
* @param    int     $perm_grup      Permissions the group has on poll
* @param    int     $perm_members   Permissions logged in members have on poll
* @param    int     $perm_anon      Permissions anonymous users have on poll
* @return   string                  HTML redirect or error message
*
*/
function savepoll($pid, $old_pid, $Q, $mainpage, $topic, $meta_description, $meta_keywords, $statuscode, $open, $hideresults, $commentcode, $A, $V, $R, $owner_id, $group_id, $perm_owner, $perm_group, $perm_members, $perm_anon)
{
    global $_CONF, $_TABLES, $_USER, $LANG21, $LANG25, $MESSAGE, $_POLL_VERBOSE, $_PO_CONF;
    $retval = '';
    // Convert array values to numeric permission values
    list($perm_owner, $perm_group, $perm_members, $perm_anon) = SEC_getPermissionValues($perm_owner, $perm_group, $perm_members, $perm_anon);
    $topic = COM_stripslashes($topic);
    $meta_description = strip_tags(COM_stripslashes($meta_description));
    $meta_keywords = strip_tags(COM_stripslashes($meta_keywords));
    $pid = COM_sanitizeID($pid);
    $old_pid = COM_sanitizeID($old_pid);
    if (empty($pid)) {
        if (empty($old_pid)) {
            $pid = COM_makeSid();
        } else {
            $pid = $old_pid;
        }
    }
    // check if any question was entered
    if (empty($topic) or count($Q) == 0 or strlen($Q[0]) == 0 or strlen($A[0][0]) == 0) {
        $retval .= COM_siteHeader('menu', $LANG25[5]);
        $retval .= COM_startBlock($LANG21[32], '', COM_getBlockTemplate('_msg_block', 'header'));
        $retval .= $LANG25[2];
        $retval .= COM_endBlock(COM_getBlockTemplate('_msg_block', 'footer'));
        $retval .= COM_siteFooter();
        return $retval;
    }
    if (!SEC_checkToken()) {
        COM_accessLog("User {$_USER['username']} tried to save poll {$pid} and failed CSRF checks.");
        return COM_refresh($_CONF['site_admin_url'] . '/plugins/polls/index.php');
    }
    // check for poll id change
    if (!empty($old_pid) && $pid != $old_pid) {
        // check if new pid is already in use
        if (DB_count($_TABLES['polltopics'], 'pid', $pid) > 0) {
            // TBD: abort, display editor with all content intact again
            $pid = $old_pid;
            // for now ...
        }
    }
    // start processing the poll topic
    if ($_POLL_VERBOSE) {
        COM_errorLog('**** Inside savepoll() in ' . $_CONF['site_admin_url'] . '/plugins/polls/index.php ***');
    }
    $access = 0;
    if (DB_count($_TABLES['polltopics'], 'pid', $pid) > 0) {
        $result = DB_query("SELECT owner_id,group_id,perm_owner,perm_group,perm_members,perm_anon FROM {$_TABLES['polltopics']} WHERE pid = '{$pid}'");
        $P = DB_fetchArray($result);
        $access = SEC_hasAccess($P['owner_id'], $P['group_id'], $P['perm_owner'], $P['perm_group'], $P['perm_members'], $P['perm_anon']);
    } else {
        $access = SEC_hasAccess($owner_id, $group_id, $perm_owner, $perm_group, $perm_members, $perm_anon);
    }
    if ($access < 3 || !SEC_inGroup($group_id)) {
        $display .= COM_siteHeader('menu', $MESSAGE[30]) . COM_showMessageText($MESSAGE[29], $MESSAGE[30]) . COM_siteFooter();
        COM_accessLog("User {$_USER['username']} tried to illegally submit or edit poll {$pid}.");
        COM_output($display);
        exit;
    }
    if (empty($voters)) {
        $voters = 0;
    }
    if ($_POLL_VERBOSE) {
        COM_errorLog('owner permissions: ' . $perm_owner, 1);
        COM_errorLog('group permissions: ' . $perm_group, 1);
        COM_errorLog('member permissions: ' . $perm_members, 1);
        COM_errorLog('anonymous permissions: ' . $perm_anon, 1);
    }
    // we delete everything and re-create it with the input from the form
    $del_pid = $pid;
    if (!empty($old_pid) && $pid != $old_pid) {
        $del_pid = $old_pid;
        // delete by old pid, create using new pid below
    }
    DB_delete($_TABLES['polltopics'], 'pid', $del_pid);
    DB_delete($_TABLES['pollanswers'], 'pid', $del_pid);
    DB_delete($_TABLES['pollquestions'], 'pid', $del_pid);
    $topic = addslashes($topic);
    $meta_description = addslashes($meta_description);
    $meta_keywords = addslashes($meta_keywords);
    $k = 0;
    // set up a counter to make sure we do assign a straight line of question id's
    $v = 0;
    // re-count votes sine they might have been changed
    // first dimension of array are the questions
    $num_questions = count($Q);
    for ($i = 0; $i < $num_questions; $i++) {
        $Q[$i] = COM_stripslashes($Q[$i]);
        if (strlen($Q[$i]) > 0) {
            // only insert questions that exist
            $Q[$i] = addslashes($Q[$i]);
            DB_save($_TABLES['pollquestions'], 'qid, pid, question', "'{$k}', '{$pid}', '{$Q[$i]}'");
            // within the questions, we have another dimensions with answers,
            // votes and remarks
            $num_answers = count($A[$i]);
            for ($j = 0; $j < $num_answers; $j++) {
                $A[$i][$j] = COM_stripslashes($A[$i][$j]);
                if (strlen($A[$i][$j]) > 0) {
                    // only insert answers etc that exist
                    if (!is_numeric($V[$i][$j])) {
                        $V[$i][$j] = "0";
                    }
                    $A[$i][$j] = addslashes($A[$i][$j]);
                    $R[$i][$j] = addslashes($R[$i][$j]);
                    $sql = "INSERT INTO {$_TABLES['pollanswers']} (pid, qid, aid, answer, votes, remark) VALUES " . "('{$pid}', '{$k}', " . ($j + 1) . ", '{$A[$i][$j]}', {$V[$i][$j]}, '{$R[$i][$j]}');";
                    DB_query($sql);
                    $v = $v + $V[$i][$j];
                }
            }
            $k++;
        }
    }
    // save topics after the questions so we can include question count into table
    $sql = "'{$pid}','{$topic}','{$meta_description}','{$meta_keywords}',{$v}, {$k}, '" . date('Y-m-d H:i:s');
    if ($mainpage == 'on') {
        $sql .= "',1";
    } else {
        $sql .= "',0";
    }
    if ($open == 'on') {
        $sql .= ",1";
    } else {
        $sql .= ",0";
    }
    if ($hideresults == 'on') {
        $sql .= ",1";
    } else {
        $sql .= ",0";
    }
    $sql .= ",'{$statuscode}','{$commentcode}',{$owner_id},{$group_id},{$perm_owner},{$perm_group},{$perm_members},{$perm_anon}";
    // Save poll topic
    DB_save($_TABLES['polltopics'], "pid, topic, meta_description, meta_keywords, voters, questions, date, display, is_open, hideresults, statuscode, commentcode, owner_id, group_id, perm_owner, perm_group, perm_members, perm_anon", $sql);
    if (empty($old_pid) || $old_pid == $pid) {
        PLG_itemSaved($pid, 'polls');
    } else {
        DB_change($_TABLES['comments'], 'sid', addslashes($pid), array('sid', 'type'), array(addslashes($old_pid), 'polls'));
        PLG_itemSaved($pid, 'polls', $old_pid);
    }
    if ($_POLL_VERBOSE) {
        COM_errorLog('**** Leaving savepoll() in ' . $_CONF['site_admin_url'] . '/plugins/polls/index.php ***');
    }
    return PLG_afterSaveSwitch($_PO_CONF['aftersave'], $_CONF['site_url'] . '/polls/index.php?pid=' . $pid, 'polls', 19);
    return COM_refresh($_CONF['site_admin_url'] . '/plugins/polls/index.php?msg=19');
}