Archived
1
0

Initial commit as of 2018-10-16

This commit is contained in:
Marcel
2018-10-16 18:28:42 +02:00
commit 29d7c2ffdc
3601 changed files with 358427 additions and 0 deletions

View File

@@ -0,0 +1,77 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class AdminModel extends CI_Model {
public function __construct() {
parent::__construct();
}
public function insertRedirect($url, $name) {
$result1 = $this->db->query('SELECT * FROM redirects WHERE redirect = ?', [$name])->result_array();
if(empty($result1)) {
$this->db->query('INSERT INTO redirects (url, redirect) VALUES (?, ?)', [$url, $name]);
return ['feedback' => 'success'];
} else {
return ['feedback' => 'error', 'message' => 'Umleitungs-Code ist schon vergeben!'];
}
}
public function getUrl($name) {
$result1 = $this->db->query('SELECT * FROM redirects WHERE redirect = ?', [$name])->result_array();
if(empty($result1)) {
return base_url();
} else {
$result = $result1[0];
return $result['url'];
}
}
public function getItems() {
$result = $this->db->query('SELECT * FROM redirects')->result_array();
return $result;
}
public function getName($url) {
$result = $this->db->query('SELECT * FROM redirects WHERE url = ?', [$url])->result_array();
if(empty($result)) {
return '';
} else {
$result1 = $result[0];
return $result1['redirect'];
}
}
public function addRandomItem($url) {
if($this->redirect->getName($url) == '') {
for($i = 0; $i < 1; $i++) {
$randomName = base64_encode($url);
$name = '';
for($j = 0; $j < 5; $j++) {
$random = rand(0, strlen($randomName) - 1);
$name .= $randomName[$random];
}
if($this->redirect->insertRedirect($url, $name)['feedback'] == 'success') {
return $this->redirect->getName($url);
} else {
$i--;
}
}
} else {
return $this->redirect->getName($url);
}
}
public function getCalendarEvents()
{
return $this->db->query('SELECT * FROM calendar')->result_array();
}
}

View File

