/td>
@@ -0,0 +1,29 @@
1
+from abc import ABC, abstractmethod
2
+
3
+class PostRepository(ABC):
4
+    
5
+    @abstractmethod
6
+    def list(self, page=1, per_page=10, order_by="-created"): pass
7
+    
8
+    @abstractmethod
9
+    def add(self, post): pass
10
+
11
+    @abstractmethod
12
+    def get(self, post_id): pass
13
+
14
+    @abstractmethod
15
+    def update(self, post):
16
+        """Update an existing post."""
17
+        pass
18
+
19
+    @abstractmethod
20
+    def delete(self, post_id):
21
+        """Delete a post by its ID."""
22
+        pass
23
+
24
+
25
+    @abstractmethod
26
+    def search(self, query: str): pass
27
+
28
+    @abstractmethod
29
+    def rate_post(self, post_id, user_id, rating: int): pass

+ 11 - 0
commu/interfaces/user_repository.py

@@ -0,0 +1,11 @@
1
+from abc import ABC, abstractmethod
2
+
3
+class UserRepository(ABC):
4
+    @abstractmethod
5
+    def add(self, user): pass
6
+
7
+    @abstractmethod
8
+    def get(self, user_id): pass
9
+
10
+    @abstractmethod
11
+    def find_by_username(self, username): pass

+ 0 - 0
commu/tests/__init__.py


BIN
commu/tests/__pycache__/__init__.cpython-310.pyc


BIN
commu/tests/__pycache__/__init__.cpython-311.pyc


BIN
commu/tests/__pycache__/test_post_repository.cpython-310-pytest-8.4.1.pyc


BIN
commu/tests/__pycache__/test_post_repository.cpython-311.pyc


BIN
commu/tests/__pycache__/test_post_service.cpython-310-pytest-8.4.1.pyc


BIN
commu/tests/__pycache__/test_post_service.cpython-311.pyc


BIN
commu/tests/__pycache__/test_user_service.cpython-310-pytest-8.4.1.pyc


BIN
commu/tests/__pycache__/test_user_service.cpython-311.pyc


+ 27 - 0
commu/tests/test_post_repository.py

@@ -0,0 +1,27 @@
1
+from commu.infrastructure.memory_post_repository import InMemoryPostRepository
2
+from commu.entities.post import Post
3
+
4
+def test_add_and_get_post():
5
+    repo = InMemoryPostRepository()
6
+    post = Post("user1", "content", images=["img.png"])
7
+    repo.add(post)
8
+    assert repo.get(post.id) == post
9
+
10
+def test_search():
11
+    repo = InMemoryPostRepository()
12
+    p1 = Post("u", "hello apple")
13
+    p2 = Post("u", "banana orange")
14
+    repo.add(p1)
15
+    repo.add(p2)
16
+    results = repo.search("apple")
17
+    assert len(results) == 1 and results[0].id == p1.id
18
+
19
+def test_rate_post():
20
+    repo = InMemoryPostRepository()
21
+    p = Post("u", "rate me")
22
+    repo.add(p)
23
+    repo.rate_post(p.id, "userA", 3)
24
+    repo.rate_post(p.id, "userB", 5)
25
+    # userA updates rating
26
+    repo.rate_post(p.id, "userA", 4)
27
+    assert p.ratings == [("userB", 5), ("userA", 4)] or p.ratings == [("userA", 4), ("userB", 5)]

+ 57 - 0
commu/tests/test_post_service.py

@@ -0,0 +1,57 @@
1
+import pytest
2
+from commu.usecases.post_service import PostService
3
+from commu.usecases.user_service import UserService
4
+from commu.infrastructure.memory_user_repository import InMemoryUserRepository
5
+from commu.infrastructure.memory_post_repository import InMemoryPostRepository
6
+from commu.entities.user import UserRole
7
+
8
+@pytest.fixture
9
+def setup_services():
10
+    user_repo = InMemoryUserRepository()
11
+    post_repo = InMemoryPostRepository()
12
+    user_svc = UserService(user_repo)
13
+    post_svc = PostService(post_repo, user_repo)
14
+    admin = user_svc.register("admin", UserRole.ADMIN)
15
+    user = user_svc.register("user", UserRole.USER)
16
+    guest = user_svc.register("guest", UserRole.GUEST)
17
+    return user_svc, post_svc, admin, user, guest
18
+
19
+def test_create_post(setup_services):
20
+    user_svc, post_svc, admin, user, guest = setup_services
21
+    post = post_svc.create_post(user.id, "My post", images=["a.jpg"])
22
+    assert post.text == "My post"
23
+    assert post.images == ["a.jpg"]
24
+
25
+def test_guest_cannot_create_post(setup_services):
26
+    user_svc, post_svc, admin, user, guest = setup_services
27
+    with pytest.raises(PermissionError):
28
+        post_svc.create_post(guest.id, "forbidden")
29
+
30
+def test_search_posts(setup_services):
31
+    user_svc, post_svc, admin, user, guest = setup_services
32
+    post1 = post_svc.create_post(user.id, "Hello world")
33
+    post2 = post_svc.create_post(user.id, "Another post")
34
+    results = post_svc.search_posts("hello")
35
+    assert len(results) == 1
36
+    assert results[0].text == "Hello world"
37
+
38
+def test_rate_post(setup_services):
39
+    user_svc, post_svc, admin, user, guest = setup_services
40
+    post = post_svc.create_post(user.id, "My post")
41
+    post_svc.rate_post(post.id, admin.id, 5)
42
+    post_svc.rate_post(post.id, user.id, 4)
43
+    assert abs(post.average_rating() - 4.5) < 1e-6
44
+
45
+def test_guest_cannot_rate(setup_services):
46
+    user_svc, post_svc, admin, user, guest = setup_services
47
+    post = post_svc.create_post(user.id, "Guest can't rate")
48
+    with pytest.raises(PermissionError):
49
+        post_svc.rate_post(post.id, guest.id, 5)
50
+
51
+def test_rating_bounds(setup_services):
52
+    user_svc, post_svc, admin, user, guest = setup_services
53
+    post = post_svc.create_post(user.id, "Test bounds")
54
+    with pytest.raises(ValueError):
55
+        post_svc.rate_post(post.id, admin.id, 0)
56
+    with pytest.raises(ValueError):
57
+        post_svc.rate_post(post.id, admin.id, 6)

+ 25 - 0
commu/tests/test_user_service.py

@@ -0,0 +1,25 @@
1
+import pytest
2
+from commu.usecases.user_service import UserService
3
+from commu.infrastructure.memory_user_repository import InMemoryUserRepository
4
+from commu.entities.user import UserRole
5
+
6
+def test_register_user():
7
+    repo = InMemoryUserRepository()
8
+    svc = UserService(repo)
9
+    user = svc.register("testuser")
10
+    assert user.username == "testuser"
11
+    assert user.role == UserRole.USER
12
+    assert repo.get(user.id) == user
13
+
14
+def test_register_admin():
15
+    repo = InMemoryUserRepository()
16
+    svc = UserService(repo)
17
+    user = svc.register("adminuser", UserRole.ADMIN)
18
+    assert user.role == UserRole.ADMIN
19
+
20
+def test_get_user():
21
+    repo = InMemoryUserRepository()
22
+    svc = UserService(repo)
23
+    user = svc.register("abc")
24
+    found = svc.get_user(user.id)
25
+    assert found.username == "abc"

