Skip to content

Commit

Permalink
MDL-65978 blog: New WS core_blog_add_entry
Browse files Browse the repository at this point in the history
  • Loading branch information
jleyva committed Feb 29, 2024
1 parent b6b2077 commit 5a679bf
Show file tree
Hide file tree
Showing 5 changed files with 371 additions and 2 deletions.
187 changes: 187 additions & 0 deletions blog/classes/external/add_entry.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

namespace core_blog\external;

use core_external\external_api;
use core_external\external_format_value;
use core_external\external_function_parameters;
use core_external\external_multiple_structure;
use core_external\external_single_structure;
use core_external\external_value;
use core_external\external_warnings;
use context_system;
use context_course;
use context_module;
use moodle_exception;

/**
* This is the external method for adding a blog post entry.
*
* @package core_blog
* @copyright 2024 Juan Leyva <juan@moodle.com>
* @category external
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class add_entry extends external_api {

/**
* Parameters.
*
* @return external_function_parameters
*/
public static function execute_parameters(): external_function_parameters {
return new external_function_parameters([
'subject' => new external_value(PARAM_TEXT, 'Blog subject'),
'summary' => new external_value(PARAM_RAW, 'Blog post content'),
'summaryformat' => new external_format_value('summary'),
'options' => new external_multiple_structure (
new external_single_structure(
[
'name' => new external_value(PARAM_ALPHANUM,
'The allowed keys (value format) are:
inlineattachmentsid (int); the draft file area id for inline attachments. Default to 0.
attachmentsid (int); the draft file area id for attachments. Default to 0.
publishstate (str); the publish state of the entry (draft, site or public). Default to site.
courseassoc (int); the course id to associate the entry with. Default to 0.
modassoc (int); the module id to associate the entry with. Default to 0.
tags (str); the tags to associate the entry with, comma separated. Default to empty.'),
'value' => new external_value(PARAM_RAW, 'the value of the option (validated inside the function)'),
]
), 'Optional settings', VALUE_DEFAULT, []
),
]);
}

/**
* Add the indicated glossary entry.
*
* @param string $subject the glossary subject
* @param string $summary the subject summary
* @param int $summaryformat the subject summary format
* @param array $options additional settings
* @return array with result and warnings
* @throws moodle_exception
*/
public static function execute(string $subject, string $summary, int $summaryformat,
array $options = []): array {

global $DB, $CFG;
require_once($CFG->dirroot . '/blog/lib.php');
require_once($CFG->dirroot . '/blog/locallib.php');

$params = self::validate_parameters(self::execute_parameters(), compact('subject', 'summary',
'summaryformat', 'options'));

if (empty($CFG->enableblogs)) {
throw new moodle_exception('blogdisable', 'blog');
}

$context = context_system::instance();

if (!has_capability('moodle/blog:create', $context)) {
throw new \moodle_exception('cannoteditentryorblog', 'blog');
}

// Prepare the entry object.
$entrydata = new \stdClass();
$entrydata->subject = $params['subject'];
$entrydata->summary_editor = [
'text' => $params['summary'],
'format' => $params['summaryformat'],
];
$entrydata->publishstate = 'site';

// Options.
foreach ($params['options'] as $option) {
$name = trim($option['name']);
switch ($name) {
case 'inlineattachmentsid':
$entrydata->summary_editor['itemid'] = clean_param($option['value'], PARAM_INT);
break;
case 'attachmentsid':
$entrydata->attachment_filemanager = clean_param($option['value'], PARAM_INT);
break;
case 'publishstate':
$entrydata->publishstate = clean_param($option['value'], PARAM_ALPHA);
$applicable = \blog_entry::get_applicable_publish_states();
if (empty($applicable[$entrydata->publishstate])) {
throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
}
break;
case 'courseassoc':
case 'modassoc':
$entrydata->{$name} = clean_param($option['value'], PARAM_INT);
if (!$CFG->useblogassociations) {
throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
}
break;
case 'tags':
$entrydata->tags = clean_param($option['value'], PARAM_TAGLIST);
// Convert to the expected format.
$entrydata->tags = explode(',', $entrydata->tags);
break;
default:
throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
}
}

// Validate course association. We need to convert the course id to context.
if (!empty($entrydata->courseassoc)) {
$coursecontext = context_course::instance($entrydata->courseassoc);
$entrydata->courseid = $entrydata->courseassoc;
$entrydata->courseassoc = $coursecontext->id; // Convert to context.
$context = $coursecontext;
}

// Validate mod association.
if (!empty($entrydata->modassoc)) {
$modcontext = context_module::instance($entrydata->modassoc);
if (!empty($coursecontext) && $coursecontext->id != $modcontext->get_course_context(true)->id) {
throw new moodle_exception('errorinvalidparam', 'webservice', '', 'modassoc');
}
$entrydata->coursemoduleid = $entrydata->modassoc;
$entrydata->modassoc = $modcontext->id; // Convert to context.
$context = $modcontext;
}

// Validate context for where the blog entry is going to be posted.
self::validate_context($context);

[$summaryoptions, $attachmentoptions] = blog_get_editor_options();

$blogentry = new \blog_entry(null, $entrydata, null);
$blogentry->add();
$blogentry->edit((array) $entrydata, null, $summaryoptions, $attachmentoptions);

return [
'entryid' => $blogentry->id,
'warnings' => [],
];
}

/**
* Return.
*
* @return external_single_structure
*/
public static function execute_returns(): external_single_structure {
return new external_single_structure([
'entryid' => new external_value(PARAM_INT, 'The new entry id.'),
'warnings' => new external_warnings(),
]);
}
}
2 changes: 1 addition & 1 deletion blog/edit.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@
$blogheaders = blog_get_headers();

