Example #1
0
/**
 * Submit a new or updated story. The story 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
 * @return  int		    Response code as defined in lib-plugins.php
 */
function service_submit_story($args, &$output, &$svc_msg)
{
    global $_CONF, $_TABLES, $_USER, $LANG24, $MESSAGE, $_GROUPS;
    if (!SEC_hasRights('story.edit')) {
        $output .= COM_showMessageText($MESSAGE[31], $MESSAGE[30], true);
        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 old sid */
        if (empty($args['old_sid'])) {
            if (!empty($args['id'])) {
                $args['old_sid'] = $args['id'];
            } else {
                return PLG_RET_ERROR;
            }
            if (empty($args['sid'])) {
                $args['sid'] = $args['old_sid'];
            }
        }
    } else {
        if (empty($args['sid']) && !empty($args['id'])) {
            $args['sid'] = $args['id'];
        }
    }
    /* Store the first CATEGORY as the Topic ID */
    if (!empty($args['category'][0])) {
        $args['tid'] = $args['category'][0];
    }
    $content = '';
    if (!empty($args['content'])) {
        $content = $args['content'];
    } else {
        if (!empty($args['summary'])) {
            $content = $args['summary'];
        }
    }
    if (!empty($content)) {
        $parts = explode('[page_break]', $content);
        if (count($parts) == 1) {
            $args['introtext'] = $content;
            $args['bodytext'] = '';
        } else {
            $args['introtext'] = array_shift($parts);
            $args['bodytext'] = implode('[page_break]', $parts);
        }
    }
    /* Apply filters to the parameters passed by the webservice */
    if ($args['gl_svc']) {
        if (isset($args['mode'])) {
            $args['mode'] = COM_applyBasicFilter($args['mode']);
        }
        if (isset($args['editopt'])) {
            $args['editopt'] = COM_applyBasicFilter($args['editopt']);
        }
    }
    /* - START: Set all the defaults - */
    if (empty($args['tid'])) {
        // see if we have a default topic
        $topic = DB_getItem($_TABLES['topics'], 'tid', 'is_default = 1' . COM_getPermSQL('AND'));
        if (!empty($topic)) {
            $args['tid'] = $topic;
        } else {
            // otherwise, just use the first one
            $o = array();
            $s = array();
            if (service_getTopicList_story(array('gl_svc' => true), $o, $s) == PLG_RET_OK) {
                $args['tid'] = $o[0];
            } else {
                $svc_msg['error_desc'] = 'No topics available';
                return PLG_RET_ERROR;
            }
        }
    }
    if (empty($args['owner_id'])) {
        $args['owner_id'] = $_USER['uid'];
    }
    if (empty($args['group_id'])) {
        $args['group_id'] = SEC_getFeatureGroup('story.edit', $_USER['uid']);
    }
    if (isset($args['alternate_id']) && $args['tid'] == $args['alternate_id']) {
        $args['alternate_id'] = NULL;
    }
    if (empty($args['postmode'])) {
        $args['postmode'] = $_CONF['postmode'];
        if (!empty($args['content_type'])) {
            if ($args['content_type'] == 'text') {
                $args['postmode'] = 'text';
            } else {
                if ($args['content_type'] == 'html' || $args['content_type'] == 'xhtml') {
                    $args['postmode'] = 'html';
                }
            }
        }
    }
    if ($args['gl_svc']) {
        /* Permissions */
        if (!isset($args['perm_owner'])) {
            $args['perm_owner'] = $_CONF['default_permissions_story'][0];
        } else {
            $args['perm_owner'] = COM_applyBasicFilter($args['perm_owner'], true);
        }
        if (!isset($args['perm_group'])) {
            $args['perm_group'] = $_CONF['default_permissions_story'][1];
        } else {
            $args['perm_group'] = COM_applyBasicFilter($args['perm_group'], true);
        }
        if (!isset($args['perm_members'])) {
            $args['perm_members'] = $_CONF['default_permissions_story'][2];
        } else {
            $args['perm_members'] = COM_applyBasicFilter($args['perm_members'], true);
        }
        if (!isset($args['perm_anon'])) {
            $args['perm_anon'] = $_CONF['default_permissions_story'][3];
        } else {
            $args['perm_anon'] = COM_applyBasicFilter($args['perm_anon'], true);
        }
        if (!isset($args['draft_flag'])) {
            $args['draft_flag'] = $_CONF['draft_flag'];
        }
        if (empty($args['frontpage'])) {
            $args['frontpage'] = $_CONF['frontpage'];
        }
        if (empty($args['show_topic_icon'])) {
            $args['show_topic_icon'] = $_CONF['show_topic_icon'];
        }
    }
    /* - END: Set all the defaults - */
    if (!isset($args['sid'])) {
        $args['sid'] = '';
    }
    $args['sid'] = COM_sanitizeID($args['sid']);
    if (!$gl_edit) {
        if (strlen($args['sid']) > STORY_MAX_ID_LENGTH) {
            $args['sid'] = WS_makeId($args['slug'], STORY_MAX_ID_LENGTH);
        }
    }
    $story = new Story();
    $gl_edit = false;
    if (isset($args['gl_edit'])) {
        $gl_edit = $args['gl_edit'];
    }
    if ($gl_edit && !empty($args['gl_etag'])) {
        /* First load the original story to check if it has been modified */
        $result = $story->loadFromDatabase($args['sid']);
        if ($result == STORY_LOADED_OK) {
            if ($args['gl_etag'] != date('c', $story->_date)) {
                $svc_msg['error_desc'] = 'A more recent version of the story is available';
                return PLG_RET_PRECONDITION_FAILED;
            }
        } else {
            $svc_msg['error_desc'] = 'Error loading story';
            return PLG_RET_ERROR;
        }
    }
    /* This function is also doing the security checks */
    $result = $story->loadFromArgsArray($args);
    $sid = $story->getSid();
    switch ($result) {
        case STORY_DUPLICATE_SID:
            if (!$args['gl_svc']) {
                if (isset($args['type']) && $args['type'] == 'submission') {
                    $output .= STORY_edit($sid, 'moderate');
                } else {
                    $output .= STORY_edit($sid, 'error');
                }
            }
            return PLG_RET_ERROR;
        case STORY_EXISTING_NO_EDIT_PERMISSION:
            $output .= COM_showMessageText($MESSAGE[31], $MESSAGE[30]);
            COM_accessLog("User {$_USER['username']} tried to illegally submit or edit story {$sid}.");
            return PLG_RET_PERMISSION_DENIED;
        case STORY_NO_ACCESS_PARAMS:
            $output .= COM_showMessageText($MESSAGE[31], $MESSAGE[30]);
            COM_accessLog("User {$_USER['username']} tried to illegally submit or edit story {$sid}.");
            return PLG_RET_PERMISSION_DENIED;
        case STORY_EMPTY_REQUIRED_FIELDS:
            if (!$args['gl_svc']) {
                $output .= STORY_edit($sid, 'error');
            }
            return PLG_RET_ERROR;
        default:
            break;
    }
    /* Image upload is not supported by the web-service at present */
    if (!$args['gl_svc']) {
        // Delete any images if needed
        if (array_key_exists('delete', $args)) {
            $delete = count($args['delete']);
            for ($i = 1; $i <= $delete; $i++) {
                $ai_filename = DB_getItem($_TABLES['article_images'], 'ai_filename', "ai_sid = '" . DB_escapeString($sid) . "' AND ai_img_num = " . intval(key($args['delete'])));
                STORY_deleteImage($ai_filename);
                DB_query("DELETE FROM {$_TABLES['article_images']} WHERE ai_sid = '" . DB_escapeString($sid) . "' AND ai_img_num = '" . intval(key($args['delete'])) . "'");
                next($args['delete']);
            }
        }
        // OK, let's upload any pictures with the article
        if (DB_count($_TABLES['article_images'], 'ai_sid', DB_escapeString($sid)) > 0) {
            $index_start = DB_getItem($_TABLES['article_images'], 'max(ai_img_num)', "ai_sid = '" . DB_escapeString($sid) . "'") + 1;
        } else {
            $index_start = 1;
        }
        if (count($_FILES) > 0 and $_CONF['maximagesperarticle'] > 0) {
            require_once $_CONF['path_system'] . 'classes/upload.class.php';
            $upload = new upload();
            if (isset($_CONF['debug_image_upload']) && $_CONF['debug_image_upload']) {
                $upload->setLogFile($_CONF['path'] . 'logs/error.log');
                $upload->setDebug(true);
            }
            $upload->setMaxFileUploads($_CONF['maximagesperarticle']);
            $upload->setAutomaticResize(true);
            if ($_CONF['keep_unscaled_image'] == 1) {
                $upload->keepOriginalImage(true);
            } else {
                $upload->keepOriginalImage(false);
            }
            $upload->setAllowedMimeTypes(array('image/gif' => '.gif', 'image/jpeg' => '.jpg,.jpeg', 'image/pjpeg' => '.jpg,.jpeg', 'image/x-png' => '.png', 'image/png' => '.png'));
            $upload->setFieldName('file');
            //@TODO - better error handling...
            if (!$upload->setPath($_CONF['path_images'] . 'articles')) {
                $output = COM_siteHeader('menu', $LANG24[30]);
                $output .= COM_showMessageText($upload->printErrors(false), $LANG24[30], true);
                $output .= COM_siteFooter();
                echo $output;
                exit;
            }
            // NOTE: if $_CONF['path_to_mogrify'] is set, the call below will
            // force any images bigger than the passed dimensions to be resized.
            // If mogrify is not set, any images larger than these dimensions
            // will get validation errors
            $upload->setMaxDimensions($_CONF['max_image_width'], $_CONF['max_image_height']);
            $upload->setMaxFileSize($_CONF['max_image_size']);
            // size in bytes, 1048576 = 1MB
            // Set file permissions on file after it gets uploaded (number is in octal)
            $upload->setPerms('0644');
            $filenames = array();
            $sql = "SELECT MAX(ai_img_num) + 1 AS ai_img_num FROM " . $_TABLES['article_images'] . " WHERE ai_sid = '" . DB_escapeString($sid) . "'";
            $result = DB_query($sql, 1);
            $row = DB_fetchArray($result);
            $ai_img_num = $row['ai_img_num'];
            if ($ai_img_num < 1) {
                $ai_img_num = 1;
            }
            for ($z = 0; $z < $_CONF['maximagesperarticle']; $z++) {
                $curfile['name'] = '';
                if (isset($_FILES['file']['name'][$z])) {
                    $curfile['name'] = $_FILES['file']['name'][$z];
                }
                if (!empty($curfile['name'])) {
                    $pos = strrpos($curfile['name'], '.') + 1;
                    $fextension = substr($curfile['name'], $pos);
                    $filenames[] = $sid . '_' . $ai_img_num . '.' . $fextension;
                    $ai_img_num++;
                } else {
                    $filenames[] = '';
                }
            }
            $upload->setFileNames($filenames);
            $upload->uploadFiles();
            //@TODO - better error handling
            if ($upload->areErrors()) {
                $retval = COM_siteHeader('menu', $LANG24[30]);
                $retval .= COM_showMessageText($upload->printErrors(false), $LANG24[30], true);
                $retval .= STORY_edit($sid, 'error');
                $retval .= COM_siteFooter();
                echo $retval;
                exit;
            }
            for ($z = 0; $z < $_CONF['maximagesperarticle']; $z++) {
                if ($filenames[$z] != '') {
                    $sql = "SELECT MAX(ai_img_num) + 1 AS ai_img_num FROM " . $_TABLES['article_images'] . " WHERE ai_sid = '" . DB_escapeString($sid) . "'";
                    $result = DB_query($sql, 1);
                    $row = DB_fetchArray($result);
                    $ai_img_num = $row['ai_img_num'];
                    if ($ai_img_num < 1) {
                        $ai_img_num = 1;
                    }
                    DB_query("INSERT INTO {$_TABLES['article_images']} (ai_sid, ai_img_num, ai_filename) VALUES ('" . DB_escapeString($sid) . "', {$ai_img_num}, '" . DB_escapeString($filenames[$z]) . "')");
                }
            }
        }
        if ($_CONF['maximagesperarticle'] > 0) {
            $errors = $story->checkImages();
            if (count($errors) > 0) {
                $output = COM_siteHeader('menu', $LANG24[54]);
                $eMsg = $LANG24[55] . '<p>';
                for ($i = 1; $i <= count($errors); $i++) {
                    $eMsg .= current($errors) . '<br />';
                    next($errors);
                }
                //@TODO - use return here...
                $output .= COM_showMessageText($eMsg, $LANG24[54], true);
                $output .= STORY_edit($sid, 'error');
                $output .= COM_siteFooter();
                echo $output;
                exit;
            }
        }
    }
    $result = $story->saveToDatabase();
    if ($result == STORY_SAVED) {
        // see if any plugins want to act on that story
        if (!empty($args['old_sid']) && $args['old_sid'] != $sid) {
            PLG_itemSaved($sid, 'article', $args['old_sid']);
        } else {
            PLG_itemSaved($sid, 'article');
        }
        // update feed(s) and Older Stories block
        COM_rdfUpToDateCheck('article', $story->DisplayElements('tid'), $sid);
        COM_olderStuff();
        if ($story->type == 'submission') {
            COM_setMessage(9);
            echo COM_refresh($_CONF['site_admin_url'] . '/moderation.php');
            exit;
        } else {
            $output = PLG_afterSaveSwitch($_CONF['aftersave_story'], COM_buildURL("{$_CONF['site_url']}/article.php?story={$sid}"), 'story', 9);
        }
        /* @TODO Set the object id here */
        $svc_msg['id'] = $sid;
        return PLG_RET_OK;
    }
}