+ 0 - 0
commu/usecases/__init__.py


BIN
commu/usecases/__pycache__/__init__.cpython-310.pyc


BIN
commu/usecases/__pycache__/__init__.cpython-311.pyc


BIN
commu/usecases/__pycache__/post_service.cpython-310.pyc


BIN
commu/usecases/__pycache__/post_service.cpython-311.pyc


BIN
commu/usecases/__pycache__/user_service.cpython-310.pyc


BIN
commu/usecases/__pycache__/user_service.cpython-311.pyc


+ 28 - 0
commu/usecases/post_service.py

@@ -0,0 +1,28 @@
1
+from commu.entities.post import Post
2
+from commu.entities.user import UserRole
3
+
4
+class PostService:
5
+    def __init__(self, post_repo, user_repo):
6
+        self.post_repo = post_repo
7
+        self.user_repo = user_repo
8
+
9
+    def create_post(self, author_id, text, images=None, videos=None):
10
+        user = self.user_repo.get(author_id)
11
+        print(f"user = {user}")
12
+        print(f"role = {user.role}")
13
+        if not user or user.role == UserRole.GUEST:
14
+            raise PermissionError("User does not have permission to create posts")
15
+        post = Post(author_id, text, images, videos)
16
+        self.post_repo.add(post)
17
+        return post
18
+
19
+    def search_posts(self, query):
20
+        return self.post_repo.search(query)
21
+
22
+    def rate_post(self, post_id, user_id, rating):
23
+        user = self.user_repo.get(user_id)
24
+        if not user or user.role == UserRole.GUEST:
25
+            raise PermissionError("Guests cannot rate posts")
26
+        if not (1 <= rating <= 5):
27
+            raise ValueError("Rating must be between 1 and 5")
28
+        self.post_repo.rate_post(post_id, user_id, rating)

+ 13 - 0
commu/usecases/user_service.py

@@ -0,0 +1,13 @@
1
+from commu.entities.user import User, UserRole
2
+
3
+class UserService:
4
+    def __init__(self, user_repo):
5
+        self.user_repo = user_repo
6
+
7
+    def register(self, username, role=UserRole.USER):
8
+        user = User(username, role)
9
+        self.user_repo.add(user)
10
+        return user
11
+
12
+    def get_user(self, user_id):
13
+        return self.user_repo.get(user_id)

+ 0 - 0
core/__init__.py


BIN
core/__pycache__/__init__.cpython-311.pyc


BIN
core/__pycache__/admin.cpython-311.pyc


BIN
core/__pycache__/apps.cpython-311.pyc


BIN
core/__pycache__/models.cpython-311.pyc


BIN
core/__pycache__/tests.cpython-311.pyc


BIN
core/__pycache__/urls.cpython-311.pyc


BIN
core/__pycache__/views.cpython-311.pyc


+ 3 - 0
core/admin.py

@@ -0,0 +1,3 @@
1
+from django.contrib import admin
2
+
3
+# Register your models here.

+ 6 - 0
core/apps.py

@@ -0,0 +1,6 @@
1
+from django.apps import AppConfig
2
+
3
+
4
+class CoreConfig(AppConfig):
5
+    default_auto_field = 'django.db.models.BigAutoField'
6
+    name = 'core'

+ 38 - 0
core/migrations/0001_initial.py

@@ -0,0 +1,38 @@
1
+# Generated by Django 5.2.4 on 2025-08-03 16:36
2
+
3
+import django.db.models.deletion
4
+from django.conf import settings
5
+from django.db import migrations, models
6
+
7
+
8
+class Migration(migrations.Migration):
9
+
10
+    initial = True
11
+
12
+    dependencies = [
13
+        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
14
+    ]
15
+
16
+    operations = [
17
+        migrations.CreateModel(
18
+            name='Post',
19
+            fields=[
20
+                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
21
+                ('text', models.TextField()),
22
+                ('images', models.JSONField(blank=True, default=list)),
23
+                ('videos', models.JSONField(blank=True, default=list)),
24
+                ('created', models.DateTimeField(auto_now_add=True)),
25
+                ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posts', to=settings.AUTH_USER_MODEL)),
26
+            ],
27
+        ),
28
+        migrations.CreateModel(
29
+            name='PostRating',
30
+            fields=[
31
+                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
32
+                ('rating', models.IntegerField()),
33
+                ('created', models.DateTimeField(auto_now_add=True)),
34
+                ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ratings', to='core.post')),
35
+                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
36
+            ],
37
+        ),
38
+    ]

+ 0 - 0
core/migrations/__init__.py


BIN
core/migrations/__pycache__/0001_initial.cpython-311.pyc


BIN
core/migrations/__pycache__/__init__.cpython-311.pyc


+ 18 - 0
core/models.py

@@ -0,0 +1,18 @@
1
+from django.db import models
2
+from django.contrib.auth import get_user_model
3
+
4
+User = get_user_model()
5
+
6
+class Post(models.Model):
7
+    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts")
8
+    text = models.TextField()
9
+    images = models.JSONField(default=list, blank=True)
10
+    videos = models.JSONField(default=list, blank=True)
11
+    created = models.DateTimeField(auto_now_add=True)
12
+
13
+class PostRating(models.Model):
14
+    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="ratings")
15
+    user = models.ForeignKey(User, on_delete=models.CASCADE)
16
+    rating = models.IntegerField()
17
+    created = models.DateTimeField(auto_now_add=True)
18
+

BIN
core/repositories/__pycache__/django_post_repository.cpython-311.pyc


BIN
core/repositories/__pycache__/django_user_repository.cpython-311.pyc


+ 112 - 0
core/repositories/django_post_repository.py