if (!has_capability('moodle/blog:create', $sitecontext) && !has_capability('moodle/blog:manageentries', $sitecontext)) {
throw new \moodle_exception('cannoteditentryorblog');
throw new \moodle_exception('cannoteditentryorblog', 'blog');
}

// Make sure that the person trying to edit has access right.
Expand Down
177 changes: 176 additions & 1 deletion blog/tests/external/external_test.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
global $CFG;
require_once($CFG->dirroot . '/blog/locallib.php');
require_once($CFG->dirroot . '/blog/lib.php');
require_once($CFG->dirroot . '/webservice/tests/helpers.php');

/**
* Unit tests for blog external API.
Expand All @@ -39,7 +40,7 @@
* @copyright 2018 Juan Leyva
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class external_test extends \advanced_testcase {
class external_test extends \externallib_advanced_testcase {

private $courseid;
private $cmid;
Expand Down Expand Up @@ -672,4 +673,178 @@ public function test_get_access_information() {
$this->assertTrue($result['canmanageexternal']);
$this->assertEmpty($result['warnings']);
}

/**
* Test add_entry
*/
public function test_add_entry() {
global $USER;

$this->resetAfterTest(true);

// Add post with attachments.
$this->setAdminUser();

// Draft files.
$draftidinlineattach = file_get_unused_draft_itemid();
$draftidattach = file_get_unused_draft_itemid();
$usercontext = \context_user::instance($USER->id);
$inlinefilename = 'inlineimage.png';
$filerecordinline = [
'contextid' => $usercontext->id,
'component' => 'user',
'filearea' => 'draft',
'itemid' => $draftidinlineattach,
'filepath' => '/',
'filename' => $inlinefilename,
];
$fs = get_file_storage();

// Create a file in a draft area for regular attachments.
$filerecordattach = $filerecordinline;
$attachfilename = 'attachment.txt';
$filerecordattach['filename'] = $attachfilename;
$filerecordattach['itemid'] = $draftidattach;
$fs->create_file_from_string($filerecordinline, 'image contents (not really)');
$fs->create_file_from_string($filerecordattach, 'simple text attachment');

$options = [
[
'name' => 'inlineattachmentsid',
'value' => $draftidinlineattach,
],
[
'name' => 'attachmentsid',
'value' => $draftidattach,
],
[
'name' => 'tags',
'value' => 'tag1, tag2',
],
[
'name' => 'courseassoc',
'value' => $this->courseid,
],
];

$subject = 'First post';
$summary = 'First post summary';
$result = add_entry::execute($subject, $summary, FORMAT_HTML, $options);
$result = external_api::clean_returnvalue(add_entry::execute_returns(), $result);
$postid = $result['entryid'];

// Retrieve files via WS.
$result = \core_blog\external::get_entries();
$result = external_api::clean_returnvalue(\core_blog\external::get_entries_returns(), $result);

foreach ($result['entries'] as $entry) {
if ($entry['id'] == $postid) {
$this->assertEquals($subject, $entry['subject']);
$this->assertEquals($summary, $entry['summary']);
$this->assertEquals($this->courseid, $entry['courseid']);
$this->assertCount(1, $entry['attachmentfiles']);
$this->assertCount(1, $entry['summaryfiles']);
$this->assertCount(2, $entry['tags']);
$this->assertEquals($attachfilename, $entry['attachmentfiles'][0]['filename']);
$this->assertEquals($inlinefilename, $entry['summaryfiles'][0]['filename']);
}
}
}

