/**
*   Insert or update an ad with form values.  Setting $admin to true
*   allows ads to be saved on behalf of another user.
*
*   @param string  $savetype Save action to perform
*   @return array
*      [0] = string value of page to redirect to
*      [1] = content of any error message or text
*/
function adSave($savetype = 'edit')
{
    global $_TABLES, $_CONF_ADVT, $_USER, $_CONF, $LANG_ADVT, $LANG12;
    global $LANG_ADMIN;
    $admin = SEC_hasRights($_CONF_ADVT['pi_name'] . '.admin');
    // Sanitize form variables.  There should always be an ad id defined
    $A = array();
    if (isset($_POST['ad_id'])) {
        $A['ad_id'] = COM_sanitizeID($_POST['ad_id'], false);
    } elseif (isset($_POST['id'])) {
        $A['ad_id'] = COM_sanitizeID($_POST['id'], false);
    }
    if ($A['ad_id'] == '') {
        return array(CLASSIFIEDS_URL, 'Missing Ad ID');
    }
    // Make sure the current user can edit this ad.
    if (CLASSIFIEDS_checkAccess($A['ad_id']) < 3) {
        return array();
    }
    $A['subject'] = trim($_POST['subject']);
    $A['descript'] = trim($_POST['descript']);
    if ($_POST['postmode'] == 'plaintext') {
        $A['descript'] = nl2br($A['descript']);
    }
    $A['price'] = trim($_POST['price']);
    $A['url'] = COM_sanitizeUrl($_POST['url'], array('http', 'https'), 'http');
    $A['catid'] = (int) $_POST['catid'];
    $A['ad_type'] = (int) $_POST['ad_type'];
    $A['keywords'] = trim($_POST['keywords']);
    $A['add_date'] = COM_applyFilter($_POST['add_date'], true);
    $A['exp_date'] = COM_applyFilter($_POST['exp_date'], true);
    if ($A['exp_date'] == 0) {
        $A['exp_date'] = $A['add_date'];
    }
    $A['exp_sent'] = (int) $_POST['exp_sent'] == 1 ? 1 : 0;
    $A['owner_id'] = (int) $_POST['owner_id'];
    $A['group_id'] = (int) $_POST['group_id'];
    $A['uid'] = $A['owner_id'];
    $A['comments_enabled'] = (int) $_POST['comments_enabled'];
    switch ($savetype) {
        case 'moderate':
        case 'adminupdate':
        case 'savesubmission':
        case 'editsubmission':
        case 'submission':
            $perms = SEC_getPermissionValues($_POST['perm_owner'], $_POST['perm_group'], $_POST['perm_members'], $_POST['perm_anon']);
            $A['perms'] = $perms;
            break;
        case $LANG_ADMIN['save']:
        case $LANG12[8]:
        default:
            $A['perms'] = array((int) $_POST['perm_owner'], (int) $_POST['perm_group'], (int) $_POST['perm_members'], (int) $_POST['perm_anon']);
            break;
    }
    // Set anon permissions according to category if not an admin.
    // To avoid form injection.
    if (!$admin && DB_getItem($_TABLES['ad_category'], 'perm_anon', "cat_id='{$A['cat_id']}'") == '0') {
        $A['perms'][3] = 0;
    }
    $photo = $_FILES['photo'];
    $moredays = COM_applyFilter($_POST['moredays'], true);
    if ($_CONF_ADVT['purchase_enabled'] && !$admin) {
        // non-administrator is limited to the available days on account,
        // if applicable.
        USES_classifieds_class_userinfo();
        $User = new adUserInfo();
        $moredays = min($moredays, $User->getMaxDays());
    }
    // Validate some fields.
    $errmsg = '';
    if ($A['subject'] == '') {
        $errmsg .= "<li>{$LANG_ADVT['subject_required']}</li>";
    }
    if ($A['descript'] == '') {
        $errmsg .= "<li>{$LANG_ADVT['description_required']}</li>";
    }
    if ($errmsg != '') {
        $errmsg = "<span class=\"alert\"><ul>{$errmsg}</ul></span>\n";
        // return to edit page so user can correct
        return array(1, $errmsg);
        //return $errmsg;
    }
    // Calculate the new number of days. For an existing ad start from the
    // date added, if new then start from now.  If the ad has already expired,
    // then $moredays will be added to now() rather than exp_date.
    if ($moredays > 0) {
        $moretime = $moredays * 86400;
        $save_exp_date = $A['exp_date'];
        if ($A['exp_date'] < time()) {
            $basetime = time();
        } else {
            $basetime = $A['exp_date'];
        }
        $A['exp_date'] = min($basetime + $moretime, $A['add_date'] + intval($_CONF_ADVT['max_total_duration']) * 86400);
        // Figure out the number of days added to this ad, and subtract
        // it from the user's account.
        $days_used = (int) (($A['exp_date'] - $save_exp_date) / 86400);
        if ($_CONF_ADVT['purchase_enabled'] && !$admin) {
            $User->UpdateDaysBalance($days_used * -1);
        }
        // Reset the "expiration notice sent" flag if the new date is at least
        // one more day from the old one.
        //if ($A['exp_date'] - $save_exp_date >= 86400) {
        if ($days_used > 0) {
            $A['exp_sent'] = 0;
        }
    }
    $errmsg .= CLASSIFIEDS_UploadPhoto($A['ad_id'], 'photo');
    if ($errmsg != '') {
        // Display the real error message, if there is one
        return array(1, "<span class=\"alert\"><ul>{$errmsg}</ul></span>\n");
        //return "<span class=\"alert\"><ul>$errmsg</ul></span>\n";
    }
    if (($savetype == 'moderate' || $savetype == 'editsubmission' || $savetype == 'submission') && plugin_ismoderator_classifieds()) {
        // If we're editing a submission, delete the submission item
        // after moving data to the main table
        $status = CLASSIFIEDS_insertAd($A, 'ad_ads');
        if ($status == NULL) {
            DB_delete($_TABLES['ad_submission'], 'ad_id', $A['ad_id']);
        } else {
            $errmsg = $status;
        }
        // Now we've duplicated most functions of the moderator approval,
        // so call the plugin_ function to do the same post-approval stuff
        plugin_moderationapprove_classifieds($A['ad_id'], $A['owner_id']);
    } elseif (CLASSIFIEDS_checkAccess($A['ad_id']) == 3) {
        CLASSIFIEDS_updateAd($A);
    } else {
        return array(1, "Acess Denied");
    }
    //$errmsg = COM_showMessage('02', $_CONF_ADVT['pi_name']);
    //$errmsg = '';
    if ($errmsg == '') {
        return array(0, '02');
    } else {
        return array(1, $errmsg);
    }
    //return $errmsg;
}