@@ -0,0 +1,112 @@
1
+from commu.interfaces.post_repository import PostRepository
2
+from core.models import Post, PostRating
3
+from django.contrib.auth import get_user_model
4
+
5
+User = get_user_model()
6
+
7
+class DjangoPostRepository(PostRepository):
8
+    def add(self, post):
9
+        # post: commu.entities.post.Post
10
+        try:
11
+            author = User.objects.get(id=post.author_id)
12
+        except User.DoesNotExist:
13
+            raise ValueError("Author not found")
14
+        obj = Post.objects.create(
15
+            author=author,
16
+            text=post.text,
17
+            images=post.images,
18
+            videos=post.videos,
19
+        )
20
+        post.id = str(obj.id)
21
+        return post
22
+
23
+    def get(self, post_id):
24
+        try:
25
+            obj = Post.objects.get(id=post_id)
26
+            from commu.entities.post import Post as DomainPost
27
+            domain_post = DomainPost(
28
+                author_id=str(obj.author.id),
29
+                text=obj.text,
30
+                images=obj.images,
31
+                videos=obj.videos,
32
+            )
33
+            domain_post.id = str(obj.id)
34
+            # Load ratings
35
+            domain_post.ratings = [
36
+                (str(r.user.id), r.rating)
37
+                for r in obj.ratings.all()
38
+            ]
39
+            return domain_post
40
+        except Post.DoesNotExist:
41
+            return None
42
+
43
+    def search(self, query: str):
44
+        qs = Post.objects.filter(text__icontains=query)
45
+        from commu.entities.post import Post as DomainPost
46
+        result = []
47
+        for obj in qs:
48
+            domain_post = DomainPost(
49
+                author_id=str(obj.author.id),
50
+                text=obj.text,
51
+                images=obj.images,
52
+                videos=obj.videos,
53
+            )
54
+            domain_post.id = str(obj.id)
55
+            # Load ratings
56
+            domain_post.ratings = [
57
+                (str(r.user.id), r.rating)
58
+                for r in obj.ratings.all()
59
+            ]
60
+            result.append(domain_post)
61
+        return result
62
+
63
+    def rate_post(self, post_id, user_id, rating: int):
64
+        try:
65
+            post = Post.objects.get(id=post_id)
66
+            user = User.objects.get(id=user_id)
67
+        except (Post.DoesNotExist, User.DoesNotExist):
68
+            raise ValueError("Post or user not found")
69
+        # Remove old rating from user, if any
70
+        PostRating.objects.filter(post=post, user=user).delete()
71
+        # Create new rating
72
+        PostRating.objects.create(post=post, user=user, rating=rating)
73
+
74
+    def delete(self, post_id):
75
+        try:
76
+            obj = Post.objects.get(id=post_id)
77
+            obj.delete()
78
+        except Post.DoesNotExist:
79
+            raise ValueError("Post not found")
80
+
81
+    def list(self, page=1, per_page=10, order_by="-created"):
82
+        qs = Post.objects.all().order_by(order_by)
83
+        total = qs.count()
84
+        start = (page - 1) * per_page
85
+        end = start + per_page
86
+        from commu.entities.post import Post as DomainPost
87
+        posts = []
88
+        for obj in qs[start:end]:
89
+            domain_post = DomainPost(
90
+                author_id=str(obj.author.id),
91
+                text=obj.text,
92
+                images=obj.images,
93
+                videos=obj.videos,
94
+            )
95
+            domain_post.id = str(obj.id)
96
+            domain_post.ratings = [
97
+                (str(r.user.id), r.rating)
98
+                for r in obj.ratings.all()
99
+            ]
100
+            posts.append(domain_post)
101
+        return posts, total
102
+
103
+    def update(self, post):
104
+        try:
105
+            obj = Post.objects.get(id=post.id)
106
+            obj.text = post.text
107
+            obj.images = post.images
108
+            obj.videos = post.videos
109
+            obj.save()
110
+            # Optionally update ratings (if part of update)
111
+        except Post.DoesNotExist:
112
+            raise ValueError("Post not found")

+ 55 - 0
core/repositories/django_user_repository.py

@@ -0,0 +1,55 @@
1
+from commu.interfaces.user_repository import UserRepository
2
+from django.contrib.auth.models import User as DjangoUser
3
+
4
+class DjangoUserRepository(UserRepository):
5
+    def add(self, user):
6
+        # user: commu.entities.user.User
7
+        # Map role to Django flags
8
+        is_staff = user.role.value in ("admin", "user") if hasattr(user.role, "value") else user.role in ("admin", "user")
9
+        is_superuser = user.role.value == "admin" if hasattr(user.role, "value") else user.role == "admin"
10
+        obj = DjangoUser.objects.create_user(
11
+            username=user.username,
12
+            password=None,  # You may set/generate a password as needed!
13
+            is_staff=is_staff,
14
+            is_superuser=is_superuser,
15
+        )
16
+        user.id = str(obj.id)
17
+        return user
18
+
19
+    def get(self, user_id):
20
+        try:
21
+            obj = DjangoUser.objects.get(id=user_id)
22
+            from commu.entities.user import User, UserRole
23
+            role = self._role_from_django(obj)
24
+            u = User(
25
+                username=obj.username,
26
+                role=role,
27
+            )
28
+            u.id = str(obj.id)
29
+            return u
30
+        except DjangoUser.DoesNotExist:
31
+            return None
32
+
33
+    def find_by_username(self, username):
34
+        try:
35
+            obj = DjangoUser.objects.get(username=username)
36
+            from commu.entities.user import User, UserRole
37
+            role = self._role_from_django(obj)
38
+            u = User(
39
+                username=obj.username,
40
+                role=role,
41
+            )
42
+            u.id = str(obj.id)
43
+            return u
44
+        except DjangoUser.DoesNotExist:
45
+            return None
46
+
47
+    def _role_from_django(self, user_obj):
48
+        from commu.entities.user import UserRole
49
+        if user_obj.is_superuser:
50
+            return UserRole.ADMIN
51
+        elif user_obj.is_staff:
52
+            return UserRole.USER
53
+        else:
54
+            return UserRole.GUEST
55
+

+ 3 - 0
core/tests.py

@@ -0,0 +1,3 @@
1
+from django.test import TestCase
2
+
3
+# Create your tests here.

+ 0 - 0
core/tests/__init__.py


BIN
core/tests/__pycache__/__init__.cpython-311.pyc


BIN
core/tests/__pycache__/test_post_service_django.cpython-311.pyc


+ 60 - 0
core/tests/test_post_service_django.py

@@ -0,0 +1,60 @@
1
+import pytest
2
+from django.test import TestCase
3
+from django.contrib.auth import get_user_model
4
+
5
+from commu.usecases.post_service import PostService
6
+from commu.entities.user import UserRole
7
+from core.repositories.django_post_repository import DjangoPostRepository
8
+from core.repositories.django_user_repository import DjangoUserRepository
9
+
10
+User = get_user_model()
11
+
12
+class PostServiceIntegrationTest(TestCase):
13
+
14
+    def setUp(self):
15
+        # Use Django's repositories
16
+        self.user_repo = DjangoUserRepository()
17
+        self.post_repo = DjangoPostRepository()
18
+        self.service = PostService(self.post_repo, self.user_repo)
19
+
20
+        # Create some users using Django ORM
21
+        self.admin = User.objects.create_user(username="admin", is_superuser=True, is_staff=True)
22
+        self.user = User.objects.create_user(username="user", is_staff=True)
23
+        self.guest = User.objects.create_user(username="guest")  # Not staff or superuser
24
+
25
+    def test_create_post_by_user(self):
26
+        post = self.service.create_post(str(self.user.id), "Hello Django!", ["img1.png"], ["vid1.mp4"])
27
+        assert post.text == "Hello Django!"
28
+        assert post.images == ["img1.png"]
29
+        assert post.videos == ["vid1.mp4"]
30
+
31
+    def test_guest_cannot_create_post(self):
32
+        with self.assertRaises(PermissionError):
33
+            self.service.create_post(str(self.guest.id), "Forbidden")
34
+
35
+    def test_search_posts(self):
36
+        p1 = self.service.create_post(str(self.user.id), "First Django post")
37
+        p2 = self.service.create_post(str(self.user.id), "Second hello world")
38
+        results = self.service.search_posts("hello")
39
+        assert len(results) == 1
40
+        assert results[0].text == "Second hello world"
41
+
42
+    def test_rate_post(self):
43
+        post = self.service.create_post(str(self.user.id), "Rate me Django!")
44
+        self.service.rate_post(post.id, str(self.admin.id), 5)
45
+        self.service.rate_post(post.id, str(self.user.id), 4)
46
+        updated_post = self.post_repo.get(post.id)
47
+        assert abs(updated_post.average_rating() - 4.5) < 1e-6
48
+
49
+    def test_guest_cannot_rate_post(self):
50
+        post = self.service.create_post(str(self.user.id), "No guest rate")
51
+        with self.assertRaises(PermissionError):
52
+            self.service.rate_post(post.id, str(self.guest.id), 2)
53
+
54
+    def test_rating_bounds(self):
55
+        post = self.service.create_post(str(self.user.id), "Bounds Django")
56
+        with self.assertRaises(ValueError):
57
+            self.service.rate_post(post.id, str(self.admin.id), 0)
58
+        with self.assertRaises(ValueError):
59
+            self.service.rate_post(post.id, str(self.admin.id), 6)
60
+