/**
* Test add_entry when blogs not enabled.
*/
public function test_add_entry_blog_not_enabled() {
global $CFG;

$this->resetAfterTest(true);
$CFG->enableblogs = 0;
$this->setAdminUser();

$this->expectException('\moodle_exception');
$this->expectExceptionMessage(get_string('blogdisable', 'blog'));
add_entry::execute('Subject', 'Summary', FORMAT_HTML);
}

/**
* Test add_entry without permissions.
*/
public function test_add_entry_no_permission() {
global $CFG;

$this->resetAfterTest(true);

// Remove capability.
$sitecontext = \context_system::instance();
$this->unassignUserCapability('moodle/blog:create', $sitecontext->id, $CFG->defaultuserroleid);
$user = $this->getDataGenerator()->create_user();
$this->setuser($user);

$this->expectException('\moodle_exception');
$this->expectExceptionMessage(get_string('cannoteditentryorblog', 'blog'));
add_entry::execute('Subject', 'Summary', FORMAT_HTML);
}

/**
* Test add_entry invalid parameter.
*/
public function test_add_entry_invalid_parameter() {
$this->resetAfterTest(true);
$this->setAdminUser();

$this->expectException('\moodle_exception');
$this->expectExceptionMessage(get_string('errorinvalidparam', 'webservice', 'invalid'));
$options = [['name' => 'invalid', 'value' => 'invalidvalue']];
add_entry::execute('Subject', 'Summary', FORMAT_HTML, $options);
}

/**
* Test add_entry diabled associations.
*/
public function test_add_entry_disabled_assoc() {
global $CFG;
$CFG->useblogassociations = 0;

$this->resetAfterTest(true);
$this->setAdminUser();

$this->expectException('\moodle_exception');
$this->expectExceptionMessage(get_string('errorinvalidparam', 'webservice', 'modassoc'));
$options = [['name' => 'modassoc', 'value' => 1]];
add_entry::execute('Subject', 'Summary', FORMAT_HTML, $options);
}

/**
* Test add_entry invalid publish state.
*/
public function test_add_entry_invalid_publishstate() {
$this->resetAfterTest(true);
$this->setAdminUser();

$this->expectException('\moodle_exception');
$this->expectExceptionMessage(get_string('errorinvalidparam', 'webservice', 'publishstate'));
$options = [['name' => 'publishstate', 'value' => 'something']];
add_entry::execute('Subject', 'Summary', FORMAT_HTML, $options);
}

/**
* Test add_entry invalid association.
*/
public function test_add_entry_invalid_association() {
$this->resetAfterTest(true);

$course = $this->getDataGenerator()->create_course();
$anothercourse = $this->getDataGenerator()->create_course();
$page = $this->getDataGenerator()->create_module('page', ['course' => $course->id]);

$this->setAdminUser();

$this->expectException('\moodle_exception');
$this->expectExceptionMessage(get_string('errorinvalidparam', 'webservice', 'modassoc'));
$options = [
['name' => 'courseassoc', 'value' => $anothercourse->id],
['name' => 'modassoc', 'value' => $page->cmid],
];
add_entry::execute('Subject', 'Summary', FORMAT_HTML, $options);
}
}
Loading

0 comments on commit 5a679bf

Please sign in to comment.