@@ -0,0 +1,665 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require "vendor/autoload.php";
use PHPHtmlParser\Dom;
use PHPHtmlParser\Dom\HtmlNode;
use PHPHtmlParser\Dom\TextNode;
class BlogModel extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->model('UserModel', '', TRUE);
}
function getAllPosts($search, $amount, $offset = 0)
{
$offset *= $amount;
if ($search !== '') {
$posts = $this->db->query('
SELECT
p.*,
ca.name categoryName,
ca.display_name categoryDisplayName,
(SELECT count(*)
FROM blog_comments
WHERE post_id = p.postID) commentCount,
(SELECT count(*)
FROM blog_post_likes
WHERE post_id = p.postID) likeCount,
(SELECT wordCount FROM blog_content c WHERE c.postID = p.postID AND isActive = TRUE AND c.language = ? ORDER BY c.contentDate DESC LIMIT 1) wordCount
FROM blog_posts p, blog_categories ca
WHERE ca.id = p.postCategoryID
AND (CONCAT((SELECT t.postTitle FROM blog_translations t WHERE t.postID = p.postID AND language = ?), postUrl, (SELECT t.postDesc FROM blog_translations t WHERE t.postID = p.postID AND language = ?)) RLIKE ?
OR (SELECT content
FROM blog_content
WHERE blog_content.postID = p.postID AND isActive = TRUE
LIMIT 1) RLIKE ?)
AND postState = 1
ORDER BY postPublishDate DESC
LIMIT ? OFFSET ?', [$_SESSION['site_lang'], $_SESSION['site_lang'], $_SESSION['site_lang'], $search, $search, $amount, $offset])->result_array();
} else {
$posts = $this->db->query('
SELECT p.*,
ca.name categoryName,
ca.display_name categoryDisplayName,
(SELECT count(*) FROM blog_comments WHERE post_id = p.postID) commentCount,
(SELECT count(*) FROM blog_post_likes WHERE post_id = p.postID) likeCount,
(SELECT wordCount FROM blog_content c WHERE c.postID = p.postID AND isActive = TRUE AND c.language = ? ORDER BY c.contentDate DESC LIMIT 1) wordCount
FROM blog_posts p, blog_categories ca
WHERE ca.id = p.postCategoryID
AND postState = 1
ORDER BY postPublishDate DESC
LIMIT ? OFFSET ?', [$_SESSION['site_lang'], $amount, $offset])->result_array();
}
$posts = $this->mergePostTitleDesc($posts);
$posts = $this->mergePostAuthorData($posts);
return $posts;
}
public function getPostPageCount($search, $postsPerPage)
{
if ($search !== '') {
$data = $this->db->query('
SELECT COUNT(*) pageCount
FROM blog_posts p, blog_categories ca
WHERE ca.id = p.postCategoryID
AND (CONCAT((SELECT t.postTitle FROM blog_translations t WHERE t.postID = p.postID AND language = ?), postUrl, (SELECT t.postDesc FROM blog_translations t WHERE t.postID = p.postID AND language = ?)) RLIKE ?
OR (SELECT content FROM blog_content WHERE blog_content.postID = p.postID AND isActive = TRUE LIMIT 1) RLIKE ?)
AND postState = 1', [$_SESSION['site_lang'], $_SESSION['site_lang'], $search, $search])->result_array();
} else {
$data = $this->db->query('SELECT COUNT(*) pageCount FROM blog_posts')->result_array();
}
return ($data[0]['pageCount']) / $postsPerPage;
}
function getCategoryPosts($category, $amount, $offset = 0)
{
$offset *= $amount;
$posts = $this->db->query('
SELECT p.*, ca.name categoryName, ca.display_name categoryDisplayName, (SELECT count(*) FROM blog_comments WHERE post_id = p.postID) commentCount, (SELECT count(*) FROM blog_post_likes WHERE post_id = p.postID) likeCount
FROM blog_posts p, blog_categories ca
WHERE ca.id = p.postCategoryID
AND postState = 1
AND ca.name = ?
ORDER BY postPublishDate DESC
LIMIT ? OFFSET ?', [$category, $amount, $offset])->result_array();
$posts = $this->mergePostTitleDesc($posts);
$posts = $this->mergePostAuthorData($posts);
return $posts;
}
public function getCategoryPostsByID($categoryID, $amount = 3, $postID = NULL)
{
$posts = $this->db->query('SELECT * FROM blog_posts WHERE postCategoryID = ? AND postID != ? AND blog_posts.postState = 1 ORDER BY postPublishDate DESC LIMIT ?', [$categoryID, $postID, $amount])->result_array();
return $this->mergePostTitleDesc($posts);
}
public function getTagPosts($tag, $amount, $offset = 0) {
$offset *= $amount;
$posts = $this->db->query('SELECT p.*, ca.name categoryName, ca.display_name categoryDisplayName, (SELECT count(*) FROM blog_comments WHERE post_id = p.postID) commentCount, (SELECT count(*) FROM blog_post_likes WHERE post_id = p.postID) likeCount FROM blog_posts p LEFT JOIN blog_categories ca ON ca.ID = p.postCategoryID WHERE postState = 1 AND EXISTS(SELECT post_id FROM blog_post_tags WHERE tag_id = (SELECT ID FROM blog_tags t WHERE t.name = ?) AND post_id = p.postID) ORDER BY postPublishDate DESC LIMIT ? OFFSET ?', [$tag, $amount, $offset])->result_array();
$posts = $this->mergePostTitleDesc($posts);
$posts = $this->mergePostAuthorData($posts);
return $posts;
}
function getCategoryIDAfterInsert($name, $display_name)
{
if (!$this->db->simple_query('INSERT INTO blog_categories (name, display_name) VALUES (?, ?)', [$name, $display_name])) {
$return = $this->db->query('SELECT ID FROM blog_categories WHERE name = ? AND display_name = ? LIMIT 1', [$name, $display_name])->result_array()[0];
$return = $return['ID'];
} else {
$return = $this->db->query('SELECT LAST_INSERT_ID() ID')->result_array()[0]['ID'];
}
return $return;
}
function incrementViews($id)
{
$this->db->query('UPDATE blog_posts SET postViews = postViews+1 WHERE postID = ?', [$id]);
$this->db->cache_delete('admin', 'blog');
}
public function getCategories()
{
$this->db->cache_off();
$categories = $this->db->query('SELECT * FROM blog_categories')->result_array();
$this->db->cache_on();
return $categories;
}
public function getPost($postUrl)
{
$content = $this->db->query('
SELECT p.*,
ca.name categoryName,
ca.display_name categoryDisplayName,
COUNT(co.comment) commentCount,
(SELECT count(*) FROM blog_post_likes l WHERE l.post_id = p.postID) likeCount
FROM blog_posts p
LEFT JOIN blog_categories ca ON p.postCategoryID = ca.ID
LEFT JOIN blog_comments co ON p.postID = co.post_id
LEFT JOIN blog_post_likes l ON p.postID = l.post_id
WHERE postUrl = ? AND postState = 1
GROUP BY p.postID', [$postUrl])->result_array(); //TODO: language integration
$content = $this->mergePostTitleDesc($content);
$content = $this->mergePostAuthorData($content);
$content = $this->mergePostContent($content, $_SESSION['site_lang']);
return $content[0];
}
public function getPostDataByID($postID)
{
$data = $this->db->query('
SELECT p.*,
ca.name AS categoryName,
ca.display_name AS categoryDisplayName,
COUNT(co.comment) AS commentCount,
COUNT(l.post_id) AS likeCount
FROM blog_posts p
LEFT JOIN blog_categories ca ON p.postCategoryID = ca.ID
LEFT JOIN blog_comments co ON p.postID = co.post_id
LEFT JOIN blog_post_likes l ON p.postID = l.post_id
WHERE postID = ?
GROUP BY p.postID', [$postID])->result_array();
return $data;
}
public function getContentDataByID($postID, $contentID, $lang)
{
$data = $this->db->query('SELECT * FROM blog_content WHERE postID = ? AND contentID = ? AND language = ?', [$postID, $contentID, $lang])->result_array();
return $data;
}
public function getTranslationDataByID($postID, $translationID, $lang)
{
$data = $this->db->query('SELECT * FROM blog_translations WHERE postID = ? AND postTranslationID = ? AND language = ?', [$postID, $translationID, $lang])->result_array();
return $data;
}
private function getPostContentByID($postID, $language)
{
$content = $this->db->query('SELECT * FROM blog_content WHERE postID = ? AND isActive = TRUE AND language = ? ORDER BY contentDate DESC LIMIT 1', [$postID, $language])->result_array();
return $content;
}
public function getRandomPosts($postID)
{
$posts = $this->db->query('SELECT * FROM blog_posts WHERE postID <> ? AND postState = 1 ORDER BY RAND() LIMIT 3', [$postID])->result_array();
$posts = $this->mergePostTitleDesc($posts);
$posts = $this->mergePostAuthorData($posts);
return $posts;
}
public function mergePostTitleDesc($posts, $language = NULL)
{
$language = ($language == NULL ? $_SESSION['site_lang'] : $language);
foreach ($posts as $i => $post) {
$titleDesc = $this->getPostTitleDesc($post['postID'], $language);
$posts[$i]['postTitle'] = $titleDesc['title'];
$posts[$i]['postDesc'] = $titleDesc['desc'];
}
return $posts;
}
private function mergePostAuthorData($posts)
{
foreach ($posts as $i => $post) {
$authorData = $this->getAuthorData($post['postAuthorID']);
$posts[$i]['postAuthorDisplayname'] = $authorData['displayname'];
$posts[$i]['postAuthorUsername'] = $authorData['username'];
$posts[$i]['postAuthorProfilePicture'] = $authorData['profile_picture'];
$posts[$i]['postAuthorHeaderImage'] = $authorData['header_image'];
$posts[$i]['postAuthorRank'] = $authorData['rank'];
$posts[$i]['postAuthorAbout'] = $authorData['about'];
}
return $posts;
}
private function mergePostContent($posts, $language)
{
$language = ($language == NULL ? $_SESSION['site_lang'] : $language);
foreach ($posts as $i => $post) {
$content = $this->getPostContentByID($post['postID'], $language);
if (empty($content) && $_SESSION['site_lang'] !== 'de') {
$content = $this->getPostContentByID($post['postID'], 'de');
}
if (!empty($content)) {
$content = $content[0];
$posts[$i]['postContent'] = $content['content'];
$posts[$i]['postWordCount'] = $content['wordCount'];
}
}
return $posts;
}
public function getPostTitleDesc($postID, $language)
{
$data = $this->db->query('SELECT * FROM blog_translations WHERE postID = ? ORDER BY blog_translations.language ASC', [$postID])->result_array();
if (empty($data)) {
return ['title' => 'Nicht vorhandener Post', 'desc' => 'Aus unbekannten Gründen ist dieser Blog-Post nicht vorhanden. Bitte versuche es später erneut oder kontaktiere das Support-Team'];
}
$postTitle = $data[0]['postTitle'];
$postDesc = $data[0]['postDesc'];
foreach ($data as $row) {
if ($row['language'] == $language) {
$postTitle = $row['postTitle'];
$postDesc = $row['postDesc'];
break;
}
}
return ['title' => $postTitle, 'desc' => $postDesc];
}
public function getAuthorData($authorID)
{
$author = $this->db->query('SELECT ID, username, displayname, rank, profile_picture, header_image, about FROM users WHERE ID = ?', [$authorID])->result_array();
$author = $this->UserModel->setDefaultImages($author);
if(empty($author)) {
return null;
}
return $author[0];
}
public function getComments($postID)
{
$comments = $this->db->query('SELECT * FROM blog_comments WHERE post_id = ? ORDER BY date_created DESC', [$postID])->result_array();
return $comments;
}
public function getCommentsByUrl($postUrl)
{
return $this->db->query('SELECT * FROM blog_comments WHERE post_id = (SELECT postID FROM blog_posts WHERE postUrl = ?) ORDER BY date_created DESC', [$postUrl])->result_array();
}
public function addComment($postID, $userID, $comment, $reply, $replyTo)
{
$this->db->query('INSERT INTO blog_comments (post_id, user_id, comment, reply, replyTo_id) VALUES (?, ?, ?, ?, ?)', [$postID, $userID, $comment, $reply, $replyTo]);
$this->db->cache_delete('blog', 'index');
$this->db->cache_delete('blog', 'post');
$this->db->cache_delete('blog', 'comment');
$this->db->cache_delete('blog', 'getComments');
$this->db->cache_delete('admin', 'blog');
}
public function addCommentByUrl($postUrl, $userID, $comment, $reply, $replyTo)
{
$postID = $this->db->query('SELECT postID FROM blog_posts WHERE postUrl = ?', [$postUrl])->result_array();
if(empty($postID)) {
return null;
}
$this->addComment($postID[0]['postID'], $userID, $comment, $reply, $replyTo);
return $this->db->query('SELECT * FROM blog_comments WHERE post_id = ? AND user_id = ? ORDER BY ID DESC LIMIT 1', [$postID[0]['postID'], $userID])->result_array()[0];
}
public function getAllTags()
{
return $this->db->query('SELECT * FROM blog_tags')->result_array();
}
public function getTags($postID)
{
$tags = $this->db->query('SELECT t.* FROM blog_tags t WHERE ID IN (SELECT tag_id FROM blog_post_tags WHERE post_id = ?)', [$postID])->result_array();
return $tags;
}
public function mergeTagInfo($tags) {
foreach ($tags as $i => $tag) {
$data = $this->db->query('SELECT count(*) countUsed, SUM(postViews) totalViews FROM blog_posts WHERE postID = (SELECT post_id FROM blog_post_tags WHERE tag_id = ? AND post_id = postID)', [$tag['ID']])->result_array();
$data = $data[0];
$tags[$i]['countUsed'] = $data['countUsed'];
$tags[$i]['totalViews'] = $data['totalViews'] != '' ? $data['totalViews'] : 0;
}
return $tags;
}
public function hasAlreadyLiked($postID, $userID)
{
$getLikes = $this->db->query('SELECT * FROM blog_post_likes WHERE post_id = ? AND user_id = ?', [$postID, $userID])->result_array();
if (empty($getLikes)) {
return false;
} else {
return true;
}
}
public function addLike($postID, $userID)
{
$this->db->query('INSERT INTO blog_post_likes (post_id, user_id) VALUES (?, ?)', [$postID, $userID]);
$this->db->cache_delete('blog', 'index');
$this->db->cache_delete('blog', 'post');
$this->db->cache_delete('blog', 'like');
$this->db->cache_delete('admin', 'blog');
return $this->db->query('SELECT count(*) likeCount FROM blog_post_likes WHERE post_id = ?', [$postID])->result_array()[0];
}
public function removeLike($postID, $userID)
{
$this->db->query('DELETE FROM blog_post_likes WHERE post_id = ? AND user_id = ?', [$postID, $userID]);
$this->db->cache_delete('blog', 'index');
$this->db->cache_delete('blog', 'post');
$this->db->cache_delete('blog', 'like');
$this->db->cache_delete('admin', 'blog');
return $this->db->query('SELECT count(*) likeCount FROM blog_post_likes WHERE post_id = ?', [$postID])->result_array()[0];
}
public function getPostList($onlyTrash)
{
$posts = $this->db->query('SELECT p.*,
ca.name categoryName,
ca.display_name categoryDisplayName,
(SELECT count(*)
FROM blog_comments
WHERE post_id = p.postID) commentCount,
(SELECT count(*)
FROM blog_post_likes
WHERE post_id = p.postID) likeCount,
(SELECT display_name
FROM blog_states
WHERE ID = p.postState) postStateDisplay
FROM blog_posts p
LEFT JOIN blog_categories ca ON ca.ID = p.postCategoryID
WHERE postIsDeleted = ?', [$onlyTrash])->result_array();
$posts = $this->mergePostTitleDesc($posts);
$posts = $this->mergePostAuthorData($posts);
return $posts;
}
public function getAllContentVersions($postID, $lang)
{
$content = $this->db->query('SELECT * FROM blog_content WHERE postID = ? AND language = ? ORDER BY contentDate DESC', [$postID, $lang])->result_array();
return $content;
}
public function createTagIfNotExists($tag)
{
$this->db->cache_off();
$tagData = $this->db->query('SELECT ID FROM blog_tags WHERE name = ?', [strtolower($tag)])->result_array();
if (empty($tagData)) {
$this->db->query('INSERT INTO blog_tags (name, display_name) VALUES (?, ?)', [strtolower($tag), $tag]);
$tagData = $this->db->query('SELECT ID FROM blog_tags WHERE name = ?', [strtolower($tag)])->result_array();
}
$this->db->cache_on();
$tagID = $tagData[0]['ID'];
return $tagID;
}
public function addPostTagByID($postID, $tagID)
{
$this->db->query('INSERT INTO blog_post_tags (post_id, tag_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE post_id = post_id', [$postID, $tagID]);
$this->db->cache_delete('blog', 'index');
$this->db->cache_delete('blog', 'post');
$this->db->cache_delete('blog', 'like');
$this->db->cache_delete('admin', 'blog');
}
public function deleteAllPostTags($postID)
{
$this->db->query('DELETE FROM blog_post_tags WHERE post_id = ?', [$postID]);
$this->db->cache_delete('blog', 'index');
$this->db->cache_delete('blog', 'post');
$this->db->cache_delete('blog', 'tag');
$this->db->cache_delete('admin', 'blog');
}
// TODO: Update
public function prepareContentForRelease($content)
{
$dom = new Dom;
$dom->load($content);
$images = $dom->find('img');
foreach ($images as $image) {
$image_src = $image->getAttribute('src');
$image_caption = $image->getAttribute('alt');
$image->removeAllAttributes();
$image->setAttribute('class', 'img-fluid');
$image->setAttribute('src', $image_src);
$image->setAttribute('alt', $image_caption);
$container = new HtmlNode('div');
$container->setAttribute('class', 'img');
$caption_node = new HtmlNode('p');
$caption = new TextNode($image_caption);
$caption_node->addChild($caption);
$parent = $image->getParent();
$parent->addChild($container);
$container->addChild($image);
$container->addChild($caption_node);
}
$iframes = $dom->find('iframe');
foreach ($iframes as $iframe) {
$container = new HtmlNode('div');
$container->setAttribute('class', 'responsive-video');
$parent = $iframe->getParent();
$parent->addChild($container);
$container->addChild($iframe);
}
return $dom;
}
public function getFirstImage($content)
{
$dom = new Dom;
$dom->load($content);
$images = $dom->find('img');
if ($images[0] == null)
return '';
$imageSrc = $images[0]->getAttribute('src');
return $imageSrc;
}
public function deletePost($id)
{
$this->db->query('UPDATE blog_posts SET postIsDeleted = TRUE, postDeletedDate = NOW(), postState = 4 WHERE postID = ? LIMIT 1', [$id]);
$this->db->cache_delete('blog', 'index');
$this->db->cache_delete('blog', 'post');
$this->db->cache_delete('blog', 'like');
$this->db->cache_delete('blog', 'comment');
$this->db->cache_delete('blog', 'getComments');
$this->db->cache_delete('admin', 'blog');
}
public function restorePost($id)
{
$this->db->query('UPDATE blog_posts SET postIsDeleted = FALSE, postDeletedDate = NULL, postState = 1 WHERE postID = ? LIMIT 1', [$id]);
$this->db->cache_delete('blog', 'index');
$this->db->cache_delete('blog', 'post');
$this->db->cache_delete('blog', 'like');
$this->db->cache_delete('blog', 'comment');
$this->db->cache_delete('blog', 'getComments');
$this->db->cache_delete('admin', 'blog');
}
public function deletePostFinally($id)
{
$this->db->query('DELETE FROM blog_content WHERE postID = ? AND (SELECT postIsDeleted FROM blog_posts WHERE postID = ?) = TRUE', [$id, $id]);
$this->db->query('DELETE FROM blog_post_likes WHERE post_id = ? AND (SELECT postIsDeleted FROM blog_posts WHERE postID = ?) = TRUE', [$id, $id]);
$this->db->query('DELETE FROM blog_post_tags WHERE post_id = ? AND (SELECT postIsDeleted FROM blog_posts WHERE postID = ?) = TRUE', [$id, $id]);
$this->db->query('DELETE FROM blog_comments WHERE post_id = ? AND (SELECT postIsDeleted FROM blog_posts WHERE postID = ?) = TRUE', [$id, $id]);
$this->db->query('DELETE FROM blog_posts WHERE postID = ? AND postIsDeleted = TRUE LIMIT 1', [$id]);
$this->db->cache_delete('blog', 'index');
$this->db->cache_delete('blog', 'post');
$this->db->cache_delete('blog', 'like');
$this->db->cache_delete('blog', 'comment');
$this->db->cache_delete('blog', 'getComments');
$this->db->cache_delete('admin', 'blog');
}
public function getPrevPost($id)
{
$posts = $this->db->query('SELECT postID, postUrl, postImage FROM blog_posts WHERE postPublishDate < (SELECT postPublishDate FROM blog_posts WHERE postID = ?) AND postState = 1 ORDER BY postPublishDate DESC LIMIT 1', [$id])->result_array();
return $this->mergePostTitleDesc($posts);
}
public function getNextPost($id)
{
$posts = $this->db->query('SELECT postID, postUrl, postImage FROM blog_posts WHERE postPublishDate > (SELECT postPublishDate FROM blog_posts WHERE postID = ?) AND postState = 1 ORDER BY postPublishDate ASC LIMIT 1', [$id])->result_array();
return $this->mergePostTitleDesc($posts);
}
public function getMostRecentPosts($count)
{
$posts = $this->db->query('SELECT postID, postImage, postUrl, postPublishDate FROM blog_posts WHERE postState = 1 ORDER BY postPublishDate DESC LIMIT ?', [$count])->result_array();
return $this->mergePostTitleDesc($posts);
}
private function countWords($text)
{
$text = preg_replace("/<[a-zA-Z0-9\/ .,:;\-_+!?&%=\"]+>/", '', $text);
return str_word_count($text);
}
public function getReadingTime($postID)
{
$data = $this->db->query('SELECT wordCount, language FROM blog_content c WHERE postID = ? AND isActive = TRUE AND (c.language = ? OR c.language = "de") ORDER BY contentDate DESC', [$postID, $_SESSION['site_lang']])->result_array();
if (empty($data)) {
return 0;
}
$wordCount = $data[0]['wordCount'];
foreach ($data as $entry) {
if ($entry['language'] == $_SESSION['site_lang']) {
$wordCount = $entry['wordCount'];
break;
}
}
$wordsPerSecond = 3;
$duration = $wordCount / $wordsPerSecond;
$duration /= 60;
$duration = round($duration);
return $duration;
}
public function createNewPostDraft($authorID)
{
$this->db->query('INSERT INTO blog_posts (postAuthorID, postState) VALUE (?, 2)', [$authorID]);
$data = $this->db->query('SELECT postID FROM blog_posts WHERE postState = 2 ORDER BY postID DESC LIMIT 1')->result_array();
return intval($data[0]['postID']);
}
public function createNewContentDraft($postID)
{
$this->db->query('INSERT INTO blog_content (postID, isActive) VALUES (?, 0)', [$postID]);
$this->db->cache_delete('admin', 'blog');
$data = $this->db->query('SELECT contentID FROM blog_content WHERE postID = ? ORDER BY contentID DESC LIMIT 1', [$postID])->result_array();
return intval($data[0]['contentID']);
}
public function createNewTranslation($postID, $language)
{
$data = $this->db->query('SELECT postTranslationID FROM blog_translations WHERE postID = ? AND language = ?', [$postID, $language])->result_array();
if (empty($data)) {
$this->db->query('INSERT INTO blog_translations (postID, language) VALUES (?, ?)', [$postID, $language]);
$data = $this->db->query('SELECT postTranslationID FROM blog_translations WHERE postID = ? AND language = ? ORDER BY postTranslationID DESC', [$postID, $language])->result_array();
}
return intval($data[0]['postTranslationID']);
}
public function updatePostDraft($postID, $postUrl, $postCategory, $postPublishDate, $postImage)
{
$this->db->query('UPDATE blog_posts SET postUrl = ?, postCategoryID = ?, postPublishDate = ?, postImage = ? WHERE postID = ?', [$postUrl, $postCategory, $postPublishDate, $postImage, $postID]);
$this->db->cache_delete('admin', 'edit');
}
public function updateContentDraft($contentID, $postContent, $postLang)
{
$wordCount = $this->countWords($postContent);
$this->db->query('UPDATE blog_content SET content = ?, language = ?, contentDate = NOW(), wordCount = ? WHERE contentID = ?', [$postContent, $postLang, $wordCount, $contentID]);
$this->db->cache_delete('admin', 'blog');
}
public function updateTranslation($translationID, $postTitle, $postDesc)
{
$this->db->query('UPDATE blog_translations SET postTitle = ?, postDesc = ? WHERE postTranslationID = ?', [$postTitle, $postDesc, $translationID]);
$this->db->cache_delete('admin', 'blog');
}
public function publishPostDraft($postID)
{
$this->db->query('UPDATE blog_posts SET postPublishDate = NOW(), postLastEdit = NOW(), postState = 1 WHERE postID = ?', [$postID]);
$this->db->cache_delete('blog', 'index');
$this->db->cache_delete('blog', 'post');
$this->db->cache_delete('blog', 'tag');
$this->db->cache_delete('blog', 'category');
$this->db->cache_delete('blog', 'search');
$this->db->cache_delete('admin', 'blog');
}
public function publishContentDraft($authorID, $contentID, $postID, $lang)
{
$firstContent = $this->db->query('SELECT contentID FROM blog_content WHERE postID = ? AND contentID != ? AND language = ?', [$postID, $contentID, $lang])->result_array();
$isNative = TRUE;
if(!empty($firstContent)) {
$isNative = FALSE;
}
$this->db->query('UPDATE blog_content SET isActive = FALSE WHERE postID = ?', [$postID]);
$this->db->query('UPDATE blog_content SET isActive = TRUE, isNativePost = ?, contentDate = NOW(), contentAuthorID = ? WHERE contentID = ?', [$isNative, $authorID, $contentID]);
}
public function getPostTranslationIDs($postID) {
$data = $this->db->query('SELECT postTranslationID, language FROM blog_translations WHERE postID = ?', [$postID])->result_array();
return $data;
}
public function getPostContentIDs($postID) {
$data = $this->db->query('SELECT (SELECT contentID FROM blog_content WHERE language = c.language ORDER BY contentID DESC LIMIT 1) contentID, language FROM blog_content c WHERE postID = ? AND language IS NOT NULL GROUP BY language ORDER BY contentID DESC', [$postID])->result_array();
return $data;
}
public function getPostTranslations($postID)
{
$data = $this->db->query('SELECT * FROM blog_translations t LEFT JOIN blog_content c ON c.postID = t.postID AND c.language = t.language WHERE t.postID = ?', [$postID])->result_array();
return $data;
}
public function postIDExisting($postID)
{
$data = $this->db->query('SELECT postID FROM blog_posts WHERE postID = ?', [$postID])->result_array();
return !empty($data);
}
public function contentIDExisting($postID, $contentID)
{
$data = $this->db->query('SELECT contentID FROM blog_content WHERE postID = ? AND contentID = ?', [$postID, $contentID])->result_array();
return !empty($data);
}
public function translationIDExisting($postID, $translationID)
{
$data = $this->db->query('SELECT postTranslationID FROM blog_translations WHERE postID = ? AND postTranslationID = ?', [$postID, $translationID])->result_array();
return !empty($data);
}
public function postUrlExisting($postUrl) {
$data = $this->db->query('SELECT postUrl FROM blog_posts WHERE postUrl = ?', [$postUrl])->result_array();
return !empty($data);
}
}

View File

@@ -0,0 +1,373 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class DatabaseModel extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->createMissingDatbases();
}
public function createMissingDatbases() {
$this->createDatabases();
$this->createTables();
$this->fillBlogDb();
$this->fillMainDb();
$this->fillPortfolioDb();
}
public function createDatabases() {
// $this->db->query('CREATE DATABASE IF NOT EXISTS `blog` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci');
// $this->db->query('CREATE DATABASE IF NOT EXISTS `kingofdog` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci');
// $this->db->query('CREATE DATABASE IF NOT EXISTS `portfolio` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci');
// $this->db->query('CREATE DATABASE IF NOT EXISTS `social_media` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci');
}
public function createTables()
{
// Calendar Table
$this->db->query('CREATE TABLE IF NOT EXISTS `calendar` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`title` VARCHAR(300) NOT NULL,
`allDay` TINYINT(1) NOT NULL,
`start` VARCHAR(20) NOT NULL,
`end` VARCHAR(20) NOT NULL,
`url` TEXT NOT NULL,
`overlap` TINYINT(1) NOT NULL,
`color` TEXT NOT NULL,
`textColor` TEXT NOT NULL,
`description` TEXT NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1');
// Feedback Table
$this->db->query('CREATE TABLE IF NOT EXISTS `feedback` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`page` VARCHAR(100) DEFAULT NULL,
`message` TEXT,
`datetime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`anonymous` TINYINT(1) DEFAULT \'1\',
`userID` INT(11) DEFAULT NULL,
`email` VARCHAR(50) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1');
// Files Table
$this->db->query('CREATE TABLE IF NOT EXISTS `files` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`original_name` VARCHAR(50) NOT NULL,
`type` VARCHAR(30) NOT NULL,
`size` INT(11) NOT NULL,
`path` VARCHAR(300) NOT NULL,
`uploadDate` DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=72 DEFAULT CHARSET=latin1');
// Redirects Table
$this->db->query('CREATE TABLE IF NOT EXISTS `redirects` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`redirect` TEXT NOT NULL,
`url` TEXT NOT NULL,
`temporary` TINYINT(1) NOT NULL,
`expireDate` DATETIME DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=220 DEFAULT CHARSET=latin1');
// User Followers Table
$this->db->query('CREATE TABLE IF NOT EXISTS `user_followers` (
`followedUserID` INT(11) NOT NULL,
`followerUserID` INT(11) NOT NULL,
`followedSince` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1');
// User Posts Table
$this->db->query('CREATE TABLE IF NOT EXISTS `user_posts` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) DEFAULT NULL,
`title` VARCHAR(150) NOT NULL,
`content` TEXT,
`date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`reply_to` INT(11) DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `user_posts_ID_uindex` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=145 DEFAULT CHARSET=latin1');
// User Posts Likes Table
$this->db->query('CREATE TABLE IF NOT EXISTS `user_posts_likes` (
`postID` INT(11) NOT NULL,
`likedUserID` INT(11) NOT NULL,
`likerUserID` INT(11) NOT NULL,
UNIQUE KEY `likerUserID` (`likerUserID`),
UNIQUE KEY `postID` (`postID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1');
// Users Table
$this->db->query('CREATE TABLE IF NOT EXISTS `users` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`original_name` VARCHAR(25) NOT NULL,
`username` VARCHAR(25) NOT NULL,
`displayname` VARCHAR(25) NOT NULL,
`login_method` INT(11) DEFAULT \'0\',
`password` TEXT,
`email` TEXT NOT NULL,
`rank` TEXT NOT NULL,
`profile_picture` TEXT NOT NULL,
`header_image` TEXT,
`social_networks` TEXT,
`is_activated` TINYINT(1) NOT NULL,
`activation_key` VARCHAR(256) DEFAULT NULL,
`showAds` TINYINT(1) NOT NULL DEFAULT \'1\',
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`isCurrentlyOnline` TINYINT(1) DEFAULT \'0\',
`about` TEXT NOT NULL,
`lastLogin` DATETIME NOT NULL,
`language` VARCHAR(10) DEFAULT \'DE\',
`country` VARCHAR(2) DEFAULT NULL,
`gender` VARCHAR(10) DEFAULT NULL,
`receiveEmails` TINYINT(1) NOT NULL DEFAULT \'1\',
`receiveNewsletter` TINYINT(1) NOT NULL DEFAULT \'1\',
`forget_password_key` VARCHAR(256) DEFAULT NULL,
`isDeleted` TINYINT(1) DEFAULT \'0\',
UNIQUE KEY `id` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1');
// Users History Table
$this->db->query('CREATE TABLE IF NOT EXISTS `users_history` (
`changeID` INT(11) NOT NULL AUTO_INCREMENT,
`changeDate` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ID` INT(11) NOT NULL,
`username` VARCHAR(25) NOT NULL,
`displayname` VARCHAR(25) NOT NULL,
`email` TEXT NOT NULL,
`rank` INT(11) NOT NULL,
`profile_picture` TEXT NOT NULL,
`header_image` TEXT,
`social_networks` TEXT,
`showAds` TINYINT(1) NOT NULL DEFAULT \'1\',
`about` TEXT NOT NULL,
`language` VARCHAR(10) DEFAULT \'DE\',
`country` VARCHAR(2) DEFAULT NULL,
`gender` VARCHAR(10) DEFAULT NULL,
`receiveEmails` TINYINT(1) NOT NULL DEFAULT \'1\',
`receiveNewsletter` TINYINT(1) NOT NULL DEFAULT \'1\',
UNIQUE KEY `changeID` (`changeID`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1');
// Blog Categories Table
$this->db->query('CREATE TABLE IF NOT EXISTS `blog_categories` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(25) NOT NULL,
`display_name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `blog_categories_name_display_name_uindex` (`name`,`display_name`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=latin1');
// Blog Comments Table
$this->db->query('CREATE TABLE IF NOT EXISTS `blog_comments` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`post_id` INT(11) NOT NULL,
`user_id` INT(11) NOT NULL,
`comment` TEXT NOT NULL,
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`like_count` INT(11) NOT NULL,
`reply` TINYINT(1) NOT NULL DEFAULT \'0\',
`replyTo_id` INT(11) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1');
// Blog Content Table
$this->db->query('CREATE TABLE IF NOT EXISTS `blog_content` (
`contentID` INT(11) NOT NULL AUTO_INCREMENT,
`postID` INT(11) NOT NULL,
`contentDate` DATETIME NOT NULL,
`content` MEDIUMTEXT NOT NULL,
`contentAuthorID` INT(11) DEFAULT NULL,
`isNativePost` TINYINT(1) NOT NULL,
`isActive` TINYINT(1) NOT NULL,
`versionMessage` VARCHAR(300) NOT NULL,
`language` VARCHAR(10) DEFAULT NULL,
PRIMARY KEY (`contentID`)
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=latin1');
// Blog Posts Table
$this->db->query('CREATE TABLE IF NOT EXISTS `blog_posts` (
`postID` INT(11) NOT NULL AUTO_INCREMENT,
`postUrl` VARCHAR(300) NOT NULL,
`postTitle` VARCHAR(255) DEFAULT NULL,
`postDesc` TEXT,
`postPublishDate` DATETIME DEFAULT NULL,
`postLastEdit` DATETIME DEFAULT NULL,
`postAuthorID` INT(11) DEFAULT NULL,
`postImage` TEXT NOT NULL,
`postState` VARCHAR(50) NOT NULL,
`postViews` INT(11) NOT NULL DEFAULT \'0\',
`postCategoryID` INT(11) NOT NULL,
`postIsDeleted` TINYINT(1) NOT NULL DEFAULT \'0\',
`postDeletedDate` DATETIME DEFAULT NULL,
PRIMARY KEY (`postID`)
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=latin1');
// Blog Post Likes Table
$this->db->query('CREATE TABLE IF NOT EXISTS `blog_post_likes` (
`post_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`post_id`,`user_id`),
KEY `fk_post_likes_user` (`user_id`),
CONSTRAINT `fk_post_likes_post` FOREIGN KEY (`post_id`) REFERENCES `blog_posts` (`postID`),
CONSTRAINT `fk_post_likes_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1');
// Blog Post Tags Table
$this->db->query('CREATE TABLE IF NOT EXISTS `blog_post_tags` (
`post_id` INT(11) NOT NULL,
`tag_id` INT(11) NOT NULL,
PRIMARY KEY (`post_id`,`tag_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1');
// Blog States Table
$this->db->query('CREATE TABLE IF NOT EXISTS `blog_states` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(15) NOT NULL,
`display_name` VARCHAR(15) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1');
// Blog Tags Table
$this->db->query('CREATE TABLE IF NOT EXISTS `blog_tags` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(25) NOT NULL,
`display_name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=latin1');
// Blog Translations Table
$this->db->query('CREATE TABLE IF NOT EXISTS `blog_translations` (
`postID` INT(11) DEFAULT NULL,
`language` VARCHAR(10) DEFAULT \'en\',
`postTitle` VARCHAR(255) DEFAULT NULL,
`postDesc` TEXT,
UNIQUE KEY `blog_translations_language_uindex` (`language`),
UNIQUE KEY `blog_translations_postID_uindex` (`postID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1');
// Collections Table
$this->db->query('CREATE TABLE IF NOT EXISTS `collections` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`collection` TEXT NOT NULL,
`displayname` TEXT NOT NULL,
`displaynameEnglish` TEXT NOT NULL,
`displaynameFrench` TEXT NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1');
// Portfolio Table
$this->db->query('CREATE TABLE IF NOT EXISTS `portfolio` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`datetime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`source` TEXT NOT NULL,
`isDownloadable` TINYINT(1) NOT NULL DEFAULT \'0\',
`isOpenSource` TINYINT(1) NOT NULL DEFAULT \'0\',
`title` TEXT NOT NULL,
`titleEnglish` TEXT NOT NULL,
`titleFrench` TEXT NOT NULL,
`headline` TEXT NOT NULL,
`headlineEnglish` TEXT NOT NULL,
`headlineFrench` TEXT NOT NULL,
`description` TEXT NOT NULL,
`descriptionEnglish` TEXT NOT NULL,
`descriptionFrench` TEXT NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=latin1');
// Project Categories Table
$this->db->query('CREATE TABLE IF NOT EXISTS `project_categories` (
`projectID` INT(11) NOT NULL,
`categoryID` INT(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1');
// Social Posts Table
$this->db->query('CREATE TABLE IF NOT EXISTS `social_posts` (
`post_id` INT(11) NOT NULL AUTO_INCREMENT,
`post_plattform` VARCHAR(20) NOT NULL,
`post_content` TEXT NOT NULL,
`post_url` VARCHAR(75) NOT NULL,
`post_author` VARCHAR(20) NOT NULL,
`post_author_url` TEXT NOT NULL,
`post_date` INT(11) NOT NULL,
`post_img_source` TEXT,
`post_original_id` BIGINT(20) NOT NULL,
PRIMARY KEY (`post_id`),
UNIQUE KEY `post_url` (`post_url`)
) ENGINE=InnoDB AUTO_INCREMENT=5474 DEFAULT CHARSET=latin1');
}
public function fillBlogDb() {
if($this->db->query('SELECT COUNT(*) count FROM blog_categories')->result_array()[0]['count'] == 0) {
$this->db->query("INSERT INTO `blog_categories` (`ID`, `name`, `display_name`) VALUES
(1, 'design', 'Design'),
(2, 'development', 'Entwicklung & Programmierung'),
(3, 'internet', 'Internet'),
(4, 'minepoint', 'MinePoint'),
(5, 'social_media', 'Soziale Medien'),
(6, 'technic', 'Technik'),
(7, 'youtube', 'YouTube')");
}
if($this->db->query('SELECT COUNT(*) count FROM blog_states')->result_array()[0]['count'] == 0) {
$this->db->query("INSERT INTO `blog_states` (`ID`, `name`, `display_name`) VALUES
(1, 'published', 'Veröffentlicht'),
(2, 'draft', 'Entwurf'),
(3, 'pending', 'Geplant'),
(4, 'trashbin', 'Im Papierkorb')");
}
if($this->db->query('SELECT COUNT(*) count FROM blog_tags')->result_array()[0]['count'] == 0) {
$this->db->query("INSERT INTO `blog_tags` (`ID`, `name`, `display_name`) VALUES
(1, 'youtube', 'YouTube'),
(2, 'twitter', 'Twitter'),
(3, 'smartphones', 'Smartphones'),
(4, 'coding', 'Programmieren'),
(5, 'development', 'Entwicklung'),
(6, 'design', 'Design'),
(7, 'adobe', 'Adobe'),
(8, '3d', '3D'),
(9, 'ux', 'User Experience'),
(10, 'ui', 'User Interface'),
(11, 'design-thinking', 'Thinking on Design'),
(12, 'games', 'Spiele'),
(13, 'hardware', 'Hardware'),
(14, 'software', 'Software'),
(15, 'photography', 'Fotografie'),
(16, 'videos', 'Videos & Filmen'),
(17, 'learning', 'Lernen'),
(28, '', ''),
(29, 'test', 'test'),
(30, 'kacke', 'kacke'),
(31, 'asdfla', 'asdfla'),
(32, 'admin', 'Admin'),
(33, 'tset', 'tset'),
(34, 'programmiersprachen', 'Programmiersprachen'),
(35, 'sprachen', 'Sprachen'),
(36, 'serie', 'Serie'),
(37, 'kanal', 'Kanal'),
(38, 'neu', 'Neu'),
(39, 'kingofdog', 'KingOfDog'),
(40, 'entwicklung', 'Entwicklung'),
(41, 'programmierung', 'Programmierung'),
(42, 'webseite', 'Webseite'),
(43, 'posts', 'Posts'),
(44, 'post', 'Post'),
(45, 'system', 'System'),
(46, 'nutzer', 'Nutzer'),
(47, 'user', 'User'),
(48, 'php', 'PHP')");
}
}
public function fillMainDb() {
if($this->db->query('SELECT COUNT(*) count FROM redirects')->result_array()[0]['count'] == 0) {
$this->db->query("INSERT INTO `redirects` (`ID`, `date`, `redirect`, `url`, `temporary`, `expireDate`) VALUES
(1, '2016-10-15 18:09:51', 'yt', 'http://youtube.com/KingOfDog', 0, '0000-00-00 00:00:00'),
(2, '2016-10-15 18:10:13', 'youtube', 'http://youtube.com/KingOfDog', 0, '0000-00-00 00:00:00'),
(3, '2016-10-15 18:10:27', 'tw', 'http://twitter.com/KingOfDogTV', 0, '0000-00-00 00:00:00'),
(4, '2016-10-15 18:10:37', 'twitter', 'http://twitter.com/KingOfDogTV', 0, '0000-00-00 00:00:00')");
}
}
public function fillPortfolioDb() {
if($this->db->query('SELECT COUNT(*) count FROM projects_categories')->result_array()[0]['count'] == 0) {
$this->db->query("INSERT INTO `projects_categories` (`ID`, `collection`, `displayname`, `displaynameEnglish`, `displaynameFrench`) VALUES
(1, 'banner', 'Banner', 'Banner', 'Bannière'),
(2, 'fotografie', 'Fotografie', 'Photography', 'Photographie'),
(3, 'minecraft', 'Minecraft', 'Minecraft', 'Minecraft'),
(4, 'websites', 'Webseiten', 'Websites', 'Sites'),
(5, 'logo', 'Logo', 'Logo', 'Logo'),
(6, 'development', 'Programmierung', 'Development', ''),
(7, 'games', 'Spiele', 'Games', ''),
(8, 'design', 'Design', 'Design', 'Design')");
}
}
}

View File

@@ -0,0 +1,96 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Coduo\PHPHumanizer\NumberHumanizer;
class FileModel extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function uploadFile($original_name, $tmpname, $size, $type)
{
$target_dir = "files" . DIRECTORY_SEPARATOR;
$filetype = pathinfo(basename($original_name), PATHINFO_EXTENSION);
$target_file = $target_dir . $this->generateName() . '.' . $filetype;
$name = explode('.' . $filetype, explode(DIRECTORY_SEPARATOR, $target_file)[1])[0];
if (!move_uploaded_file($tmpname, $target_file)) {
die('File couldn\'t be uploaded!');
}
$this->db->query('INSERT INTO files (name, original_name, type, size, path) VALUES (?, ?, ?, ?, ?)', [$name, $original_name, $type, $size, $target_file]);
return "/file/open/" . $name;
}
public function uploadImage($name, $max_size, $originalname, $max_width) {
$config['upload_path'] = './files/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = $max_size;
$config['file_name'] = $this->generateName() . "." . pathinfo(basename($originalname), PATHINFO_EXTENSION);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($name)) {
return null;
} else {
$data = $this->upload->data();
// Resize
$config['image_library'] = 'gd2';
$config['source_image'] = $data['full_path'];
$config['maintain_ratio'] = TRUE;
$config['width'] = $max_width;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$this->db->query('INSERT INTO files (name, original_name, type, size, path) VALUES (?, ?, ?, ?, ?)', [$data['raw_name'], $originalname, $data['file_type'], $data['file_size'] * 1024, 'files/' . $data['file_name']]);
return '/f/' . $data['raw_name'];
}
}
public function uploadFileByContent($content, $original_name, $fullType, $fileSize) {
$target_dir = "files" . DIRECTORY_SEPARATOR;
$filetype = pathinfo(basename($original_name), PATHINFO_EXTENSION);
$target_file = $target_dir . $this->generateName() . '.' . $filetype;
$name = explode('.' . $filetype, explode(DIRECTORY_SEPARATOR, $target_file)[1])[0];
$fp = fopen($target_file, 'w');
fwrite($fp, $content);
fclose($fp);
$this->db->query('INSERT INTO files (name, original_name, type, size, path) VALUES (?, ?, ?, ?, ?)', [$name, $original_name, $fullType, $fileSize, $target_file]);
return '/f/' . $name;
}
public function generateName()
{
return md5(uniqid(rand(), true));
}
public function getFileList()
{
$unfiltered_result = $this->db->query('SELECT * FROM files')->result_array();
$result = [];
foreach ($unfiltered_result as $item) {
$item['size'] = NumberHumanizer::binarySuffix(intval($item['size']), $_SESSION['site_lang']);
$result[] = $item;
}
return $result;
}
public function delete($id) {
$filePath = $this->db->query('SELECT path FROM files WHERE ID = ? LIMIT 1', [$id])->result_array()[0];
unlink($filePath['path']);
$this->db->query('DELETE FROM files WHERE ID = ? LIMIT 1', [$id]);
}
}

View File

@@ -0,0 +1,62 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Coduo\PHPHumanizer\DateTimeHumanizer;
class GeneralModel extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->model('BlogModel', '', TRUE);
$this->load->model('NotificationModel', '', TRUE);
}
function getBlogPosts($count)
{
$posts = $this->BlogModel->getMostRecentPosts($count);
$return = '';
foreach($posts as $result) {
$date = strtotime($result['postPublishDate']);
$return .= '<div class="media">
<div class="pull-left">
<img src="' . $result['postImage'] . '?w=100" style="max-width:100px" class="img-fluid">
</div>
<div class="media-body">
<span class="media-heading"><a href="#">' . $result['postTitle'] . '</a></span>
<small class="muted">' . lang('footer_published') . ' ' . DateTimeHumanizer::difference(new \DateTime(), new \DateTime("@$date"), $_SESSION['site_lang']) . '</small>
</div>
</div>';
}
return $return;
}
function addFeedbackAnonymously($pageUrl, $message) {
$this->addFeedback($pageUrl, $message, true, NULL, NULL);
}
function addFeedback($pageUrl, $message, $anonymous, $userID, $email) {
$this->db->query('INSERT INTO feedback (page, message, anonymous, userID, email) VALUES (?, ?, ?, ?, ?)', [$pageUrl, $message, $anonymous, $userID, $email]);
$this->db->cache_delete('admin', 'feedback');
// Send notifications
$this->NotificationModel->rankNotificationNewFeedback($userID != NULL ? $userID : -1, 9, $pageUrl);
}
function getRankName($rankID) {
$ranks = [
0 => "Nutzer",
1 => "Registrierter Nutzer",
2 => "Premium-Nutzer",
3 => "Plus-Nutzer",
6 => "Autor (Blog)",
7 => "Editor (Blog)",
8 => "Moderator",
9 => "Admin",
10 => "Admin"
];
return isset($ranks[$rankID]) ? $ranks[$rankID] : "Nutzer";
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,35 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MessageModel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function getFeedbackMessages() {
return $this->db->query('SELECT feedback.*, feedback_states.name feedbackStateName, feedback_states.displayname feedbackStateDisplayname, users.username username, users.displayname userDisplayname, supporter.username supporterUsername, supporter.displayname supporterDisplayname FROM feedback LEFT JOIN feedback_states ON feedback.feedbackState = feedback_states.ID LEFT JOIN users ON feedback.userID = users.ID LEFT JOIN users supporter ON feedback.supporterID = supporter.ID ORDER BY feedbackState ASC, datetime DESC')->result_array();
}
public function setFeedbackSupporter($feedbackID, $userID, $feedbackState = 1) {
if($feedbackState == 0)
$feedbackState = 1;
$this->db->query('UPDATE feedback SET feedbackState = ?, supporterID = ?, lastStateUpdate = NOW() WHERE ID = ?', [$feedbackState, $userID, $feedbackID]);
}
public function updateState($feedbackID, $userID, $feedbackState) {
$this->db->query('UPDATE feedback SET feedbackState = (SELECT ID FROM feedback_states WHERE name = ?), lastStateUpdate = NOW() WHERE ID = ? AND supporterID = ?', [$feedbackState, $feedbackID, $userID]);
}
public function archiveFeedback($feedbackID) {
$data = $this->db->query('SELECT * FROM feedback WHERE ID = ? AND feedbackState >= 10', [$feedbackID])->result_array();
if(!empty($data)) {
$this->db->query('INSERT INTO feedback_archive (ID, page, message, datetime, anonymous, userID, email, feedbackState, feedbackStatusMessage, supporterID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', $data[0]);
}
return !empty($data);
}
}

View File

@@ -0,0 +1,101 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MinecraftModel extends CI_Model {
public function __construct() {
parent::__construct();
}
public function getUUID($username) {
$json = json_decode(@file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . $username));
if(empty($json)) {
return ["Nicht vorhanden", $username, true];
} else {
$uuid = $json->id;
$name = $json->name;
return [$uuid, $name, false];
}
}
public function getIcon($user) {
return "https://crafatar.com/avatars/" . $user . "?overlay&size=64&default=MHF_Alex";
}
public function getRender($user) {
return "https://crafatar.com/renders/body/" . $user . "?overlay&scale=7&default=MHF_Alex";
}
public function serverIcon($server) {
return "https://craftapi.com/api/server/favicon/" . $server;
}
public function getServerName($server) {
$json = json_decode(@file_get_contents('https://craftapi.com/api/server/info/' . $server));
if(!empty($json->error) || empty($json)) {
return lang('servers_error_ip');
} else {
return $json->server;
}
}
public function getPlayers($server) {
$json = json_decode(@file_get_contents('https://craftapi.com/api/server/info/' . $server));
if (!empty($json->error)) {
return lang('servers_error');
} else {
$online = $json->players->online;
$max = $json->players->max;
$ping = floatval($json->latency) * 1000;
$version = $json->version->name;
if($online < $max) {
$color = "#00AA00";
} else {
$color = "#FFAA00";
}
return [$online, $max, $color, $ping, $version];
}
}
public function getMOTD($server) {
$json = json_decode(@file_get_contents('https://craftapi.com/api/server/info/' . $server));
if(!empty($json->error) || empty($json)) {
return lang('servers_error');
} else {
return $json->motd;
}
}
public function getHistory($uuid) {
$json = json_decode(@file_get_contents('https://craftapi.com/api/user/namehistory/' . $uuid));
$return = '';
if(!empty($json)) {
foreach($json as $element) {
$name = $element->name;
if(!empty($element->changedToAt)) {
$milliseconds = floatval($element->changedToAt);
$date = date("d.m.Y \u\m H:i:s", $milliseconds/1000);
$changedtoat = $date . " Uhr";
} else {
$changedtoat = "<i>" . lang('player_original_name') . "</i>";
}
$return .= "<tr><td>" . $name . "</td><td>" . $changedtoat . "</td></tr>";
}
return $return;
} else {
return null;
}
}
public function formatUUID($uuid) {
$return = $uuid;
$return = substr_replace($return, '-' . $uuid[8], 8, -23);
$return = substr_replace($return, '-' . $uuid[12], 13, -19);
$return = substr_replace($return, '-' . $uuid[16], 18, -15);
$return = substr_replace($return, '-' . $uuid[20], 23, -11);
return $return;
}
}

View File

@@ -0,0 +1,105 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class NicknameModel extends CI_Model {
public function __construct() {
parent::__construct();
}
function generateMarkovTable($names = [])
{
$table = [];
foreach ($names as $name) {
$letters = str_split($name);
foreach ($letters as $key => $letter) {
$letter = strtolower($letter);
if (!array_key_exists($key + 1, $letters)) {
continue;
}
$nextLetter = strtolower($letters[$key + 1]);
if (!(array_key_exists($letter, $table) && array_key_exists($nextLetter, $table[$letter]))) {
$table[$letter][$nextLetter] = 1;
continue;
}
$table[$letter][$nextLetter] = $table[$letter][$nextLetter] + 1;
}
}
return $table;
}
function generateMarkovName($table, $minLength = 3, $maxLength = 10)
{
$currentLetter = array_rand($table);
$text = [$currentLetter];
$length = mt_rand($minLength, $maxLength);
for ($i = 0; $i < $length; $i++) {
$nextLetter = $this->getRandomWeightedElement($currentLetter, $table);
if (count($text) > 1) {
$previousLetter = $text[$i - 1];
while ($previousLetter == $nextLetter) {
$nextLetter = $this->getRandomWeightedElement($currentLetter, $table);
}
}
$text[] = $nextLetter;
$currentLetter = $nextLetter;
}
return ucfirst(implode('', $text));
}
function getRandomWeightedElement($key, array $table)
{
if (array_key_exists($key, $table)) {
$weightedValues = $table[$key];
$rand = mt_rand(1, (int) array_sum($weightedValues));
foreach ($weightedValues as $key => $value) {
$rand -= $value;
if ($rand <= 0) {
return $key;
}
}
}
return array_rand($table);
}
public function generateName() {
$names = [
'Gronkh',
'Currywurst',
'KingOfDog',
'Zeybe',
'unge',
'Dner',
'Arazhul',
'Hopson',
'Carykh',
'Benx',
'Demaster',
'Manucraft',
'Minecraft',
'ProPlayer91',
'Green',
'Blue',
'Red',
'Ultra',
'Pro',
'Racing',
'Shooter',
'King',
'Yellow',
'Gold',
'xXXx',
'iTz_',
'Running',
'YT',
'TV',
'HD',
'Huge',
'Best',
'imFlying',
'Not'
];
$table = $this->generateMarkovTable($names);
echo str_pad($this->generateMarkovName($table, 4, 7), 12);
}
}

View File

@@ -0,0 +1,211 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once 'notifications/NotificationGroup.php';
require_once 'notifications/NewFollowerNotification.php';
require_once 'notifications/PostLikeNotification.php';
require_once 'notifications/UserRegisteredNotification.php';
require_once 'notifications/PostMentionNotification.php';
require_once 'notifications/PostReplyNotification.php';
require_once 'notifications/PostReportNotification.php';
require_once 'notifications/NotificationUser.php';
require_once 'notifications/NewFeedbackNotification.php';
class NotificationModel extends CI_Model
{
public function __construct()
{
parent::__construct();
$lang = isset($_SESSION['site_lang']) ? $_SESSION['site_lang'] : 'de';
$_SESSION['site_lang'] = $lang;
$this->lang->load('notification', 'de');
$this->lang->load('notification', $_SESSION['site_lang']);
}
public function getUserNotificationsRaw($userID, $limit = 20, $offset = 0)
{
$this->db->cache_off();
$rawData = $this->db->query('SELECT n.*, count(*) count, s.username senderName, s.displayname senderDisplayname, s.profile_picture senderPicture, r.username recipientName, r.displayName recipientDisplayname FROM notifications n LEFT JOIN users s ON n.senderID = s.ID LEFT JOIN users r ON n.recipientID = r.ID WHERE recipientID = ? GROUP BY type, referenceID ORDER BY createdAt DESC, unread DESC LIMIT ? OFFSET ?', [$userID, $limit, $offset])->result_array();
$notifications = [];
foreach ($rawData as $notification) {
$notificationGroup = ['count' => $notification['count']];
if ($notificationGroup['count'] == 1) {
$notificationGroup['items'] = [$notification];
} else {
$notificationGroup['items'] = $this->db->query('SELECT n.*, s.username senderName, s.displayname senderDisplayname, s.profile_picture senderPicture, r.username recipientName, r.displayName recipientDisplayname FROM notifications n LEFT JOIN users s ON n.senderID = s.ID LEFT JOIN users r ON n.recipientID = r.ID WHERE recipientID = ? AND type = ? AND referenceID = ? LIMIT 5', [$userID, $notification['type'], $notification['referenceID']])->result_array();
}
$notifications[] = $notificationGroup;
}
$this->db->cache_on();
return $notifications;
}
public function getUserNotifications($userID, $limit = 20, $offset = 0)
{
$result = [];
foreach ($notifications = $this->get($userID, $limit, $offset) as $group) {
$date = strtotime($group->createdAt);
$messageData = $group->message();
$result[] = [
'sender' => $group->sender->getName(),
'unread' => $group->unread,
'message' => sprintf(lang($messageData['line']), ...$messageData['attributes']),
'link' => base_url($group->getNotificationLink()),
'image' => base_url($group->getNotificationImage()),
'time' => \Coduo\PHPHumanizer\DateTimeHumanizer::difference(new \DateTime(), new \DateTime("@$date"), $_SESSION['site_lang'])
];
}
return $result;
// Mark as read
}
private function add(Notification $notification) {
$results = $this->db->query('SELECT * FROM notifications WHERE referenceID = ? AND recipientID = ? AND senderID = ? AND type = ? AND parameters = ?', [$notification->referenceID, $notification->recipient->getID(), $notification->sender->getID(), $notification->type, $notification->parameters])->result_array();
if(empty($results)) {
$this->db->insert('notifications', [
'recipientID' => $notification->recipient->getID(),
'senderID' => $notification->sender->getID(),
'unread' => 1,
'type' => $notification->type,
'parameters' => $notification->parameters,
'referenceID' => $notification->referenceID,
'createdAt' => date('Y-m-d H:i:s', time())
]);
}
$this->db->cache_delete('Main', 'getNotifications');
}
public function markAsRead(array $notifications) {
}
public function markUserNotificationsAsRead($userID) {
$this->db->query('UPDATE notifications SET unread = FALSE WHERE recipientID = ?', [$userID]);
}
public function get($userID, $limit = 20, $offset = 0) {
$groups = [];
$results = $this->getUserNotificationsRaw($userID, $limit, $offset);
foreach ($results as $group) {
$items = [];
foreach ($group['items'] as $item) {
switch ($item['type']) {
case 'users.newFollower':
$items[] = new \Notification\Users\NewFollowerNotification($item);
break;
case 'users.likedPost':
$items[] = new \Notification\Users\PostLikeNotification($item);
break;
case 'users.mentionedPost':
$items[] = new \Notification\Users\PostMentionNotification($item);
break;
case 'users.repliedPost':
$items[] = new \Notification\Users\PostReplyNotification($item);
break;
case 'admin.newUserRegistered':
$items[] = new \Notification\Admin\UserRegisteredNotification($item);
break;
case 'admin.feedback':
$items[] = new \Notification\Admin\NewFeedbackNotification($item);
break;
}
}
$groups[] = new NotificationGroup($items, $group['count']);
}
return $groups;
}
public function removeNotification($senderID, $recipientID, $referenceID, $type)
{
$this->db->query('DELETE FROM notifications WHERE senderID = ? AND recipientID = ? AND referenceID = ? AND type = ?', [$senderID, $recipientID, $referenceID, $type]);
$this->db->cache_delete('Main', 'getNotifications');
}
public function userNotificationNewFollower($senderID, $recipientID) {
$notification = new \Notification\Users\NewFollowerNotification([
'senderID' => $senderID,
'recipientID' => $recipientID,
'referenceID' => $recipientID
]);
$this->add($notification);
}
public function userNotificationPostLike($senderID, $recipientID, $postID, $postUuid) {
$notification = new \Notification\Users\PostLikeNotification([
'senderID' => $senderID,
'recipientID' => $recipientID,
'referenceID' => $postID,
'parameters' => $postUuid
]);
$this->add($notification);
}
public function userNotificationPostMentioned($senderID, $recipientID, $postID, $postUuid) {
$notification = new \Notification\Users\PostMentionNotification([
'senderID' => $senderID,
'recipientID' => $recipientID,
'referenceID' => $postID,
'parameters' => $postUuid
]);
$this->add($notification);
}
public function userNotificationPostReply($senderID, $recipientID, $postID, $postUuid) {
$notification = new \Notification\Users\PostReplyNotification([
'senderID' => $senderID,
'recipientID' => $recipientID,
'referenceID' => $postID,
'parameters' => $postUuid
]);
$this->add($notification);
}
public function rankNotificationNewUserRegistered($senderID, $rankRecipientID) {
$rankUsers = $this->db->query('SELECT ID FROM users WHERE rank >= ?', [$rankRecipientID])->result_array();
foreach ($rankUsers as $user) {
$notification = new \Notification\Admin\UserRegisteredNotification([
'senderID' => $senderID,
'recipientID' => $user['ID'],
'referenceID' => $senderID,
]);
$this->add($notification);
}
}
public function rankNotificationNewFeedback($senderID, $rankRecipientID, $pageName) {
$rankUsers = $this->db->query('SELECT ID FROM users WHERE rank >= ?', [$rankRecipientID])->result_array();
foreach ($rankUsers as $user) {
$notification = new \Notification\Admin\NewFeedbackNotification([
'senderID' => $senderID,
'recipientID' => $user['ID'],
'referenceID' => base_convert(md5($pageName), 16, 10) % 9999
]);
$this->add($notification);
}
}
public function rankNotificationPostReport($senderID, $rankRecipientID, $postID, $postUUID) {
$rankUsers = $this->db->query('SELECT ID FROM users WHERE rank >= ?', [$rankRecipientID])->result_array();
foreach ($rankUsers as $user) {
$notification = new \Notification\Users\PostReportNotification([
'senderID' => $senderID,
'recipientID' => $user['ID'],
'referenceID' => $postID,
'parameters' => $postUUID
]);
$this->add($notification);
}
}
}

View File

@@ -0,0 +1,378 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class PostsModel extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->model('UserModel', '', TRUE);
$this->load->model('NotificationModel', '', TRUE);
}
function addPost($userID, $content)
{
return $this->addReply($userID, $content, NULL);
}
public function addReply($userID, $content, $replyToUUID)
{
$content = $this->preparePostContent($content);
$uuid = $this->generatePostUUID($userID, $content);
$replyTo = NULL;
if ($replyToUUID !== NULL) {
$replyToID = $this->db->query('SELECT ID FROM user_posts WHERE uuid = ?', [$replyToUUID])->result_array();
$replyTo = !empty($replyToID) ? $replyToID[0]['ID'] : NULL;
}
$this->db->query('INSERT INTO user_posts (user_id, content, uuid, reply_to) VALUES (?, ?, ?, ?)', [$userID, $content, $uuid, $replyTo]);
$insertedPost = $this->db->query('SELECT ID, user_id FROM user_posts WHERE uuid = ?', [$uuid])->result_array();
$this->addPostMentions($insertedPost[0]['ID'], $content, $uuid);
$this->addPostHashtags($insertedPost[0]['ID'], $content);
// Send notification to user whose post was replied to
if ($userID != $insertedPost[0]['user_id']) {
$this->NotificationModel->userNotificationPostReply($userID, $insertedPost[0]['user_id'], $insertedPost[0]['ID'], $uuid);
}
return $insertedPost[0]['ID'];
}
public function addImageToPost($postID, $imageUrl) {
$this->db->query('INSERT INTO user_posts_media (postID, mediaType, mediaUrl) VALUES (?, ?, ?)', [$postID, 'image', $imageUrl]);
}
public function preparePostContent($content)
{
if ($this->endsWith($content, '<br>&nbsp;')) {
$content = substr($content, 0, strlen($content) - 10);
}
$content = htmlspecialchars($content);
return $content;
}
function endsWith($haystack, $needle)
{
$length = strlen($needle);
return $length === 0 ||
(substr($haystack, -$length) === $needle);
}
function generatePostUUID($userID, $content)
{
return md5($userID . $content . date("Y-m-d H:i:s"));
}
public function addPostMentions($postID, $content, $postUUID)
{
preg_match_all('/@([A-Za-z0-9._]+)/', $content, $mentions, PREG_OFFSET_CAPTURE);
foreach ($mentions[1] as $mention) {
$mentionedUser = $this->UserModel->getUserIDByUsername(strtolower($mention[0]));
if ($mentionedUser == null) {
continue;
}
$mentionedUser = $mentionedUser[0];
$this->addMention($postID, $_SESSION['user']['ID'], $mentionedUser['ID'], $mention[1], $postUUID);
}
}
public function addMention($postID, $userID, $mentionedUserID, $position, $postUUID)
{
$this->db->query('INSERT INTO user_posts_mentions (userID, postID, mentionedUserID, position) VALUES (?, ?, ?, ?)', [$userID, $postID, $mentionedUserID, $position]);
// Send notification
$this->NotificationModel->userNotificationPostMentioned($userID, $mentionedUserID, $postID, $postUUID);
}
public function addPostHashtags($postID, $content)
{
preg_match_all('/#([A-Za-z0-9]+)/', $content, $hashtags, PREG_OFFSET_CAPTURE);
foreach ($hashtags[1] as $hashtag) {
$this->addHashtag($postID, $_SESSION['user']['ID'], $hashtag[0], $hashtag[1]);
}
}
public function addHashtag($postID, $userID, $hashtag, $position)
{
$this->db->query('INSERT INTO user_posts_hashtags (userID, postID, hashtag, position) VALUES (?, ?, ?, ?)', [$userID, $postID, $hashtag, $position]);
}
function getUserPosts($id, $count, $offset, $maxLength = 250)
{
$this->db->cache_off();
$posts = $this->db->query('SELECT * FROM user_posts p WHERE user_id = ? ORDER BY date DESC LIMIT ? OFFSET ?', [$id, $count, $offset])->result_array();
$this->db->cache_on();
$posts = $this->preparePostList($posts, $maxLength);
return $posts;
}
public function preparePostList($postList, $maxLength = 250)
{
foreach ($postList as $i => $post) {
$post = $this->mergePostUserData($post);
$post['replyCount'] = $this->getPostReplyCountByID($post['ID']);
$post['likeCount'] = $this->getPostLikeCountByID($post['ID']);
if ($maxLength > 0) {
$post['content'] = strlen($post['content']) > $maxLength ? substr($post['content'], 0, $maxLength) . '...' : $post['content'];
}
$post['content'] = $this->mergePostMentionsHashtags($post['ID'], $post['content']);
$post['media'] = $this->getPostMedia($post['ID']);
if (isset($_SESSION['user']) && !empty($_SESSION['user'])) {
$post = $this->mergeUserHasLiked($post, $_SESSION['user']['ID']);
}
if($post['reply_to'] != NULL) {
$post = $this->mergeReplyData($post);
}
$postList[$i] = $post;
}
$postList = $this->UserModel->setDefaultImages($postList);
return $postList;
}
public function getPostMedia($postID) {
$result = $this->db->query('SELECT * FROM user_posts_media WHERE postID = ?', [$postID])->result_array();
return $result;
}
private function mergePostUserData($post)
{
$user = $this->UserModel->getUserByID($post['user_id']);
$user = $user[0];
$post['username'] = $user['username'];
$post['displayname'] = $user['displayname'];
$post['profile_picture'] = $user['profile_picture'];
return $post;
}
public function getPostReplyCountByID($postID)
{
$this->db->cache_off();
$data = $this->db->query('SELECT count(*) replyCount FROM user_posts WHERE reply_to = ?', [$postID])->result_array();
$this->db->cache_on();
return $data[0]['replyCount'];
}
public function getPostLikeCountByID($id)
{
$this->db->cache_off();
$data = $this->db->query('SELECT count(*) likeCount FROM user_posts_likes WHERE postID = ?', [$id])->result_array();
$this->db->cache_on();
return $data[0]['likeCount'];
}
private function mergePostMentionsHashtags($postID, $content)
{
$mentions = $this->db->query('SELECT m.*, u.username, u.displayname FROM user_posts_mentions m LEFT JOIN users u ON m.mentionedUserID = u.ID WHERE postID = ?', [$postID])->result_array();
$hashtags = $this->db->query('SELECT * FROM user_posts_hashtags WHERE postID = ?', [$postID])->result_array();
$links = array_merge($mentions, $hashtags);
usort($links, function ($a, $b) {
return $a['position'] - $b['position'];
});
$finalContent = '';
$prevPos = 0;
foreach ($links as $link) {
$finalContent .= substr($content, $prevPos, $link['position'] - $prevPos - 1);
if (isset($link['username'])) { // Is link a mention?
$finalContent .= '<a href="' . base_url('user/' . $link['username']) . '">@' . $link['displayname'] . '</a>';
$prevPos = $link['position'] + strlen($link['username']);
} else { // Link is a hashtag
$finalContent .= '<a href="' . base_url('posts/search?q=%23' . $link['hashtag'] . '&type=type-posts') . '">#' . $link['hashtag'] . '</a>';
$prevPos = $link['position'] + strlen($link['hashtag']);
}
if ($prevPos > strlen($content)) {
break;
}
}
$finalContent .= substr($content, $prevPos, strlen($content) - $prevPos);
return $finalContent;
}
private function mergeUserHasLiked($post, $userID)
{
$this->db->cache_off();
$data = $this->db->query('SELECT * FROM user_posts_likes WHERE postID = (SELECT ID FROM user_posts WHERE uuid = ?) AND likerUserID = ?', [$post['uuid'], $userID])->result_array();
$this->db->cache_on();
if (empty($data)) {
$post['userHasLiked'] = FALSE;
} else {
$post['userHasLiked'] = TRUE;
}
return $post;
}
private function mergeReplyData($post) {
$data = $this->db->query('SELECT uuid, username, displayname FROM user_posts LEFT JOIN users ON users.ID = user_posts.user_id WHERE user_posts.ID = ?', [$post['reply_to']])->result_array();
$post['replyToUuid'] = $data[0]['uuid'];
$post['replyToUsername'] = $data[0]['username'];
$post['replyToDisplayname'] = $data[0]['displayname'];
return $post;
}
public function getNewestPosts($count, $maxLength = 250)
{
$this->db->cache_off();
$data = $this->db->query('SELECT * FROM user_posts ORDER BY date DESC LIMIT ?', [$count])->result_array();
$this->db->cache_on();
$data = $this->preparePostList($data, $maxLength);
return $data;
}
public function getFeedPosts($userID, $amount, $offset)
{
$this->db->cache_off();
$data = $this->db->query('SELECT * FROM user_posts WHERE user_id IN (SELECT followedUserID FROM user_followers WHERE followerUserID = ?) OR ID IN(SELECT postID FROM user_posts_mentions WHERE mentionedUserID = ?) OR ID IN (SELECT postID FROM user_posts_likes WHERE likedUserID = ?) OR user_id = ? ORDER BY date DESC LIMIT ? OFFSET ?', [$userID, $userID, $userID, $userID, $amount, $offset])->result_array();
$this->db->cache_on();
$data = $this->preparePostList($data);
return $data;
}
public function getPopularPosts($amount, $offset)
{
$this->db->cache_off();
$data = $this->db->query('SELECT * FROM user_posts p ORDER BY ((SELECT count(*) FROM user_posts_likes WHERE postID = p.ID) + (SELECT count(*) FROM user_posts WHERE reply_to = p.ID)) DESC, date DESC LIMIT ? OFFSET ?', [$amount, $offset])->result_array();
$this->db->cache_on();
$data = $this->preparePostList($data);
return $data;
}
public function getPostDetails($userID, $uuid)
{
$this->db->cache_off();
$data = $this->db->query('SELECT * FROM user_posts WHERE user_id = ? AND uuid = ?', [$userID, $uuid])->result_array();
$this->db->cache_on();
$data = $this->preparePostList($data);
return $data;
}
public function getPostReplies($postID)
{
$this->db->cache_off();
$replies = $this->db->query('SELECT * FROM user_posts WHERE reply_to = ? ORDER BY date', [$postID])->result_array();
$this->db->cache_on();
$replies = $this->preparePostList($replies);
return $replies;
}
public function getPostByUUID($uuid) {
$result = $this->db->query('SELECT * FROM user_posts WHERE uuid = ?', [$uuid])->result_array();
return $result;
}
public function addPostLikeByUUID($uuid, $userID)
{
$this->db->cache_off();
$data = $this->db->query('SELECT * FROM user_posts_likes WHERE postID = (SELECT ID FROM user_posts WHERE uuid = ?) AND likerUserID = ?', [$uuid, $userID])->result_array();
$this->db->cache_on();
// IDs needed for handling notifications later
$postUser = $this->db->query('SELECT ID FROM users WHERE ID = (SELECT user_id FROM user_posts WHERE uuid = ?)', [$uuid])->result_array();
$postID = $this->db->query('SELECT ID FROM user_posts WHERE uuid = ?', [$uuid])->result_array();
if (empty($data)) {
$this->db->query('INSERT INTO user_posts_likes (postID, likedUserID, likerUserID) VALUES ((SELECT ID FROM user_posts WHERE uuid = ?), (SELECT user_id FROM user_posts WHERE uuid = ?), ?)', [$uuid, $uuid, $userID]);
// Send like notification
if ($postUser[0]['ID'] != $userID) {
$this->NotificationModel->userNotificationPostLike($userID, $postUser[0]['ID'], $postID[0]['ID'], $uuid);
}
return true;
} else {
$this->db->query('DELETE FROM user_posts_likes WHERE postID = (SELECT ID FROM user_posts WHERE uuid = ?) AND likerUserID = ?', [$uuid, $userID]);
// Remove existing notification
$this->NotificationModel->removeNotification($userID, $postUser[0]['ID'], $postID[0]['ID'], 'users.likedPost');
return false;
}
}
public function getPostLikeCountByUUID($uuid)
{
$this->db->cache_off();
$data = $this->db->query('SELECT count(*) likeCount FROM user_posts_likes WHERE postID = (SELECT ID FROM user_posts WHERE uuid = ?)', [$uuid])->result_array();
$this->db->cache_on();
return $data[0]['likeCount'];
}
public function isUUIDValid($uuid)
{
$this->db->cache_off();
$data = $this->db->query('SELECT ID FROM user_posts WHERE uuid = ?', [$uuid])->result_array();
$this->db->cache_on();
return !empty($data);
}
public function closeTags($html)
{
preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
$openedtags = $result[1];
preg_match_all('#</([a-z]+)>#iU', $html, $result);
$closedtags = $result[1];
$len_opened = count($openedtags);
if (count($closedtags) == $len_opened) {
return $html;
}
$openedtags = array_reverse($openedtags);
for ($i = 0; $i < $len_opened; $i++) {
if (!in_array($openedtags[$i], $closedtags)) {
$html .= '</' . $openedtags[$i] . '>';
} else {
unset($closedtags[array_search($openedtags[$i], $closedtags)]);
}
}
return $html;
}
public function searchPosts($query, $limit = 20, $offset = 0)
{
$this->db->cache_off();
$results = $this->db->query('SELECT * FROM user_posts WHERE content RLIKE ? OR (SELECT username FROM users WHERE ID = user_id) RLIKE ? ORDER BY (SELECT count(*) FROM user_posts_likes WHERE postID = ID) DESC, (SELECT count(*) FROM user_posts WHERE user_posts.reply_to = ID) DESC, date DESC LIMIT ? OFFSET ?', [$query, $query, $limit, $offset])->result_array();
$this->db->cache_on();
$results = $this->preparePostList($results);
return $results;
}
public function reportPost($uuid, $reason, $reasonText) {
$this->db->query('INSERT INTO user_posts_reports (postID, reason, reasonText) VALUES ((SELECT ID FROM user_posts WHERE uuid = ?), ?, ?)', [$uuid, $reason, $reasonText]);
$this->db->cache_delete('admin', 'reports');
// Send notification
$postID = $this->db->query('SELECT ID FROM user_posts WHERE uuid = ?', [$uuid])->result_array();
$this->NotificationModel->rankNotificationPostReport(
isset($_SESSION['user']) ? $_SESSION['user']['ID'] : -1,
8, $postID[0]['ID'], $uuid);
}
}

View File

@@ -0,0 +1,207 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class ProjectsModel extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->model('projectsModel', '', TRUE);
}
public function getEntries($category) {
if($category !== 'all') {
$content = $this->db->query('SELECT *, (SELECT (SELECT COUNT(*) FROM projects_entry_votes WHERE projectID = p.ID AND type = 1) - (SELECT COUNT(*) FROM projects_entry_votes WHERE projectID = p.ID AND type = -1)) voteCount FROM projects p WHERE ID IN (SELECT projectID FROM projects_entry_categories WHERE categoryID = ?) ORDER BY datetime DESC', [$category])->result_array();
} else {
$content = $this->db->query('SELECT *, (SELECT (SELECT COUNT(*) FROM projects_entry_votes WHERE projectID = p.ID AND type = 1) - (SELECT COUNT(*) FROM projects_entry_votes WHERE projectID = p.ID AND type = -1)) voteCount FROM projects p ORDER BY datetime DESC')->result_array();
}
$content = $this->mergeTranslationData($content, $_SESSION['site_lang']);
return $content;
}
public function getCategories() {
$collections = $this->db->query('SELECT c.*, count(p.projectID) count FROM projects_categories c LEFT JOIN projects_entry_categories p ON c.ID = p.categoryID GROUP BY c.ID ORDER BY c.collection')->result_array();
return $collections;
}
public function editEntry($data, $id) {
$this->db->update('projects', $data, ['id' => $id]);
$this->db->cache_delete('projects', 'index');
$this->db->cache_delete('projects', 'entry');
$this->db->cache_delete('admin', 'projects');
}
public function addEntry($data) {
$this->db->insert('projects', $data);
$this->db->cache_delete('projects', 'index');
$this->db->cache_delete('admin', 'projects');
}
public function delete($id) {
$this->db->query('DELETE FROM projects WHERE ID = ? LIMIT 1', [$id]);
$this->db->cache_delete('projects', 'index');
$this->db->cache_delete('projects', 'entry');
$this->db->cache_delete('admin', 'projects');
}
public function deleteCategory($id) {
$this->db->query('DELETE FROM projects_entry_categories WHERE categoryID = ?', [$id]);
$this->db->query('DELETE FROM projects_categories WHERE ID = ? LIMIT 1', [$id]);
$this->db->cache_delete('projects', 'index');
$this->db->cache_delete('projects', 'entry');
$this->db->cache_delete('admin', 'projects');
}
public function checkIfExists($id) {
$result = $this->db->query('SELECT ID FROM projects WHERE ID = ? LIMIT 1', [$id])->result_array();
if(!empty($result)) {
return true;
} else {
return false;
}
}
public function checkIfNameExists($name) {
$result = $this->db->query('SELECT ID FROM projects WHERE name = ? LIMIT 1', [$name])->result_array();
if(!empty($result)) {
return true;
} else {
return false;
}
}
public function getEntry($id) {
return $this->db->query('SELECT * FROM projects WHERE ID = ? LIMIT 1', [$id])->result_array();
}
public function getEntryByName($name, $lang = 'de') {
$result = $this->db->query('SELECT * FROM projects WHERE name = ? LIMIT 1', [$name])->result_array();
$result = $this->mergeTranslationData($result, $lang);
return !empty($result) ? $result[0] : null;
}
public function getEntryCategories($id) {
return $this->db->query('SELECT * FROM projects_categories WHERE ID IN (SELECT categoryID FROM projects_entry_categories WHERE projectID = ?)', [$id])->result_array();
}
public function resetEntryCategories($postID) {
$this->db->query('DELETE FROM projects_entry_categories WHERE projectID = ?', $postID);
$this->db->cache_delete('projects', 'index');
$this->db->cache_delete('projects', 'entry');
$this->db->cache_delete('admin', 'projects');
}
public function addCategoryToEntryID($postID, $categoryID) {
$this->db->query('INSERT INTO projects_entry_categories (projectID, categoryID) VALUES (?, ?)', [$postID, $categoryID]);
$this->db->cache_delete('projects', 'index');
$this->db->cache_delete('projects', 'entry');
$this->db->cache_delete('admin', 'projects');
}
public function updateCategories($postID, $categories) {
$this->resetEntryCategories($postID);
foreach ($categories as $category) {
$this->addCategoryToEntryID($postID, $category);
}
}
public function addCategoryToEntryName($name, $categoryID) {
$id = $this->db->query('SELECT ID FROM projects WHERE name = ? LIMIT 1', [$name])->result_array()[0];
$this->addCategoryToEntryID(intval($id['ID']), $categoryID);
}
public function getPrevProject($id) {
$result = $this->db->query('SELECT * FROM projects WHERE datetime < (SELECT datetime FROM projects WHERE ID = ?) ORDER BY datetime DESC LIMIT 1', [$id])->result_array();
$result = $this->mergeTranslationData($result, $_SESSION['site_lang']);
return $result;
}
public function getNextProject($id) {
$result = $this->db->query('SELECT * FROM projects WHERE datetime > (SELECT datetime FROM projects WHERE ID = ?) ORDER BY datetime ASC LIMIT 1', [$id])->result_array();
$result = $this->mergeTranslationData($result, $_SESSION['site_lang']);
return $result;
}
public function addVote($projectID, $userID, $voteType) {
$this->db->query('DELETE FROM projects_entry_votes WHERE projectID = ? AND userID = ?', [$projectID, $userID]);
$this->db->query('INSERT INTO projects_entry_votes (projectID, userID, type) VALUES (?, ?, ?)', [$projectID, $userID, $voteType]);
$this->db->cache_delete('projects', 'index');
$this->db->cache_delete('projects', 'entry');
$this->db->cache_delete('projects', 'addVote');
$this->db->cache_delete('admin', 'projects');
}
public function getVoteCount($projectID) {
$result = $this->db->query('SELECT (SELECT COUNT(*) FROM projects_entry_votes WHERE projectID = ? AND type = 1) - (SELECT COUNT(*) FROM projects_entry_votes WHERE projectID = ? AND type = -1) voteCount', [$projectID, $projectID])->result_array();
return $result[0]['voteCount'];
}
public function getUserVoteType($projectID, $userID) {
$result = $this->db->query('SELECT type FROM projects_entry_votes WHERE projectID = ? AND userID = ?', [$projectID, $userID])->result_array();
if(empty($result))
return 0;
return $result[0]['type'];
}
public function createNewProjectDraft() {
$this->db->query('INSERT INTO projects () VALUES ()');
$this->db->cache_delete('admin', 'projects');
$data = $this->db->query('SELECT ID FROM projects ORDER BY ID DESC LIMIT 1')->result_array();
return $data[0]['ID'];
}
public function updateProject($id, $translations, $url, $download, $openSource, $customLink, $date, $image) {
$this->db->query('UPDATE projects SET name = ?, isDownloadable = ?, downloadLink = ?, isOpenSource = ?, openSourceLink = ?, customLink = ?, datetime = ?, source = ? WHERE ID = ?', [$url, $download['available'], $download['link'], $openSource['available'], $openSource['link'], $customLink['link'], $date, $image, $id]);
$this->db->cache_off();
foreach($translations as $lang => $translation) {
$data = $this->db->query('SELECT translationID FROM projects_translations WHERE projectID = ? AND lang = ?', [$id, $lang])->result_array();
if(empty($data)) {
$this->db->query('INSERT INTO projects_translations (projectID, lang) VALUES (?, ?)', [$id, $lang]);
$data = $this->db->query('SELECT translationID FROM projects_translations WHERE projectID = ? AND lang = ?', [$id, $lang])->result_array();
}
$translationID = $data[0]['translationID'];
$this->db->query('UPDATE projects_translations SET title = ?, description = ?, content = ?, downloadName = ?, openSourceName = ?, customLinkName = ? WHERE translationID = ?', array_merge($translation, [$download['name'], $openSource['name'], $customLink['name'], $translationID]));
}
$this->db->cache_on();
$this->db->cache_delete('admin', 'projects');
$this->db->cache_delete('projects', 'index');
$this->db->cache_delete('projects', 'entry');
}
public function mergeTranslationData($postList, $lang = 'de') {
foreach ($postList as $i => $post) {
$data = $this->db->query('SELECT * FROM projects_translations WHERE projectID = ? AND (lang = ? OR lang = ?) ORDER BY lang', [$post['ID'], 'de', $lang])->result_array();
if(sizeof($data) == 1) {
$postList[$i] = array_merge($post, $data[0]);
continue;
}
$merged = [];
foreach ($data[0] as $key => $value) {
if(($value == NULL && $data[1][$key] == NULL) || ($value != NULL && $data[1][$key] == NULL)) {
$merged[$key] = $value;
} else {
$merged[$key] = $data[1][$key];
}
}
$postList[$i] = array_merge($post, $merged);
}
return $postList;
}
}

View File

@@ -0,0 +1,79 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class RedirectModel extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->model('blogModel', '', TRUE);
}
public function insertRedirect($url, $name, $temp = false, $expireDate = null) {
$result1 = $this->db->query('SELECT * FROM redirects WHERE redirect = ?', [$name])->result_array();
if(empty($result1)) {
$this->db->query('INSERT INTO redirects (url, redirect, temporary, expireDate) VALUES (?, ?, ?, ?)', [$url, $name, $temp, $expireDate]);
return ['feedback' => 'success'];
} else {
return ['feedback' => 'error', 'message' => 'Umleitungs-Code ist schon vergeben!'];
}
}
public function editRedirect($id, $url, $name) {
$this->db->query('UPDATE redirects SET url = ? WHERE ID = ? AND redirect = ?', [$url, $id, $name]);
}
public function removeRedirect($id) {
$this->db->query('DELETE FROM redirects WHERE ID = ?', [$id]);
}
public function getUrl($name) {
$result1 = $this->db->query('SELECT * FROM redirects WHERE redirect = ?', [$name])->result_array();
if(empty($result1)) {
return base_url();
} else {
$result = $result1[0];
return $result['url'];
}
}
public function getItems() {
$result = $this->db->query('SELECT * FROM redirects')->result_array();
return $result;
}
public function getName($url) {
$result = $this->db->query('SELECT * FROM redirects WHERE url = ?', [$url])->result_array();
if(empty($result)) {
return '';
} else {
$result1 = $result[0];
return $result1['redirect'];
}
}
public function addRandomItem($url, $temporary, $temporaryTime) {
$alreadyExists = $this->getName($url);
if($alreadyExists == '') {
for($i = 0; $i < 1; $i++) {
$randomName = base64_encode($url);
$name = '';
for($j = 0; $j < 5; $j++) {
$random = rand(0, strlen($randomName) - 1);
$name .= $randomName[$random];
}
$expireDate = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' + ' . $temporaryTime . ' hours'));
if($this->insertRedirect($url, $name, $temporary, $expireDate)['feedback'] == 'success') {
return $this->getName($url);
} else {
$i--;
}
}
} else {
return $alreadyExists;
}
}
}

View File

@@ -0,0 +1,113 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class SocialMediaModel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
private function getSslPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function getYouTubeVideos()
{
$apiUrl = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=20&playlistId=UUEDHiXaIhm2VFu-hi6CcOWw&key=AIzaSyDAZ_TwVMZeiKDQxgWM2OYRq3YskEpY9yw';
$apiResult = json_decode($this->getSslPage($apiUrl));
$items = $apiResult->items;
foreach ($items as $item) {
$snippet = $item->snippet;
$published = $snippet->publishedAt;
$author = $snippet->channelTitle;
$author_url = "https://youtube.com/channel/" . $snippet->channelId;
$title = $snippet->title;
if (isset($snippet->thumbnails->maxres->url)) $thumbnail = $snippet->thumbnails->maxres->url;
else $thumbnail = $snippet->thumbnails->standard->url;
$url = "http://youtu.be/" . $snippet->resourceId->videoId;
$this->db->query('INSERT INTO social_posts (post_plattform, post_content, post_url, post_author, post_author_url, post_date, post_img_source) VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE post_content = ?, post_img_source = ?;', ["YouTube", $title, $url, $author, $author_url, strtotime($published), $thumbnail, $title, $thumbnail]);
}
}
public function getTwitterPosts()
{
$consumer_key = 'TsUzd4stukv9Ix7TGG7RdYq4k';
$consumer_key_secret = 'sTRq4WcELJZuciTrkNUttGgWhEiGaUkuqNhISgaG4uHRFgzm0B';
$access_token = '1880071790-Nij2RaBDVRGVWoWW2PSJUwAvuLAOaQFAAr5tAtC';
$access_token_secret = 'ldhLg0SP3ycrrdIqhNcddj0042pdGY9vmZMKQJRClmDkD';
$oauth_hash = 'count=20&oauth_consumer_key=' . $consumer_key . '&oauth_nonce=' . time() . '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' . time() . '&oauth_token=' . $access_token . '&oauth_version=1.0';
$base = 'GET&' . urlencode('https://api.twitter.com/1.1/statuses/user_timeline.json') . '&' . rawurlencode($oauth_hash);
$key = rawurlencode($consumer_key_secret) . '&' . rawurlencode($access_token_secret);
$signature = base64_encode(hash_hmac('sha1', $base, $key, true));
$signature = rawurlencode($signature);
$oauth_header = 'oauth_consumer_key="' . $consumer_key . '", oauth_nonce="' . time() . '", oauth_signature="' . $signature . '", oauth_signature_method="HMAC-SHA1", oauth_timestamp="' . time() . '", oauth_token="' . $access_token . '", oauth_version="1.0", ';
$curl_header = array("Authorization: Oauth {$oauth_header}", 'Expect:');
$curl_request = curl_init();
curl_setopt($curl_request, CURLOPT_HTTPHEADER, $curl_header);
curl_setopt($curl_request, CURLOPT_HEADER, false);
curl_setopt($curl_request, CURLOPT_URL, 'https://api.twitter.com/1.1/statuses/user_timeline.json?count=20');
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, false);
$json = curl_exec($curl_request);
curl_close($curl_request);
$posts = json_decode($json);
foreach ($posts as $post) {
$content = str_replace("\n", "<br>", $post->text);
$author = $post->user->screen_name;
$author_url = 'https://twitter.com/' . $author;
$url = $author_url . '/status/' . $post->id_str;
$published = strtotime($post->created_at);
$original_id = $post->id_str;
if (isset($post->extended_entities->media[0]->media_url)) {
$image = $post->extended_entities->media[0]->media_url;
} else {
$image = '';
}
$this->db->query('INSERT INTO social_posts (post_plattform, post_content, post_url, post_author, post_author_url, post_date, post_img_source, post_original_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE post_content = ?, post_author_url = ?, post_original_id = ?;', ["Twitter", $content, $url, $author, $author_url, $published, $image, $original_id, $content, $author_url, $original_id]);
}
}
public function getAllPosts()
{
$this->getTwitterPosts();
$items = $this->db->query('SELECT * FROM social_posts ORDER BY post_date DESC')->result_array();
return $items;
}
public function getPosts($amount, $offset)
{
if($offset == 0) {
$items = $this->db->query('SELECT * FROM social_posts ORDER BY post_date DESC LIMIT ?', [$amount])->result_array();
} else {
$items = $this->db->query('SELECT * FROM social_posts ORDER BY post_date DESC LIMIT ? OFFSET ?', [$amount, $offset])->result_array();
}
return $items;
}
public function getPostsOfCategory($amount, $offset, $category) {
if($offset == 0) {
$items = $this->db->query('SELECT * FROM social_posts WHERE post_plattform LIKE ? ORDER BY post_date DESC LIMIT ?', [$category, $amount])->result_array();
} else {
$items = $this->db->query('SELECT * FROM social_posts WHERE post_plattform LIKE ? ORDER BY post_date DESC LIMIT ? OFFSET ?', [$category, $amount, $offset])->result_array();
}
return $items;
}
}

View File

@@ -0,0 +1,47 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TwitchModel extends CI_Model {
public function getTwitchInfos($channel) {
$url = "https://api.twitch.tv/helix/users?login=" . $channel;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'client-id: e4iys1e969ndfyrdzuiae7whaact2p'
]);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
public function getTwitchStream($channel) {
$url = "https://api.twitch.tv/kraken/streams/" . $channel;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
public function getTwitchVideos($channel) {
$url = "https://api.twitch.tv/kraken/channels/" . $channel . "/videos";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
}

View File

@@ -0,0 +1,236 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class UserModel extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->model('BlogModel', '', TRUE);
$this->load->model('NotificationModel', '', TRUE);
}
function getUser($username)
{
$result = $this->db->query('SELECT ID, username, displayname, email, rank, profile_picture, header_image, about, social_networks, showAds, date_created, gender, language, country, birthdate, birthyear, receiveEmails, receiveNewsletter FROM users WHERE username = ? AND is_activated = TRUE LIMIT 1', [$username])->result_array();
if (empty($result)) {
return null;
}
$result = $this->setDefaultImages($result);
$result = $this->setRankname($result);
return $result;
}
public function setDefaultImages($userList)
{
for ($i = 0; $i < sizeof($userList); $i++) {
if ((isset($userList[$i]['header_image']) && ($userList[$i]['header_image'] == '' || $userList[$i]['header_image'] == NULL)) || !isset($userList[$i]['header_image'])) {
$userList[$i]['header_image'] = substr(base_url(), 0, base_url() - 1) . ':3000/' . $userList[$i]['displayname'];
}
if (isset($userList[$i]['profile_picture']) && $userList[$i]['profile_picture'] == '') {
$userList[$i]['profile_picture'] = base_url('/f/8d204712d8132b36d765640ce775ce15');
}
}
return $userList;
}
public function setRankname($userList)
{
for ($i = 0; $i < sizeof($userList); $i++) {
if (isset($userList[$i]['rank'])) {
$userList[$i]['rankName'] = $this->GeneralModel->getRankName($userList[$i]['rank']);
}
}
return $userList;
}
public function getUserIDByUsername($username)
{
$result = $this->db->query('SELECT ID FROM users WHERE username = ?', [$username])->result_array();
return $result;
}
public function mergeFollowerCount($users) {
foreach ($users as $i => $user) {
$this->db->cache_off();
$followerCount = $this->db->query('SELECT count(*) followerCount FROM user_followers WHERE followedUserID = ?', [$user['ID']])->result_array();
$this->db->cache_on();
$users[$i]['followerCount'] = $followerCount[0]['followerCount'];
}
return $users;
}
public function getFollowers($id)
{
$this->db->cache_off();
$followers = $this->db->query('SELECT ID, followedSince, username, displayname, profile_picture, header_image FROM user_followers LEFT JOIN users ON ID = followerUserID WHERE followedUserID = ? ORDER BY followedSince DESC', [$id])->result_array();
$this->db->cache_on();
$followers = $this->setDefaultImages($followers);
$followers = $this->mergeFollowerCount($followers);
return $followers;
}
function getUserByID($id)
{
$result = $this->db->query('SELECT ID, original_name, username, displayname, email, rank, profile_picture, header_image, is_activated, about, lastLogin, social_networks, showAds, date_created, gender, language, country, birthdate, birthyear, receiveEmails, receiveNewsletter FROM users WHERE ID = ? AND is_activated = TRUE LIMIT 1', [$id])->result_array();
if (empty($result)) {
return null;
}
$result = $this->setDefaultImages($result);
$result = $this->setRankname($result);
return $result;
}
public function getFollowing($id)
{
$this->db->cache_off();
$following = $this->db->query('SELECT ID, followedSince, username, displayname, profile_picture, header_image FROM user_followers LEFT JOIN users ON ID = followedUserID WHERE followerUserID = ? ORDER BY followedSince DESC', [$id])->result_array();
$this->db->cache_on();
$following = $this->setDefaultImages($following);
$following = $this->mergeFollowerCount($following);
return $following;
}
function getUserComments($id, $count, $offset)
{
$comments = $this->db->query('SELECT *, p.postUrl FROM blog_comments c LEFT JOIN blog_posts p ON p.postID = c.post_id WHERE user_id = ? ORDER BY date_created DESC LIMIT ? OFFSET ?', [$id, $count, $offset])->result_array();
$comments = $this->BlogModel->mergePostTitleDesc($comments);
return $comments;
}
function getUserBlogPosts($id, $count, $offset)
{
$posts = $this->db->query('SELECT * FROM blog_posts WHERE postIsDeleted = FALSE AND postState = 1 AND postAuthorID = ? ORDER BY postPublishDate DESC LIMIT ? OFFSET ?', [$id, $count, $offset])->result_array();
$posts = $this->BlogModel->mergePostTitleDesc($posts);
return $posts;
}
function getUserStats($userID)
{
$result = [];
$this->db->cache_off();
$user = $this->db->query('SELECT
COUNT(*) postCount,
(SELECT COUNT(*)
FROM user_followers
WHERE followedUserID = ?) followerCount,
(SELECT COUNT(*)
FROM user_followers
WHERE followerUserID = ?) followedCount
FROM user_posts
WHERE user_id = ?', [$userID, $userID, $userID])->result_array()[0];
$result['postCount'] = $user['postCount'];
$result['followerCount'] = $user['followerCount'];
$result['followedCount'] = $user['followedCount'];
$blogResults = $this->db->query('SELECT COUNT(*) blogCount, (SELECT COUNT(*) FROM blog_comments WHERE user_id = ?) commentCount FROM blog_posts WHERE postIsDeleted = FALSE AND postState = 1 AND postAuthorID = ?', [$userID, $userID])->result_array()[0];
$result['blogCount'] = $blogResults['blogCount'];
$result['commentCount'] = $blogResults['commentCount'];
$this->db->cache_on();
return $result;
}
function isFollowing($followerID, $followingID)
{
$this->db->cache_off();
$response = $this->db->query('SELECT followedUserID FROM user_followers WHERE followerUserID = ? AND followedUserID = ?', [$followerID, $followingID])->result_array();
$this->db->cache_off();
return !empty($response);
}
function unfollow($followerID, $followedID)
{
$this->db->query('DELETE FROM user_followers WHERE followerUserID = ? AND followedUserID = ?', [$followerID, $followedID]);
// Remove notification
$this->NotificationModel->removeNotification($followerID, $followedID, $followedID, 'users.newFollower');
}
function follow($followerID, $followedID)
{
$this->db->query('INSERT INTO user_followers (followerUserID, followedUserID) VALUES (?, ?)', [$followerID, $followedID]);
// Send notification to followed user
$this->NotificationModel->userNotificationNewFollower($followerID, $followedID);
}
function updateProfile($data, $id)
{
$this->db->where('ID', $id);
$this->db->update('users', $data);
}
function insertIntoHistory($data)
{
unset($data['date_created']);
$this->db->insert('users_history', $data);
}
function getUserList($amount, $offset)
{
$data = $this->db->query('SELECT ID, username, displayname, rank, profile_picture, header_image, is_activated, showAds, receiveEmails, receiveNewsletter, date_created, isCurrentlyOnline, lastLogin, login_method, language, country, gender FROM users LIMIT ? OFFSET ?', [$amount, $offset])->result_array();
$data = $this->setDefaultImages($data);
$data = $this->setRankname($data);
return $data;
}
public function updateOnline($id)
{
$this->db->query('UPDATE users SET isCurrentlyOnline = 1, lastOnlineUpdate = NOW() WHERE ID = ? LIMIT 1', [$id]);
}
function getActiveUsers($count)
{
$data = $this->db->query('SELECT username, displayname, profile_picture, lastLogin, (SELECT COUNT(*) FROM user_followers WHERE followedUserID = users.ID) follower_count FROM users WHERE isCurrentlyOnline = TRUE ORDER BY lastLogin DESC LIMIT ?', [$count])->result_array();
$data = $this->setDefaultImages($data);
return $data;
}
public function getNewestUsers($count)
{
$data = $this->db->query('SELECT username, displayname, profile_picture, date_created, (SELECT COUNT(*) FROM user_followers WHERE followedUserID = users.ID) follower_count FROM users ORDER BY date_created DESC LIMIT ?', [$count])->result_array();
$data = $this->setDefaultImages($data);
return $data;
}
public function searchUsers($query, $rank = '', $region = '', $lang = '', $amount = 3, $offset = 0) {
$conditions = [];
$inputs = [];
if($query !== '') {
$conditions[] = 'username RLIKE ?';
$inputs[] = $query;
}
if($rank !== '') {
$conditions[] = 'rank = ?';
$inputs[] = $rank;
}
if($region !== '') {
$conditions[] = 'country = ?';
$inputs[] = $region;
}
if($lang !== '') {
$conditions[] = 'language = ?';
$inputs[] = $lang;
}
$dbClause = join(' AND ', $conditions);
$inputs[] = $amount;
$inputs[] = $offset;
$data = $this->db->query('SELECT username, displayname, profile_picture, header_image, about, rank FROM users WHERE ' . $dbClause . ' LIMIT ? OFFSET ?', $inputs)->result_array();
$data = $this->setDefaultImages($data);
$data = $this->setRankname($data);
return $data;
}
public function getAvailableCountries() {
return $this->db->query('SELECT country, count(*) countryUserCount FROM users WHERE country IS NOT NULL AND country != "" GROUP BY country ORDER BY country')->result_array();
}
public function getAvailableLanguages() {
return $this->db->query('SELECT language, count(*) langUserCount FROM users GROUP BY language ORDER BY language')->result_array();
}
}

View File

@@ -0,0 +1,92 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class YoutubeDownloadModel extends CI_Model {
public function __construct() {
parent::__construct();
}
function curlGet($URL) {
$ch = curl_init();
$timeout = 3;
curl_setopt( $ch , CURLOPT_URL , $URL );
curl_setopt( $ch , CURLOPT_RETURNTRANSFER , 1 );
curl_setopt( $ch , CURLOPT_CONNECTTIMEOUT , $timeout );
/* if you want to force to ipv6, uncomment the following line */
//curl_setopt( $ch , CURLOPT_IPRESOLVE , 'CURLOPT_IPRESOLVE_V6');
$tmp = curl_exec( $ch );
curl_close( $ch );
return $tmp;
}
/*
* function to use cUrl to get the headers of the file
*/
function get_location($url) {
$my_ch = curl_init();
curl_setopt($my_ch, CURLOPT_URL,$url);
curl_setopt($my_ch, CURLOPT_HEADER, true);
curl_setopt($my_ch, CURLOPT_NOBODY, true);
curl_setopt($my_ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($my_ch, CURLOPT_TIMEOUT, 10);
$r = curl_exec($my_ch);
foreach(explode("\n", $r) as $header) {
if(strpos($header, 'Location: ') === 0) {
return trim(substr($header,10));
}
}
return '';
}
function get_size($url) {
$my_ch = curl_init();
curl_setopt($my_ch, CURLOPT_URL,$url);
curl_setopt($my_ch, CURLOPT_HEADER, true);
curl_setopt($my_ch, CURLOPT_NOBODY, true);
curl_setopt($my_ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($my_ch, CURLOPT_TIMEOUT, 10);
$r = curl_exec($my_ch);
foreach(explode("\n", $r) as $header) {
if(strpos($header, 'Content-Length:') === 0) {
return trim(substr($header,16));
}
}
return '';
}
function get_description($url) {
$fullpage = curlGet($url);
$dom = new DOMDocument();
@$dom->loadHTML($fullpage);
$xpath = new DOMXPath($dom);
$tags = $xpath->query('//div[@class="info-description-body"]');
foreach ($tags as $tag) {
$my_description .= (trim($tag->nodeValue));
}
return utf8_decode($my_description);
}
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
function formatBytes($bytes, $precision = 2) {
$units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
function is_chrome(){
$agent=$_SERVER['HTTP_USER_AGENT'];
if( preg_match("/like\sGecko\)\sChrome\//", $agent) ){ // if user agent is google chrome
if(!strstr($agent, 'Iron')) // but not Iron
return true;
}
return false; // if isn't chrome return false
}
}

View File

@@ -0,0 +1,134 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Coduo\PHPHumanizer\DateTimeHumanizer;
class YoutubePlayerModel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function getRecommendVideos($id)
{
$data = $this->youtubePlayerModel->newestVids('15');
$return = '';
if (!empty($data)) {
foreach ($data as $row) {
$videoId = $row['contentDetails'];
$videoId = $videoId['videoId'];
$title = $this->youtubePlayerModel->getInfos($videoId)['title'];
if ($id == $videoId) {
$return .= '<li>
<a onclick="switchVideo(\'' . $videoId . '\');" style="cursor: pointer;">
<div class="image-container active">
<img src="http://img.youtube.com/vi/' . $videoId . '/maxresdefault.jpg" alt="' . $title . '" class="img-fluid">
<div class="overlay"><span>' . $title . '</span></div>
</div>
</a>
</li>';
} else {
$return .= '<li>
<a onclick="switchVideo(\'' . $videoId . '\');" style="cursor: pointer;">
<div class="image-container">
<img src="http://img.youtube.com/vi/' . $videoId . '/maxresdefault.jpg" alt="' . $title . '" class="img-fluid">
<div class="overlay"><span>' . $title . '</span></div>
</div>
</a>
</li>';
}
// if($id == $videoId) {
// $return .= '<a onClick="switchVideo(\'' . $videoId . '\');" class="btn btn-sm btn-default active raised">' .$title. '</a>';
// } else {
// $return .= '<a onClick="switchVideo(\'' . $videoId . '\');" class="btn btn-sm btn-default raised">' .$title. '</a>';
// }
}
} else {
$return = null;
}
return $return;
}
public function newestVids($vidCount)
{
$data = $this->db->query('SELECT * FROM social_posts WHERE post_plattform = \'YouTube\' ORDER BY post_date DESC LIMIT ?', [$vidCount])->result_array();
if (!empty($data)) {
return $data;
} else {
return null;
}
}
public function getInfos($id)
{
$data = json_decode(@file_get_contents('https://www.googleapis.com/youtube/v3/videos?part=snippet%2Cstatistics&hl=de&id=' . $id . '&regionCode=de&key=AIzaSyAZi6W9FODqd-bjlmV0sGJ8vjvSgFNTXVM'), true)['items'];
$data = $data[0];
$infos = $data['snippet'];
$stats = $data['statistics'];
$return = [];
$return['title'] = $infos['title'];
$description = htmlspecialchars($infos['description']);
$descriptionList = explode(' ', $description);
$description = '';
foreach ($descriptionList as $item) {
if (isset(parse_url($item)['scheme']) && isset(parse_url($item)['host'])) {
$description .= '<a href="' . $item . '" target="_blank">' . $item . '</a> ';
} else {
if ($infos['channelTitle'] == 'KingOfDog') {
$items1 = ['✔️', '', '©'];
$items2 = ['</p><p>✔️', '<br>', '<br>©'];
$description .= str_replace($items1, $items2, $item) . ' ';
} else {
$description .= $item . ' ';
}
}
}
$return['description'] = $description;
$published = strtotime($infos['publishedAt']);
$return['published'] = DateTimeHumanizer::difference(new \DateTime(), new \DateTime("@$published"), $_SESSION['site_lang']);
$return['channelName'] = $infos['channelTitle'];
$return['channelUrl'] = 'http://youtube.com/channel/' . $infos['channelId'];
$return['views'] = number_format($stats['viewCount'], 0, ',', '.');
$return['likes'] = $stats['likeCount'];
$return['dislikes'] = $stats['dislikeCount'];
$return['comments'] = number_format($stats['commentCount'], 0, ',', '.');
$rateCount = intval($return['likes']) + intval($return['dislikes']);
if (intval($return['likes']) > 0 && intval($return['dislikes']) > 0) {
$return['likeWidth'] = intval($return['likes']) / $rateCount * 100;
$return['dislikeWidth'] = intval($return['dislikes']) / $rateCount * 100;
$return['grayWidth'] = 0;
} elseif (intval($return['likes']) == 0 && intval($return['dislikes']) == 0) {
$return['likeWidth'] = 0;
$return['dislikeWidth'] = 0;
$return['grayWidth'] = 100;
} elseif (intval($return['likes']) == 0) {
$return['likeWidth'] = 0;
$return['dislikeWidth'] = 100;
$return['grayWidth'] = 0;
} else {
$return['likeWidth'] = 100;
$return['dislikeWidth'] = 0;
$return['grayWidth'] = 0;
}
$return['thumbnails'] = $infos['thumbnails'];
return $return;
}
public function checkVideo($videoID)
{
$data = json_decode(@file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=" . $videoID . "&key=AIzaSyAZi6W9FODqd-bjlmV0sGJ8vjvSgFNTXVM"));
return $data->pageInfo->totalResults !== 0;
}
}

View File

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>

View File

@@ -0,0 +1,46 @@
<?php
namespace Notification\Admin;
use Notification;
require_once 'Notification.php';
class NewFeedbackNotification extends \Notification
{
public function __construct(array $data)
{
$data['type'] = 'admin.feedback';
parent::__construct($data);
}
public function getNotificationLink()
{
return '/admin/feedback';
}
public function getNotificationImage()
{
return $this->sender->getProfilePicture();
}
public function messageForNotification(Notification $notification)
{
return ['line' => 'admin.feedback.single', 'attributes' => [$this->sender->getName()]];
}
public function messageForNotifications(array $notifications, $realCount = 0)
{
if ($realCount === 0) {
$realCount = count($notifications);
}
if ($realCount < 5) {
$names = $this->manyNames($notifications);
return ['line' => 'admin.feedback.multiple', 'attributes' => [$names]];
} else {
$names = $this->manyNamesCutoff($notifications, $realCount);
return ['line' => 'admin.feedback.many', 'attributes' => [$names]];
}
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Notification\Users;
use Notification;
require_once 'Notification.php';
class NewFollowerNotification extends \Notification
{
public function __construct(array $data)
{
$data['type'] = 'users.newFollower';
parent::__construct($data);
}
public function getNotificationLink()
{
return '/user/' . $this->recipient->getUsername() . '/followers';
}
public function getNotificationImage()
{
return $this->sender->getProfilePicture();
}
public function messageForNotification(Notification $notification)
{
return ['line' => 'users.newFollower.single', 'attributes' => [$this->sender->getName()]];
}
public function messageForNotifications(array $notifications, $realCount = 0)
{
if ($realCount === 0) {
$realCount = count($notifications);
}
if ($realCount < 5) {
$names = $this->manyNames($notifications);
return ['line' => 'users.newFollower.multiple', 'attributes' => [$names]];
} else {
$names = $this->manyNamesCutoff($notifications, $realCount);
return ['line' => 'users.newFollower.many', 'attributes' => [$names]];
}
}
}

View File

@@ -0,0 +1,63 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once 'NotificationGroup.php';
abstract class Notification
{
public $recipient;
public $sender;
public $unread;
public $type;
public $parameters;
public $referenceID;
public $createdAt;
public function __construct(array $data)
{
$this->recipient = new NotificationUser($data['recipientID'],
isset($data['recipientName']) ? $data['recipientName'] : '',
isset($data['recipientDisplayname']) ? $data['recipientDisplayname'] : ($data['recipientID'] == -1 ? 'Anonym' : ($data['recipientID'] == -2 ? 'System' : 'Unbekannt')));
$this->sender = new NotificationUser($data['senderID'],
isset($data['senderName']) ? $data['senderName'] : '',
isset($data['senderDisplayname']) ? $data['senderDisplayname'] : ($data['senderID'] == -1 ? 'Anonym' : ($data['senderID'] == -2 ? 'System' : 'Unbekannt')));
$this->sender->setProfilePicture(isset($data['senderPicture']) ? $data['senderPicture'] : '');
$this->unread = isset($data['unread']) ? $data['unread'] : 1;
$this->type = $data['type'];
$this->parameters = isset($data['parameters']) ? $data['parameters'] : '';
$this->referenceID = $data['referenceID'];
$this->createdAt = isset($data['createdAt']) ? $data['createdAt'] : time();
}
public abstract function getNotificationLink();
public abstract function getNotificationImage();
public abstract function messageForNotification(Notification $notification);
public abstract function messageForNotifications(array $notifications);
public function message()
{
return $this->messageForNotification($this);
}
protected function manyNames(array $names) {
$last = array_pop($names);
$finalNames = '';
foreach ($names as $name) {
$finalNames .= $name->sender->getName() . ', ';
}
return sprintf(lang('notification.multiple'), substr($finalNames, 0, -2), $last->sender->getName());
}
protected function manyNamesCutoff(array $names, $realCount) {
list($first, $second) = array_slice($names, 0, 2);
return sprintf(lang('notification.many'), $first->sender->getName(), $second->sender->getName(), $realCount);
}
}

View File

@@ -0,0 +1,33 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once 'Notification.php';
class NotificationGroup
{
protected $notifications;
protected $realCount;
public function __construct(array $notifications, $count)
{
$this->notifications = $notifications;
$this->realCount = $count;
}
public function message() {
if($this->realCount == 1) {
return $this->notifications[0]->messageForNotification($this->notifications[0]);
}
return $this->notifications[0]->messageForNotifications($this->notifications, $this->realCount);
}
public function __get($attribute)
{
return $this->notifications[0]->{$attribute};
}
public function __call($name, $arguments)
{
return call_user_func_array([$this->notifications[0], $name], $arguments);
}
}

View File

@@ -0,0 +1,42 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class NotificationUser
{
protected $id;
protected $username;
protected $displayname;
protected $profilePicture;
public function __construct($id, $username, $displayname)
{
$this->id = $id;
$this->username = $username;
$this->displayname = $displayname;
}
public function getId()
{
return $this->id;
}
public function getUsername()
{
return $this->username;
}
public function getName()
{
return $this->displayname;
}
public function getProfilePicture()
{
return $this->profilePicture;
}
public function setProfilePicture($profilePicture)
{
$this->profilePicture = $profilePicture;
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Notification\Users;
use Notification;
require_once 'Notification.php';
class PostLikeNotification extends \Notification
{
public function __construct(array $data)
{
$data['type'] = 'users.likedPost';
parent::__construct($data);
}
public function getNotificationLink()
{
return '/user/' . $this->recipient->getUsername() . '/post/' . $this->parameters;
}
public function getNotificationImage()
{
return $this->sender->getProfilePicture();
}
public function messageForNotification(Notification $notification)
{
return ['line' => 'users.likedPost.single', 'attributes' => [$this->sender->getName()]];
}
public function messageForNotifications(array $notifications, $realCount = 0)
{
if ($realCount === 0) {
$realCount = count($notifications);
}
if ($realCount < 5) {
$names = $this->manyNames($notifications);
return ['line' => 'users.likedPost.multiple', 'attributes' => [$names]];
} else {
$names = $this->manyNamesCutoff($notifications, $realCount);
return ['line' => 'users.likedPost.many', 'attributes' => [$names]];
}
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Notification\Users;
use Notification;
require_once 'Notification.php';
class PostMentionNotification extends \Notification
{
public function __construct(array $data)
{
$data['type'] = 'users.mentionedPost';
parent::__construct($data);
}
public function getNotificationLink()
{
return '/user/' . $this->sender->getUsername() . '/post/' . $this->parameters;
}
public function getNotificationImage()
{
return $this->sender->getProfilePicture();
}
public function messageForNotification(Notification $notification)
{
return ['line' => 'users.mentionedPost.single', 'attributes' => [$this->sender->getName()]];
}
public function messageForNotifications(array $notifications, $realCount = 0)
{
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Notification\Users;
use Notification;
require_once 'Notification.php';
class PostReplyNotification extends \Notification
{
public function __construct(array $data)
{
$data['type'] = 'users.repliedPost';
parent::__construct($data);
}
public function getNotificationLink()
{
return '/user/' . $this->recipient->getUsername() . '/post/' . $this->parameters;
}
public function getNotificationImage()
{
return $this->sender->getProfilePicture();
}
public function messageForNotification(Notification $notification)
{
return ['line' => 'users.repliedPost.single', 'attributes' => [$this->sender->getName()]];
}
public function messageForNotifications(array $notifications, $realCount = 0)
{
if ($realCount === 0) {
$realCount = count($notifications);
}
if ($realCount < 5) {
$names = $this->manyNames($notifications);
return ['line' => 'users.replied.multiple', 'attributes' => [$names]];
} else {
$names = $this->manyNamesCutoff($notifications, $realCount);
return ['line' => 'users.replied.many', 'attributes' => [$names]];
}
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Notification\Users;
use Notification;
require_once 'Notification.php';
class PostReportNotification extends \Notification
{
public function __construct(array $data)
{
$data['type'] = 'users.reportedPost';
parent::__construct($data);
}
public function getNotificationLink()
{
return '/user/' . $this->recipient->getUsername() . '/post/' . $this->parameters;
}
public function getNotificationImage()
{
return $this->recipient->getProfilePicture();
}
public function messageForNotification(Notification $notification)
{
return ['line' => 'users.reportedPost.single', 'attributes' => [$this->recipient->getName()]];
}
public function messageForNotifications(array $notifications, $realCount = 0)
{
if ($realCount === 0) {
$realCount = count($notifications);
}
if ($realCount < 5) {
$names = $this->manyNames($notifications);
return ['line' => 'users.reportedPost.multiple', 'attributes' => [$names]];
} else {
$names = $this->manyNamesCutoff($notifications, $realCount);
return ['line' => 'users.reportedPost.many', 'attributes' => [$names]];
}
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Notification\Admin;
use Notification;
require_once 'Notification.php';
class UserRegisteredNotification extends \Notification
{
public function __construct(array $data)
{
$data['type'] = 'admin.newUserRegistered';
parent::__construct($data);
}
public function getNotificationLink()
{
return '/user/' . $this->sender->getUsername();
}
public function getNotificationImage()
{
return $this->sender->getProfilePicture();
}
public function messageForNotification(Notification $notification)
{
return ['line' => 'admin.newUserRegistered.single', 'attributes' => [$this->sender->getName()]];
}
public function messageForNotifications(array $notifications, $realCount = 0)
{
}
}