+ 8 - 0
core/urls.py

@@ -0,0 +1,8 @@
1
+from django.urls import path
2
+from . import views
3
+
4
+urlpatterns = [
5
+    path('posts/create/', views.create_post, name='create_post'),
6
+    path('posts/search/', views.search_posts, name='search_posts'),
7
+    path('posts/rate/', views.rate_post, name='rate_post'),
8
+]

+ 69 - 0
core/views.py

@@ -0,0 +1,69 @@
1
+import json
2
+from django.http import JsonResponse, HttpResponseBadRequest
3
+from django.views.decorators.csrf import csrf_exempt
4
+from django.contrib.auth.decorators import login_required
5
+from commu.usecases.post_service import PostService
6
+from core.repositories.django_post_repository import DjangoPostRepository
7
+from core.repositories.django_user_repository import DjangoUserRepository
8
+
9
+# Service setup (could be moved to app config for larger apps)
10
+user_repo = DjangoUserRepository()
11
+post_repo = DjangoPostRepository()
12
+post_service = PostService(post_repo, user_repo)
13
+
14
+@csrf_exempt
15
+@login_required
16
+def create_post(request):
17
+    if request.method != 'POST':
18
+        return HttpResponseBadRequest("POST only")
19
+    try:
20
+        data = json.loads(request.body.decode())
21
+        text = data.get("text")
22
+        images = data.get("images", [])
23
+        videos = data.get("videos", [])
24
+        if not text:
25
+            return JsonResponse({"error": "Missing post text"}, status=400)
26
+        # Use logged-in Django user as author
27
+        user_id = str(request.user.id)
28
+        post = post_service.create_post(user_id, text, images, videos)
29
+        return JsonResponse({
30
+            "id": post.id,
31
+            "text": post.text,
32
+            "author_id": post.author_id,
33
+            "images": post.images,
34
+            "videos": post.videos
35
+        })
36
+    except Exception as e:
37
+        return JsonResponse({"error": str(e)}, status=400)
38
+
39
+def search_posts(request):
40
+    q = request.GET.get("q", "")
41
+    results = post_service.search_posts(q)
42
+    posts = [{
43
+        "id": p.id,
44
+        "text": p.text,
45
+        "author_id": p.author_id,
46
+        "images": p.images,
47
+        "videos": p.videos,
48
+        "avg_rating": p.average_rating()
49
+    } for p in results]
50
+    return JsonResponse({"results": posts})
51
+
52
+@csrf_exempt
53
+@login_required
54
+def rate_post(request):
55
+    if request.method != 'POST':
56
+        return HttpResponseBadRequest("POST only")
57
+    try:
58
+        data = json.loads(request.body.decode())
59
+        post_id = data.get("post_id")
60
+        rating = data.get("rating")
61
+        if not post_id or rating is None:
62
+            return JsonResponse({"error": "Missing post_id or rating"}, status=400)
63
+        user_id = str(request.user.id)
64
+        post_service.rate_post(post_id, user_id, int(rating))
65
+        return JsonResponse({"ok": True})
66
+    except Exception as e:
67
+        return JsonResponse({"error": str(e)}, status=400)
68
+
69
+

+ 0 - 0
db.sqlite3


+ 0 - 0
django_commu/__init__.py


BIN
django_commu/__pycache__/__init__.cpython-311.pyc


BIN
django_commu/__pycache__/settings.cpython-311.pyc


BIN
django_commu/__pycache__/urls.cpython-311.pyc


BIN
django_commu/__pycache__/wsgi.cpython-311.pyc


+ 16 - 0
django_commu/asgi.py

@@ -0,0 +1,16 @@
1
+"""
2
+ASGI config for django_commu project.
3
+
4
+It exposes the ASGI callable as a module-level variable named ``application``.
5
+
6
+For more information on this file, see
7
+https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/
8
+"""
9
+
10
+import os
11
+
12
+from django.core.asgi import get_asgi_application
13
+
14
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_commu.settings')
15
+
16
+application = get_asgi_application()

+ 128 - 0
django_commu/settings.py

@@ -0,0 +1,128 @@
1
+"""
2
+Django settings for django_commu project.
3
+
4
+Generated by 'django-admin startproject' using Django 5.2.4.
5
+
6
+For more information on this file, see
7
+https://docs.djangoproject.com/en/5.2/topics/settings/
8
+
9
+For the full list of settings and their values, see
10
+https://docs.djangoproject.com/en/5.2/ref/settings/
11
+"""
12
+
13
+from pathlib import Path
14
+import os
15
+
16
+# Build paths inside the project like this: BASE_DIR / 'subdir'.
17
+BASE_DIR = Path(__file__).resolve().parent.parent
18
+
19
+
20
+# Quick-start development settings - unsuitable for production
21
+# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/
22
+
23
+# SECURITY WARNING: keep the secret key used in production secret!
24
+SECRET_KEY = 'django-insecure-c$ieo22nwe^v#*e$xlh@fath9*t+f8wtqrt9e!op9-ittc=b_x'
25
+
26
+# SECURITY WARNING: don't run with debug turned on in production!
27
+DEBUG = True
28
+
29
+ALLOWED_HOSTS = []
30
+
31
+
32
+# Application definition
33
+
34
+INSTALLED_APPS = [
35
+    'django.contrib.admin',
36
+    'django.contrib.auth',
37
+    'django.contrib.contenttypes',
38
+    'django.contrib.sessions',
39
+    'django.contrib.messages',
40
+    'django.contrib.staticfiles',
41
+    'core',
42
+]
43
+
44
+MIDDLEWARE = [
45
+    'django.middleware.security.SecurityMiddleware',
46
+    'django.contrib.sessions.middleware.SessionMiddleware',
47
+    'django.middleware.common.CommonMiddleware',
48
+    'django.middleware.csrf.CsrfViewMiddleware',
49
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
50
+    'django.contrib.messages.middleware.MessageMiddleware',
51
+    'django.middleware.clickjacking.XFrameOptionsMiddleware',
52
+]
53
+
54
+ROOT_URLCONF = 'django_commu.urls'
55
+
56
+TEMPLATES = [
57
+    {
58
+        'BACKEND': 'django.template.backends.django.DjangoTemplates',
59
+        'DIRS': [],
60
+        'APP_DIRS': True,
61
+        'OPTIONS': {
62
+            'context_processors': [
63
+                'django.template.context_processors.request',
64
+                'django.contrib.auth.context_processors.auth',
65
+                'django.contrib.messages.context_processors.messages',
66
+            ],
67
+        },
68
+    },
69
+]
70
+
71
+WSGI_APPLICATION = 'django_commu.wsgi.application'
72
+
73
+
74
+# Database
75
+# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
76
+
77
+DATABASES = {
78
+    'default': {
79
+        'ENGINE': 'django.db.backends.postgresql',
80
+        'NAME': os.getenv('DB_NAME', 'commudb'),
81
+        'USER': os.getenv('DB_USER', 'commuuser'),
82
+        'PASSWORD': os.getenv('DB_PASSWORD', 'commupass'),
83
+        'HOST': os.getenv('DB_HOST', 'db'),
84
+        'PORT': os.getenv('DB_PORT', '5432'),
85
+    }
86
+}
87
+
88
+
89
+# Password validation
90
+# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators
91
+
92
+AUTH_PASSWORD_VALIDATORS = [
93
+    {
94
+        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
95
+    },
96
+    {
97
+        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
98
+    },
99
+    {
100
+        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
101
+    },
102
+    {
103
+        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
104
+    },
105
+]
106
+
107
+
108
+# Internationalization
109
+# https://docs.djangoproject.com/en/5.2/topics/i18n/
110
+
111
+LANGUAGE_CODE = 'en-us'
112
+
113
+TIME_ZONE = 'UTC'
114
+
115
+USE_I18N = True
116
+
117
+USE_TZ = True
118
+
119
+
120
+# Static files (CSS, JavaScript, Images)
121
+# https://docs.djangoproject.com/en/5.2/howto/static-files/
122
+
123
+STATIC_URL = 'static/'
124
+
125
+# Default primary key field type
126
+# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
127
+
128
+DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

