Session: Move session image extra field to the session table as asset - refs GH#4366

Author:  @christianbeeznest
pull/4726/head
christianbeeznest 2 years ago committed by GitHub
parent 27f9d965c7
commit 6e84e2adbe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 91
      public/main/inc/lib/sessionmanager.lib.php
  2. 35
      public/main/session/session_add.php
  3. 16
      public/main/session/session_edit.php
  4. 1
      src/CoreBundle/Entity/Asset.php
  5. 22
      src/CoreBundle/Entity/Session.php
  6. 31
      src/CoreBundle/Migrations/Schema/V200/Version20230204145530.php
  7. 85
      src/CoreBundle/Migrations/Schema/V200/Version20230204150030.php

@ -2,6 +2,7 @@
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Entity\Asset;
use Chamilo\CoreBundle\Entity\Course;
use Chamilo\CoreBundle\Entity\ExtraField;
use Chamilo\CoreBundle\Entity\SequenceResource;
@ -15,6 +16,7 @@ use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CourseBundle\Entity\CSurvey;
use ExtraField as ExtraFieldModel;
use Monolog\Logger;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* This is the session library for Chamilo
@ -1929,6 +1931,9 @@ class SessionManager
}
}
// Delete Picture Session
SessionManager::deleteAsset($sessionId);
// Delete documents inside a session
$courses = self::getCoursesInSession($sessionId);
foreach ($courses as $courseId) {
@ -8098,9 +8103,24 @@ class SessionManager
get_lang('Send an email when a user being subscribed to session'),
);
// Picture
$form->addFile(
'picture',
get_lang('Add image'),
['id' => 'picture', 'class' => 'picture-form', 'crop_image' => true, 'crop_ratio' => '1 / 1']
);
$allowedPictureTypes = api_get_supported_image_extensions(false);
$form->addRule('picture', get_lang('Only PNG, JPG or GIF images allowed').' ('.implode(',', $allowedPictureTypes).')', 'filetype', $allowedPictureTypes);
if ($session && $session->getImage()) {
$form->addElement('checkbox', 'delete_picture', null, get_lang('Delete picture'));
$imageUrl = self::getSessionPictureUrl($session);
$form->addLabel(get_lang('Image'), "<img src = '$imageUrl' />");
}
// Extra fields
$extra_field = new ExtraFieldModel('session');
$extra = $extra_field->addElements($form, $session ? $session->getId() : 0);
$extra = $extra_field->addElements($form, $session ? $session->getId() : 0, ['image']);
$form->addElement('html', '</div>');
@ -8109,6 +8129,75 @@ class SessionManager
return ['js' => $js];
}
/**
* Saves the session picture.
*
* @param int $sessionId
* @param array $file
* @param string $crop
*
* @return false
*/
public static function updateSessionPicture(
$sessionId,
$file,
string $crop = ''
) {
if (empty($file)) {
return false;
}
$sessionRepo = Container::getSessionRepository();
$assetRepo = Container::getAssetRepository();
$asset = (new Asset())
->setCategory(Asset::SESSION)
->setTitle($file['name'])
;
if (!empty($crop)) {
$asset->setCrop($crop);
}
$asset = $assetRepo->createFromRequest($asset, $file);
/** @var Session $session */
$session = $sessionRepo->find($sessionId);
$session->setImage($asset);
$sessionRepo->update($session);
}
/**
* Deletes de session picture as asset.
*
* @param int $sessionId
*/
public static function deleteAsset(int $sessionId): void
{
$sessionRepo = Container::getSessionRepository();
/** @var Session $session */
$session = $sessionRepo->find($sessionId);
$em = Database::getManager();
if ($session->hasImage()) {
$asset = $session->getImage();
$em->remove($asset);
$em->flush();
}
}
/**
* Get the session picture url.
*
* @param Session $session
* @return string
*/
public static function getSessionPictureUrl(Session $session): string
{
$assetRepo = Container::getAssetRepository();
$imageUrl = $assetRepo->getAssetUrl($session->getImage());
return $imageUrl;
}
/**
* Gets the number of rows in the session table filtered through the given
* array of parameters.

@ -390,30 +390,6 @@ if ($form->validate()) {
$extraFields['extra_image']['crop_parameters'] = $params['picture_crop_result'];
}
// Check if the session image will be copied from the template
$importImageFromSession = false;
$sessionIdToImport = explode('::', $params['extra_image_crop_result']);
$sessionIdToImport = isset($sessionIdToImport[1]) ? (int) $sessionIdToImport[1] : 0;
if (!empty($sessionIdToImport)) {
$extraField = new ExtraField('session');
$extraFieldInfo = $extraField->get_handler_field_info_by_field_variable('image');
$extraFieldValue = new ExtraFieldValue('session');
$extraFieldValueData = $extraFieldValue->get_values_by_handler_and_field_id(
$sessionIdToImport,
$extraFieldInfo['id']
);
if ($extraFieldValueData) {
$repo = Container::getAssetRepository();
/** @var Asset $asset */
$asset = $repo->find($extraFieldValueData);
if ($asset) {
$extraFields['extra_image']['id'] = $extraFieldValueData;
}
}
}
$return = SessionManager::create_session(
$name,
$startDate,
@ -437,6 +413,17 @@ if ($form->validate()) {
);
if ($return == strval(intval($return))) {
// Add image
$picture = $_FILES['picture'];
if (!empty($picture['name'])) {
SessionManager::updateSessionPicture(
$return,
$picture,
$params['picture_crop_result']
);
}
// integer => no error on session creation
header('Location: add_courses_to_session.php?id_session='.$return.'&add=true');
exit();

@ -133,6 +133,22 @@ if ($form->validate()) {
);
if ($return) {
// Delete picture of session
$deletePicture = $_POST['delete_picture'] ?? '';
if ($deletePicture && $return) {
SessionManager::deleteAsset($return);
}
// Add image
$picture = $_FILES['picture'];
if (!empty($picture['name'])) {
SessionManager::updateSessionPicture(
$return,
$picture,
$params['picture_crop_result']
);
}
Display::addFlash(Display::return_message(get_lang('Update successful')));
header('Location: resume_session.php?id_session='.$return);
exit();

@ -36,6 +36,7 @@ class Asset implements Stringable
public const SKILL = 'skill';
public const EXERCISE_ATTEMPT = 'exercise_attempt';
public const EXERCISE_FEEDBACK = 'exercise_feedback';
public const SESSION = 'session';
#[ORM\Id]
#[ORM\Column(type: 'uuid')]

@ -15,6 +15,7 @@ use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use ApiPlatform\Serializer\Filter\PropertyFilter;
use Chamilo\CoreBundle\Entity\Asset;
use Chamilo\CoreBundle\Entity\Listener\SessionListener;
use Chamilo\CoreBundle\Repository\SessionRepository;
use DateTime;
@ -160,6 +161,13 @@ class Session implements ResourceWithAccessUrlInterface, Stringable
protected ?SessionCategory $category = null;
#[ORM\Column(name: 'send_subscription_notification', type: 'boolean', nullable: false, options: ['default' => false])]
protected bool $sendSubscriptionNotification;
/**
* Image illustrating the session (was extra field 'image' in 1.11)
*/
#[ORM\ManyToOne(targetEntity: Asset::class, cascade: ['remove'])]
#[ORM\JoinColumn(name: 'image_id', referencedColumnName: 'id', onDelete: 'SET NULL')]
protected ?Asset $image = null;
public function __construct()
{
$this->skills = new ArrayCollection();
@ -828,6 +836,20 @@ class Session implements ResourceWithAccessUrlInterface, Stringable
{
return $this->resourceLinks;
}
public function getImage(): ?Asset
{
return $this->image;
}
public function setImage(?Asset $asset): self
{
$this->image = $asset;
return $this;
}
public function hasImage(): bool
{
return null !== $this->image;
}
/**
* Check if $user is course coach in any course.
*/

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
/* For licensing terms, see /license.txt */
namespace Chamilo\CoreBundle\Migrations\Schema\V200;
use Chamilo\CoreBundle\Migrations\AbstractMigrationChamilo;
use Doctrine\DBAL\Schema\Schema;
class Version20230204145530 extends AbstractMigrationChamilo
{
public function getDescription(): string
{
return 'Session changes';
}
public function up(Schema $schema): void
{
$table = $schema->getTable('session');
if (false === $table->hasColumn('image_id')) {
$this->addSql("ALTER TABLE session ADD image_id BINARY(16) DEFAULT NULL COMMENT '(DC2Type:uuid)'");
$this->addSql("ALTER TABLE session ADD CONSTRAINT FK_D044D5D43DA5256D FOREIGN KEY (image_id) REFERENCES asset (id) ON DELETE SET NULL");
$this->addSql("CREATE INDEX IDX_D044D5D43DA5256D ON session (image_id)");
}
}
public function down(Schema $schema): void
{
}
}

@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
/* For licensing terms, see /license.txt */
namespace Chamilo\CoreBundle\Migrations\Schema\V200;
use Chamilo\CoreBundle\Entity\Asset;
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
use Chamilo\CoreBundle\Entity\Session;
use Chamilo\CoreBundle\Migrations\AbstractMigrationChamilo;
use Doctrine\DBAL\Schema\Schema;
use ExtraField;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class Version20230204150030 extends AbstractMigrationChamilo
{
public function getDescription(): string
{
return 'Move extrafield session image to asset';
}
public function up(Schema $schema): void
{
$container = $this->getContainer();
$doctrine = $container->get('doctrine');
$em = $doctrine->getManager();
$kernel = $container->get('kernel');
$rootPath = $kernel->getProjectDir();
$batchSize = self::BATCH_SIZE;
$counter = 1;
$dql = "SELECT v FROM Chamilo\CoreBundle\Entity\ExtraFieldValues v";
$dql .= " JOIN v.field f";
$dql .= " WHERE f.variable = :variable AND f.itemType = :itemType";
$q = $em->createQuery($dql);
$q->setParameters([
'variable' => 'image',
'itemType' => ExtraField::SESSION_FIELD_TYPE,
]);
$sessionRepo = $container->get(Session::class);
/** @var ExtraFieldValues $item */
foreach ($q->toIterable() as $item) {
$path = $item->getFieldValue();
if (empty($path)) {
continue;
}
$filePath = $rootPath.'/app/upload/'.$path;
if ($this->fileExists($filePath)) {
$fileName = basename($path);
$mimeType = mime_content_type($filePath);
$file = new UploadedFile($filePath, $fileName, $mimeType, null, true);
$asset = (new Asset())
->setCategory(Asset::SESSION)
->setTitle($fileName)
->setFile($file)
;
$em->persist($asset);
$em->flush();
$item->setAsset($asset);
$em->persist($item);
$sessionId = $item->getItemId();
/** @var Session $session */
$session = $sessionRepo->find($sessionId);
$session->setImage($asset);
$sessionRepo->update($session);
}
if (($counter % $batchSize) === 0) {
$em->flush();
$em->clear(); // Detaches all objects from Doctrine!
}
$counter++;
}
$em->flush();
$em->clear();
}
public function down(Schema $schema): void
{
}
}
Loading…
Cancel
Save