+ 23 - 0
django_commu/urls.py

@@ -0,0 +1,23 @@
1
+"""
2
+URL configuration for django_commu project.
3
+
4
+The `urlpatterns` list routes URLs to views. For more information please see:
5
+    https://docs.djangoproject.com/en/5.2/topics/http/urls/
6
+Examples:
7
+Function views
8
+    1. Add an import:  from my_app import views
9
+    2. Add a URL to urlpatterns:  path('', views.home, name='home')
10
+Class-based views
11
+    1. Add an import:  from other_app.views import Home
12
+    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
13
+Including another URLconf
14
+    1. Import the include() function: from django.urls import include, path
15
+    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
16
+"""
17
+from django.contrib import admin
18
+from django.urls import path, include
19
+
20
+urlpatterns = [
21
+    path('admin/', admin.site.urls),
22
+    path('core/', include('core.urls')),
23
+]

+ 16 - 0
django_commu/wsgi.py

@@ -0,0 +1,16 @@
1
+"""
2
+WSGI config for django_commu project.
3
+
4
+It exposes the WSGI callable as a module-level variable named ``application``.
5
+
6
+For more information on this file, see
7
+https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/
8
+"""
9
+
10
+import os
11
+
12
+from django.core.wsgi import get_wsgi_application
13
+
14
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_commu.settings')
15
+
16
+application = get_wsgi_application()

+ 40 - 0
docker-compose.yml

@@ -0,0 +1,40 @@
1
+version: '3.9'
2
+
3
+services:
4
+  db:
5
+    image: postgres:16
6
+    environment:
7
+      POSTGRES_DB: commudb
8
+      POSTGRES_USER: commuuser
9
+      POSTGRES_PASSWORD: commupass
10
+    ports:
11
+      - "5432:5432"
12
+    volumes:
13
+      - postgres_data:/var/lib/postgresql/data
14
+
15
+  web:
16
+    build:
17
+      context: .
18
+      args:
19
+        UID: ${UID}
20
+        GID: ${GID}
21
+    user: "${UID}:${GID}"
22
+    command: >
23
+      sh -c "python manage.py runserver 0.0.0.0:8000"
24
+    volumes:
25
+      - .:/app
26
+    working_dir: /app
27
+    ports:
28
+      - "8000:8000"
29
+    depends_on:
30
+      - db
31
+    environment:
32
+      - DEBUG=1
33
+      - DB_NAME=commudb
34
+      - DB_USER=commuuser
35
+      - DB_PASSWORD=commupass
36
+      - DB_HOST=db
37
+      - DB_PORT=5432
38
+
39
+volumes:
40
+  postgres_data:

+ 38 - 0
main.py

@@ -0,0 +1,38 @@
1
+from commu.infrastructure.memory_user_repository import InMemoryUserRepository
2
+from commu.infrastructure.memory_post_repository import InMemoryPostRepository
3
+from commu.usecases.user_service import UserService
4
+from commu.usecases.post_service import PostService
5
+from commu.entities.user import UserRole
6
+
7
+def main():
8
+    user_repo = InMemoryUserRepository()
9
+    post_repo = InMemoryPostRepository()
10
+    user_service = UserService(user_repo)
11
+    post_service = PostService(post_repo, user_repo)
12
+
13
+    # Create users
14
+    admin = user_service.register("alice", UserRole.ADMIN)
15
+    user = user_service.register("bob", UserRole.USER)
16
+    guest = user_service.register("guest", UserRole.GUEST)
17
+
18
+    # User creates post
19
+    post = post_service.create_post(user.id, "Hello world!", images=["img1.png"], videos=["vid1.mp4"])
20
+    print(f"Created Post: {post.text}, by {user.username}")
21
+
22
+    # Post search
23
+    found = post_service.search_posts("hello")
24
+    print(f"Found {len(found)} posts containing 'hello'.")
25
+
26
+    # Post rating
27
+    post_service.rate_post(post.id, admin.id, 5)
28
+    post_service.rate_post(post.id, user.id, 4)
29
+    print(f"Average Rating: {post.average_rating()}")
30
+
31
+    # Guest tries to create post (should fail)
32
+    try:
33
+        post_service.create_post(guest.id, "I am a guest")
34
+    except PermissionError as e:
35
+        print("Guest cannot create post:", e)
36
+
37
+if __name__ == "__main__":
38
+    main()

+ 22 - 0
manage.py

@@ -0,0 +1,22 @@
1
+#!/usr/bin/env python
2
+"""Django's command-line utility for administrative tasks."""
3
+import os
4
+import sys
5
+
6
+
7
+def main():
8
+    """Run administrative tasks."""
9
+    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_commu.settings')
10
+    try:
11
+        from django.core.management import execute_from_command_line
12
+    except ImportError as exc:
13
+        raise ImportError(
14
+            "Couldn't import Django. Are you sure it's installed and "
15
+            "available on your PYTHONPATH environment variable? Did you "
16
+            "forget to activate a virtual environment?"
17
+        ) from exc
18
+    execute_from_command_line(sys.argv)
19
+
20
+
21
+if __name__ == '__main__':
22
+    main()

+ 3 - 0
requirements.txt

@@ -0,0 +1,3 @@
1
+pytest
2
+Django>=4.2
3
+psycopg2-binary

tum/whitesports - Gogs: Simplico Git Service

Ei kuvausta

class-wp-users-list-table.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. <?php
  2. /**
  3. * List Table API: WP_Users_List_Table class
  4. *
  5. * @package WordPress
  6. * @subpackage Administration
  7. * @since 3.1.0
  8. */
  9. /**
  10. * Core class used to implement displaying users in a list table.
  11. *
  12. * @since 3.1.0
  13. * @access private
  14. *
  15. * @see WP_List_Table
  16. */
  17. class WP_Users_List_Table extends WP_List_Table {
  18. /**
  19. * Site ID to generate the Users list table for.
  20. *
  21. * @since 3.1.0
  22. * @var int
  23. */
  24. public $site_id;
  25. /**
  26. * Whether or not the current Users list table is for Multisite.
  27. *
  28. * @since 3.1.0
  29. * @var bool
  30. */
  31. public $is_site_users;
  32. /**
  33. * Constructor.
  34. *
  35. * @since 3.1.0
  36. *
  37. * @see WP_List_Table::__construct() for more information on default arguments.
  38. *
  39. * @param array $args An associative array of arguments.
  40. */
  41. public function __construct( $args = array() ) {
  42. parent::__construct(
  43. array(
  44. 'singular' => 'user',
  45. 'plural' => 'users',
  46. 'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
  47. )
  48. );
  49. $this->is_site_users = 'site-users-network' === $this->screen->id;
  50. if ( $this->is_site_users ) {
  51. $this->site_id = isset( $_REQUEST['id'] ) ? (int) $_REQUEST['id'] : 0;
  52. }
  53. }
  54. /**
  55. * Check the current user's permissions.
  56. *
  57. * @since 3.1.0
  58. *
  59. * @return bool
  60. */
  61. public function ajax_user_can() {
  62. if ( $this->is_site_users ) {
  63. return current_user_can( 'manage_sites' );
  64. } else {
  65. return current_user_can( 'list_users' );
  66. }
  67. }
  68. /**
  69. * Prepare the users list for display.
  70. *
  71. * @since 3.1.0
  72. *
  73. * @global string $role
  74. * @global string $usersearch
  75. */
  76. public function prepare_items() {
  77. global $role, $usersearch;
  78. $usersearch = isset( $_REQUEST['s'] ) ? wp_unslash( trim( $_REQUEST['s'] ) ) : '';
  79. $role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : '';
  80. $per_page = ( $this->is_site_users ) ? 'site_users_network_per_page' : 'users_per_page';
  81. $users_per_page = $this->get_items_per_page( $per_page );
  82. $paged = $this->get_pagenum();
  83. if ( 'none' === $role ) {
  84. $args = array(
  85. 'number' => $users_per_page,
  86. 'offset' => ( $paged - 1 ) * $users_per_page,
  87. 'include' => wp_get_users_with_no_role( $this->site_id ),
  88. 'search' => $usersearch,
  89. 'fields' => 'all_with_meta',
  90. );
  91. } else {
  92. $args = array(
  93. 'number' => $users_per_page,
  94. 'offset' => ( $paged - 1 ) * $users_per_page,
  95. 'role' => $role,
  96. 'search' => $usersearch,
  97. 'fields' => 'all_with_meta',
  98. );
  99. }
  100. if ( '' !== $args['search'] ) {
  101. $args['search'] = '*' . $args['search'] . '*';
  102. }
  103. if ( $this->is_site_users ) {
  104. $args['blog_id'] = $this->site_id;
  105. }
  106. if ( isset( $_REQUEST['orderby'] ) ) {
  107. $args['orderby'] = $_REQUEST['orderby'];
  108. }
  109. if ( isset( $_REQUEST['order'] ) ) {
  110. $args['order'] = $_REQUEST['order'];
  111. }
  112. /**
  113. * Filters the query arguments used to retrieve users for the current users list table.
  114. *
  115. * @since 4.4.0
  116. *
  117. * @param array $args Arguments passed to WP_User_Query to retrieve items for the current
  118. * users list table.
  119. */
  120. $args = apply_filters( 'users_list_table_query_args', $args );
  121. // Query the user IDs for this page.
  122. $wp_user_search = new WP_User_Query( $args );
  123. $this->items = $wp_user_search->get_results();
  124. $this->set_pagination_args(
  125. array(
  126. 'total_items' => $wp_user_search->get_total(),
  127. 'per_page' => $users_per_page,
  128. )
  129. );
  130. }
  131. /**
  132. * Output 'no users' message.
  133. *
  134. * @since 3.1.0
  135. */
  136. public function no_items() {
  137. _e( 'No users found.' );
  138. }
  139. /**
  140. * Return an associative array listing all the views that can be used
  141. * with this table.
  142. *
  143. * Provides a list of roles and user count for that role for easy
  144. * Filtersing of the user table.
  145. *
  146. * @since 3.1.0
  147. *
  148. * @global string $role
  149. *
  150. * @return string[] An array of HTML links keyed by their view.
  151. */
  152. protected function get_views() {
  153. global $role;
  154. $wp_roles = wp_roles();
  155. if ( $this->is_site_users ) {
  156. $url = 'site-users.php?id=' . $this->site_id;
  157. switch_to_blog( $this->site_id );
  158. $users_of_blog = count_users( 'time', $this->site_id );
  159. restore_current_blog();
  160. } else {
  161. $url = 'users.php';
  162. $users_of_blog = count_users();
  163. }
  164. $total_users = $users_of_blog['total_users'];
  165. $avail_roles =& $users_of_blog['avail_roles'];
  166. unset( $users_of_blog );
  167. $current_link_attributes = empty( $role ) ? ' class="current" aria-current="page"' : '';
  168. $role_links = array();
  169. $role_links['all'] = sprintf(
  170. '<a href="%s"%s>%s</a>',
  171. $url,
  172. $current_link_attributes,
  173. sprintf(
  174. /* translators: %s: Number of users. */
  175. _nx(
  176. 'All <span class="count">(%s)</span>',
  177. 'All <span class="count">(%s)</span>',
  178. $total_users,
  179. 'users'
  180. ),
  181. number_format_i18n( $total_users )
  182. )
  183. );
  184. foreach ( $wp_roles->get_names() as $this_role => $name ) {
  185. if ( ! isset( $avail_roles[ $this_role ] ) ) {
  186. continue;
  187. }
  188. $current_link_attributes = '';
  189. if ( $this_role === $role ) {
  190. $current_link_attributes = ' class="current" aria-current="page"';
  191. }
  192. $name = translate_user_role( $name );
  193. $name = sprintf(
  194. /* translators: 1: User role name, 2: Number of users. */
  195. __( '%1$s <span class="count">(%2$s)</span>' ),
  196. $name,
  197. number_format_i18n( $avail_roles[ $this_role ] )
  198. );
  199. $role_links[ $this_role ] = "<a href='" . esc_url( add_query_arg( 'role', $this_role, $url ) ) . "'$current_link_attributes>$name</a>";
  200. }
  201. if ( ! empty( $avail_roles['none'] ) ) {
  202. $current_link_attributes = '';
  203. if ( 'none' === $role ) {
  204. $current_link_attributes = ' class="current" aria-current="page"';
  205. }
  206. $name = __( 'No role' );
  207. $name = sprintf(
  208. /* translators: 1: User role name, 2: Number of users. */
  209. __( '%1$s <span class="count">(%2$s)</span>' ),
  210. $name,
  211. number_format_i18n( $avail_roles['none'] )
  212. );
  213. $role_links['none'] = "<a href='" . esc_url( add_query_arg( 'role', 'none', $url ) ) . "'$current_link_attributes>$name</a>";
  214. }
  215. return $role_links;
  216. }
  217. /**
  218. * Retrieve an associative array of bulk actions available on this table.
  219. *
  220. * @since 3.1.0
  221. *
  222. * @return array Array of bulk action labels keyed by their action.
  223. */
  224. protected function get_bulk_actions() {
  225. $actions = array();
  226. if ( is_multisite() ) {
  227. if ( current_user_can( 'remove_users' ) ) {
  228. $actions['remove'] = __( 'Remove' );
  229. }
  230. } else {
  231. if ( current_user_can( 'delete_users' ) ) {
  232. $actions['delete'] = __( 'Delete' );
  233. }
  234. }
  235. // Add a password reset link to the bulk actions dropdown.
  236. if ( current_user_can( 'edit_users' ) ) {
  237. $actions['resetpassword'] = __( 'Send password reset' );
  238. }
  239. return $actions;
  240. }
  241. /**
  242. * Output the controls to allow user roles to be changed in bulk.
  243. *
  244. * @since 3.1.0
  245. *
  246. * @param string $which Whether this is being invoked above ("top")
  247. * or below the table ("bottom").
  248. */
  249. protected function extra_tablenav( $which ) {
  250. $id = 'bottom' === $which ? 'new_role2' : 'new_role';
  251. $button_id = 'bottom' === $which ? 'changeit2' : 'changeit';
  252. ?>
  253. <div class="alignleft actions">
  254. <?php if ( current_user_can( 'promote_users' ) && $this->has_items() ) : ?>
  255. <label class="screen-reader-text" for="<?php echo $id; ?>"><?php _e( 'Change role to&hellip;' ); ?></label>
  256. <select name="<?php echo $id; ?>" id="<?php echo $id; ?>">
  257. <option value=""><?php _e( 'Change role to&hellip;' ); ?></option>
  258. <?php wp_dropdown_roles(); ?>
  259. <option value="none"><?php _e( '&mdash; No role for this site &mdash;' ); ?></option>
  260. </select>
  261. <?php
  262. submit_button( __( 'Change' ), '', $button_id, false );
  263. endif;
  264. /**
  265. * Fires just before the closing div containing the bulk role-change controls
  266. * in the Users list table.
  267. *
  268. * @since 3.5.0
  269. * @since 4.6.0 The `$which` parameter was added.
  270. *
  271. * @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
  272. */
  273. do_action( 'restrict_manage_users', $which );
  274. ?>
  275. </div>
  276. <?php
  277. /**
  278. * Fires immediately following the closing "actions" div in the tablenav for the users
  279. * list table.
  280. *
  281. * @since 4.9.0
  282. *
  283. * @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
  284. */
  285. do_action( 'manage_users_extra_tablenav', $which );
  286. }
  287. /**
  288. * Capture the bulk action required, and return it.
  289. *
  290. * Overridden from the base class implementation to capture
  291. * the role change drop-down.
  292. *
  293. * @since 3.1.0
  294. *
  295. * @return string The bulk action required.
  296. */
  297. public function current_action() {
  298. if ( isset( $_REQUEST['changeit'] ) && ! empty( $_REQUEST['new_role'] ) ) {
  299. return 'promote';
  300. }
  301. return parent::current_action();
  302. }
  303. /**
  304. * Get a list of columns for the list table.
  305. *
  306. * @since 3.1.0
  307. *
  308. * @return string[] Array of column titles keyed by their column name.
  309. */
  310. public function get_columns() {
  311. $c = array(
  312. 'cb' => '<input type="checkbox" />',
  313. 'username' => __( 'Username' ),
  314. 'name' => __( 'Name' ),
  315. 'email' => __( 'Email' ),
  316. 'role' => __( 'Role' ),
  317. 'posts' => __( 'Posts' ),
  318. );
  319. if ( $this->is_site_users ) {
  320. unset( $c['posts'] );
  321. }
  322. return $c;
  323. }
  324. /**
  325. * Get a list of sortable columns for the list table.
  326. *
  327. * @since 3.1.0
  328. *
  329. * @return array Array of sortable columns.
  330. */
  331. protected function get_sortable_columns() {
  332. $c = array(
  333. 'username' => 'login',
  334. 'email' => 'email',
  335. );
  336. return $c;
  337. }
  338. /**
  339. * Generate the list table rows.
  340. *
  341. * @since 3.1.0
  342. */
  343. public function display_rows() {
  344. // Query the post counts for this page.
  345. if ( ! $this->is_site_users ) {
  346. $post_counts = count_many_users_posts( array_keys( $this->items ) );
  347. }
  348. foreach ( $this->items as $userid => $user_object ) {
  349. echo "\n\t" . $this->single_row( $user_object, '', '', isset( $post_counts ) ? $post_counts[ $userid ] : 0 );
  350. }
  351. }
  352. /**
  353. * Generate HTML for a single row on the users.php admin panel.
  354. *
  355. * @since 3.1.0
  356. * @since 4.2.0 The `$style` parameter was deprecated.
  357. * @since 4.4.0 The `$role` parameter was deprecated.
  358. *
  359. * @param WP_User $user_object The current user object.
  360. * @param string $style Deprecated. Not used.
  361. * @param string $role Deprecated. Not used.
  362. * @param int $numposts Optional. Post count to display for this user. Defaults
  363. * to zero, as in, a new user has made zero posts.
  364. * @return string Output for a single row.
  365. */
  366. public function single_row( $user_object, $style = '', $role = '', $numposts = 0 ) {
  367. if ( ! ( $user_object instanceof WP_User ) ) {
  368. $user_object = get_userdata( (int) $user_object );
  369. }
  370. $user_object->filter = 'display';
  371. $email = $user_object->user_email;
  372. if ( $this->is_site_users ) {
  373. $url = "site-users.php?id={$this->site_id}&amp;";
  374. } else {
  375. $url = 'users.php?';
  376. }
  377. $user_roles = $this->get_role_list( $user_object );
  378. // Set up the hover actions for this user.
  379. $actions = array();
  380. $checkbox = '';
  381. $super_admin = '';
  382. if ( is_multisite() && current_user_can( 'manage_network_users' ) ) {
  383. if ( in_array( $user_object->user_login, get_super_admins(), true ) ) {
  384. $super_admin = ' &mdash; ' . __( 'Super Admin' );
  385. }
  386. }
  387. // Check if the user for this row is editable.
  388. if ( current_user_can( 'list_users' ) ) {
  389. // Set up the user editing link.
  390. $edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user_object->ID ) ) );
  391. if ( current_user_can( 'edit_user', $user_object->ID ) ) {
  392. $edit = "<strong><a href=\"{$edit_link}\">{$user_object->user_login}</a>{$super_admin}</strong><br />";
  393. $actions['edit'] = '<a href="' . $edit_link . '">' . __( 'Edit' ) . '</a>';
  394. } else {
  395. $edit = "<strong>{$user_object->user_login}{$super_admin}</strong><br />";
  396. }
  397. if ( ! is_multisite() && get_current_user_id() != $user_object->ID && current_user_can( 'delete_user', $user_object->ID ) ) {
  398. $actions['delete'] = "<a class='submitdelete' href='" . wp_nonce_url( "users.php?action=delete&amp;user=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Delete' ) . '</a>';
  399. }
  400. if ( is_multisite() && current_user_can( 'remove_user', $user_object->ID ) ) {
  401. $actions['remove'] = "<a class='submitdelete' href='" . wp_nonce_url( $url . "action=remove&amp;user=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Remove' ) . '</a>';
  402. }
  403. // Add a link to the user's author archive, if not empty.
  404. $author_posts_url = get_author_posts_url( $user_object->ID );
  405. if ( $author_posts_url ) {
  406. $actions['view'] = sprintf(
  407. '<a href="%s" aria-label="%s">%s</a>',
  408. esc_url( $author_posts_url ),
  409. /* translators: %s: Author's display name. */
  410. esc_attr( sprintf( __( 'View posts by %s' ), $user_object->display_name ) ),
  411. __( 'View' )
  412. );
  413. }
  414. // Add a link to send the user a reset password link by email.
  415. if ( get_current_user_id() !== $user_object->ID && current_user_can( 'edit_user', $user_object->ID ) ) {
  416. $actions['resetpassword'] = "<a class='resetpassword' href='" . wp_nonce_url( "users.php?action=resetpassword&amp;users=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Send password reset' ) . '</a>';
  417. }
  418. /**
  419. * Filters the action links displayed under each user in the Users list table.
  420. *
  421. * @since 2.8.0
  422. *
  423. * @param string[] $actions An array of action links to be displayed.
  424. * Default 'Edit', 'Delete' for single site, and
  425. * 'Edit', 'Remove' for Multisite.
  426. * @param WP_User $user_object WP_User object for the currently listed user.
  427. */
  428. $actions = apply_filters( 'user_row_actions', $actions, $user_object );
  429. // Role classes.
  430. $role_classes = esc_attr( implode( ' ', array_keys( $user_roles ) ) );
  431. // Set up the checkbox (because the user is editable, otherwise it's empty).
  432. $checkbox = sprintf(
  433. '<label class="screen-reader-text" for="user_%1$s">%2$s</label>' .
  434. '<input type="checkbox" name="users[]" id="user_%1$s" class="%3$s" value="%1$s" />',
  435. $user_object->ID,
  436. /* translators: %s: User login. */
  437. sprintf( __( 'Select %s' ), $user_object->user_login ),
  438. $role_classes
  439. );
  440. } else {
  441. $edit = "<strong>{$user_object->user_login}{$super_admin}</strong>";
  442. }
  443. $avatar = get_avatar( $user_object->ID, 32 );
  444. // Comma-separated list of user roles.
  445. $roles_list = implode( ', ', $user_roles );
  446. $r = "<tr id='user-$user_object->ID'>";
  447. list( $columns, $hidden, $sortable, $primary ) = $this->get_column_info();
  448. foreach ( $columns as $column_name => $column_display_name ) {
  449. $classes = "$column_name column-$column_name";
  450. if ( $primary === $column_name ) {
  451. $classes .= ' has-row-actions column-primary';
  452. }
  453. if ( 'posts' === $column_name ) {
  454. $classes .= ' num'; // Special case for that column.
  455. }
  456. if ( in_array( $column_name, $hidden, true ) ) {
  457. $classes .= ' hidden';
  458. }
  459. $data = 'data-colname="' . esc_attr( wp_strip_all_tags( $column_display_name ) ) . '"';
  460. $attributes = "class='$classes' $data";
  461. if ( 'cb' === $column_name ) {
  462. $r .= "<th scope='row' class='check-column'>$checkbox</th>";
  463. } else {
  464. $r .= "<td $attributes>";
  465. switch ( $column_name ) {
  466. case 'username':
  467. $r .= "$avatar $edit";
  468. break;
  469. case 'name':
  470. if ( $user_object->first_name && $user_object->last_name ) {
  471. $r .= "$user_object->first_name $user_object->last_name";
  472. } elseif ( $user_object->first_name ) {
  473. $r .= $user_object->first_name;
  474. } elseif ( $user_object->last_name ) {
  475. $r .= $user_object->last_name;
  476. } else {
  477. $r .= sprintf(
  478. '<span aria-hidden="true">&#8212;</span><span class="screen-reader-text">%s</span>',
  479. _x( 'Unknown', 'name' )
  480. );
  481. }
  482. break;
  483. case 'email':
  484. $r .= "<a href='" . esc_url( "mailto:$email" ) . "'>$email</a>";
  485. break;
  486. case 'role':
  487. $r .= esc_html( $roles_list );
  488. break;
  489. case 'posts':
  490. if ( $numposts > 0 ) {
  491. $r .= sprintf(
  492. '<a href="%s" class="edit"><span aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
  493. "edit.php?author={$user_object->ID}",
  494. $numposts,
  495. sprintf(
  496. /* translators: %s: Number of posts. */
  497. _n( '%s post by this author', '%s posts by this author', $numposts ),
  498. number_format_i18n( $numposts )
  499. )
  500. );
  501. } else {
  502. $r .= 0;
  503. }
  504. break;
  505. default:
  506. /**
  507. * Filters the display output of custom columns in the Users list table.
  508. *
  509. * @since 2.8.0
  510. *
  511. * @param string $output Custom column output. Default empty.
  512. * @param string $column_name Column name.
  513. * @param int $user_id ID of the currently-listed user.
  514. */
  515. $r .= apply_filters( 'manage_users_custom_column', '', $column_name, $user_object->ID );
  516. }
  517. if ( $primary === $column_name ) {
  518. $r .= $this->row_actions( $actions );
  519. }
  520. $r .= '</td>';
  521. }
  522. }
  523. $r .= '</tr>';
  524. return $r;
  525. }
  526. /**
  527. * Gets the name of the default primary column.
  528. *
  529. * @since 4.3.0
  530. *
  531. * @return string Name of the default primary column, in this case, 'username'.
  532. */
  533. protected function get_default_primary_column_name() {
  534. return 'username';
  535. }
  536. /**
  537. * Returns an array of user roles for a given user object.
  538. *
  539. * @since 4.4.0
  540. *
  541. * @param WP_User $user_object The WP_User object.
  542. * @return string[] An array of user roles.
  543. */
  544. protected function get_role_list( $user_object ) {
  545. $wp_roles = wp_roles();
  546. $role_list = array();
  547. foreach ( $user_object->roles as $role ) {
  548. if ( isset( $wp_roles->role_names[ $role ] ) ) {
  549. $role_list[ $role ] = translate_user_role( $wp_roles->role_names[ $role ] );
  550. }
  551. }
  552. if ( empty( $role_list ) ) {
  553. $role_list['none'] = _x( 'None', 'no user roles' );
  554. }
  555. /**
  556. * Filters the returned array of roles for a user.
  557. *
  558. * @since 4.4.0
  559. *
  560. * @param string[] $role_list An array of user roles.
  561. * @param WP_User $user_object A WP_User object.
  562. */
  563. return apply_filters( 'get_role_list', $role_list, $user_object );
  564. }
  565. }