Browse Source

Move Cache to Eloquent

Code cleanup
pull/617/head
Timothée Jaussoin 8 years ago
parent
commit
21d3745477
  1. 102
      app/Cache.php
  2. 23
      app/User.php
  3. 2
      app/views/page.tpl
  4. 6
      app/widgets/Blog/Blog.php
  5. 2
      app/widgets/Chat/Chat.php
  6. 14
      app/widgets/Chats/Chats.php
  7. 3
      app/widgets/CommunityPosts/CommunityPosts.php
  8. 9
      app/widgets/Config/Config.php
  9. 6
      app/widgets/Menu/Menu.php
  10. 4
      app/widgets/Notifs/Notifs.php
  11. 4
      app/widgets/Post/Post.php
  12. 2
      app/widgets/PublishBrief/PublishBrief.php
  13. 1
      app/widgets/Roster/Roster.php
  14. 33
      database/migrations/20180317185328_create_privacy_table.php
  15. 28
      database/migrations/20180318222026_create_caches_table.php
  16. 5
      src/Movim/Bootstrap.php
  17. 109
      src/Movim/Cache.php
  18. 3
      src/Movim/Template/Builder.php
  19. 67
      src/Movim/User.php

102
app/Cache.php

@ -0,0 +1,102 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cache extends Model
{
private static $_instance;
protected $primaryKey = 'name';
public static function instanciate()
{
if (!is_object(self::$_instance)) {
self::$_instance = new Cache;
}
return self::$_instance;
}
/**
* Helper function to access cache.
*/
public static function c()
{
$cache = self::instanciate();
return call_user_func_array([$cache, 'handle'], func_get_args());
}
/**
* Fetches or commits an object to cache with the provided key.
*
* Prototype: handle(string $key, ...)
*
* The following fetches an object from cache.
* handle('key')
*
* This commits an object to cache.
* handle('key', $object);
*
* Several objects can be commited to cache in this manner:
* handle('key', $object1, $object2, $object3);
* And retrieved as follows:
* list($object1, $object2, $object3) = handle('key');
*/
public function handle($key)
{
$arglist = func_get_args();
$key = $arglist[0];
if (func_num_args() == 1) {
$content = $this->_readCache($key);
if (isset($content) && $content != '') {
return $content;
}
return null;
}
if (func_num_args() == 2) {
return $this->_writeCache($key, $arglist[1]);
}
// Cutting a piece of the args.
$content = array_slice($arglist, 1);
return $this->_writeCache($key, $content);
}
/**
* Serializes data in a proper fashion.
*/
private function _writeCache($key, $object)
{
$data = str_replace(
"'", "\\'",
base64_encode(gzcompress(serialize($object)))
);
$cache = Cache::firstOrNew(['user_id' => User::me()->id, 'name' => $key]);
$cache->data = $data;
$cache->save();
}
/**
* Unserializes data.
*/
private function _readCache($key)
{
$cache = $this->where('user_id', User::me()->id)
->where('name', $key)
->first();
if (isset($cache)) {
return unserialize(
gzuncompress(base64_decode(str_replace("\\'", "'", $cache->data)))
);
}
return false;
}
}

23
app/User.php

@ -24,7 +24,9 @@ class User extends Model
public static function me()
{
$session = Session::start();
return self::find($session->get('jid'));
$me = self::find($session->get('jid'));
return ($me) ? $me : new User;
}
public function init()
@ -33,6 +35,25 @@ class User extends Model
$contact->save();
}
public function setConfig(array $config)
{
if (isset($config['language'])) {
$this->language = $config['language'];
}
if (isset($config['cssurl'])) {
$this->cssurl = $config['cssurl'];
}
if (isset($config['nsfw'])) {
$this->nsfw = $config['nsfw'];
}
if (isset($config['nightmode'])) {
$this->nightmode = $config['nightmode'];
}
}
public function setPublic()
{
$this->attributes['public'] = true;

2
app/views/page.tpl

@ -45,7 +45,7 @@
?>
</head>
<body dir="<?php $this->dir();?>"
class="<?php if (!$this->public && (new \Movim\User)->getConfig('nightmode')) { ?>nightmode<?php } ?>">
class="<?php if (!$this->public && \App\User::me()->nightmode) { ?>nightmode<?php } ?>">
<noscript>
<style type="text/css">
nav {display:none;} #content {display: none;}

6
app/widgets/Blog/Blog.php

@ -1,7 +1,7 @@
<?php
use Respect\Validation\Validator;
use Movim\User;
use App\User;
include_once WIDGETS_PATH.'Post/Post.php';
@ -142,9 +142,7 @@ class Blog extends \Movim\Widget\Base
}
if ($this->_node == 'urn:xmpp:microblog:0') {
$this->user = new User($this->_from);
$cssurl = $this->user->getDumpedConfig('cssurl');
$cssurl = User::find($this->_from)->cssurl;
if (isset($cssurl)
&& $cssurl != ''
&& Validator::url()->validate($cssurl)) {

2
app/widgets/Chat/Chat.php

@ -789,7 +789,7 @@ class Chat extends \Movim\Widget\Base
{
$view = $this->tpl();
$chats = \Movim\Cache::c('chats');
$chats = \App\Cache::c('chats');
$chats = ($chats == null) ? false : array_keys($chats);
$cd = new \Modl\ContactDAO;

14
app/widgets/Chats/Chats.php

@ -41,7 +41,7 @@ class Chats extends \Movim\Widget\Base
$contacts = $packet->content;
if ($contacts != null){
$c = $contacts[0];
$chats = \Movim\Cache::c('chats');
$chats = \App\Cache::c('chats');
if (is_array($chats) && array_key_exists($c->jid, $chats)) {
$this->rpc('MovimTpl.replace', '#' . cleanupId($c->jid.'_chat_item'), $this->prepareChat($c->jid));
$this->rpc('Chats.refresh');
@ -116,7 +116,7 @@ class Chats extends \Movim\Widget\Base
{
if (!$this->validateJid($jid)) return;
$chats = \Movim\Cache::c('chats');
$chats = \App\Cache::c('chats');
if ($chats == null) $chats = [];
unset($chats[$jid]);
@ -127,7 +127,7 @@ class Chats extends \Movim\Widget\Base
if ($history) $this->ajaxGetHistory($jid);
\Movim\Cache::c('chats', $chats);
\App\Cache::c('chats', $chats);
$this->rpc('Chats.prepend', $jid, $this->prepareChat($jid));
}
}
@ -136,9 +136,9 @@ class Chats extends \Movim\Widget\Base
{
if (!$this->validateJid($jid)) return;
$chats = \Movim\Cache::c('chats');
$chats = \App\Cache::c('chats');
unset($chats[$jid]);
\Movim\Cache::c('chats', $chats);
\App\Cache::c('chats', $chats);
$this->rpc('MovimTpl.remove', '#' . cleanupId($jid . '_chat_item'));
@ -155,7 +155,7 @@ class Chats extends \Movim\Widget\Base
$view = $this->tpl();
$cd = new \Modl\ContactDAO;
$chats = \Movim\Cache::c('chats');
$chats = \App\Cache::c('chats');
if (!isset($chats)) $chats = [];
@ -182,7 +182,7 @@ class Chats extends \Movim\Widget\Base
function prepareChats()
{
$chats = \Movim\Cache::c('chats');
$chats = \App\Cache::c('chats');
$view = $this->tpl();

3
app/widgets/CommunityPosts/CommunityPosts.php

@ -6,6 +6,7 @@ use Moxl\Xec\Action\Pubsub\Delete;
use Respect\Validation\Validator;
use Cocur\Slugify\Slugify;
use App\User;
include_once WIDGETS_PATH.'Post/Post.php';
@ -154,7 +155,7 @@ class CommunityPosts extends \Movim\Widget\Base
$nsfwMessage = false;
if ($this->user->getConfig('nsfw') == false
if (User::me()->nsfw == false
&& is_array($posts)) {
foreach ($posts as $key => $post) {
if ($post->nsfw) {

9
app/widgets/Config/Config.php

@ -2,6 +2,7 @@
use Moxl\Xec\Action\Storage\Set;
use Respect\Validation\Validator;
use App\User;
class Config extends \Movim\Widget\Base
{
@ -18,8 +19,7 @@ class Config extends \Movim\Widget\Base
$l = Movim\i18n\Locale::start();
$view->assign('languages', $l->getList());
$view->assign('me', $this->user->getLogin());
$view->assign('conf', $this->user->getConfig());
$view->assign('conf', User::me());
$view->assign('submit',
$this->call(
@ -35,8 +35,9 @@ class Config extends \Movim\Widget\Base
function onConfig($package)
{
$this->user->setConfig((array)$package->content);
$this->refreshConfig();
$me = User::me();
$me->setConfig($package->content);
$me->save();
Notification::append(null, $this->__('config.updated'));
}

6
app/widgets/Menu/Menu.php

@ -38,7 +38,7 @@ class Menu extends \Movim\Widget\Base
$pd = new \Modl\PostnDAO;
$cd = new \Modl\ContactDAO;
$since = \Movim\Cache::c('since');
$since = \App\Cache::c('since');
$count = $pd->getCountSince($since);
$post = $packet->content;
@ -157,11 +157,11 @@ class Menu extends \Movim\Widget\Base
{
$view = $this->tpl();
$pd = new \Modl\PostnDAO;
$count = $pd->getCountSince(\Movim\Cache::c('since'));
$count = $pd->getCountSince(\App\Cache::c('since'));
// getting newer, not older
if ($page == 0 || $page == ""){
$count = 0;
\Movim\Cache::c('since', date(DATE_ISO8601, strtotime($pd->getLastDate())));
\App\Cache::c('since', date(DATE_ISO8601, strtotime($pd->getLastDate())));
}
$next = $page + 1;

4
app/widgets/Notifs/Notifs.php

@ -14,7 +14,7 @@ class Notifs extends \Movim\Widget\Base
function ajaxClear()
{
\Movim\Cache::c('notifs_since', date(\Modl\SQL::SQL_DATE));
\App\Cache::c('notifs_since', date(\Modl\SQL::SQL_DATE));
$this->onNotifs();
}
@ -23,7 +23,7 @@ class Notifs extends \Movim\Widget\Base
$view = $this->tpl();
$pd = new \Modl\PostnDAO;
$since = \Movim\Cache::c('notifs_since');
$since = \App\Cache::c('notifs_since');
if (!$since) $since = date(\Modl\SQL::SQL_DATE, 0);

4
app/widgets/Post/Post.php

@ -5,6 +5,8 @@ use Moxl\Xec\Action\Pubsub\GetItem;
use Moxl\Xec\Action\Microblog\CommentsGet;
use Moxl\Xec\Action\Microblog\CommentPublish;
use App\User;
use Respect\Validation\Validator;
class Post extends \Movim\Widget\Base
@ -274,7 +276,7 @@ class Post extends \Movim\Widget\Base
$view->assign('repost', \App\Contact::find($p->origin));
}
$view->assign('nsfw', $this->user->getConfig('nsfw'));
$view->assign('nsfw', User::me()->nsfw);
$view->assign('post', $p);
$view->assign('attachments', $p->getAttachments());

2
app/widgets/PublishBrief/PublishBrief.php

@ -5,7 +5,7 @@ use Moxl\Xec\Action\Microblog\CommentCreateNode;
use Moxl\Xec\Action\Pubsub\Subscribe;
use Movim\Session;
use Movim\Cache;
use App\Cache;
use Respect\Validation\Validator;
use Michelf\MarkdownExtra;

1
app/widgets/Roster/Roster.php

@ -155,7 +155,6 @@ class Roster extends \Movim\Widget\Base
$view = $this->tpl();
$view->assign('contacts', $cd->getRoster());
$view->assign('offlineshown', $this->user->getConfig('roster'));
$view->assign('presencestxt', getPresencesTxt());
return $view->draw('_roster_list', true);

33
database/migrations/20180317185328_create_privacy_table.php

@ -1,33 +0,0 @@
<?php
use Phinx\Migration\AbstractMigration;
class CreatePrivacyTable extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
}
}

28
database/migrations/20180318222026_create_caches_table.php

@ -0,0 +1,28 @@
<?php
use Movim\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateCachesTable extends Migration
{
public function up()
{
$this->schema->create('caches', function(Blueprint $table) {
$table->string('user_id', 64);
$table->string('name', 32);
$table->text('data');
$table->timestamps();
$table->primary(['user_id', 'name']);
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
});
}
public function down()
{
$this->schema->drop('caches');
}
}

5
src/Movim/Bootstrap.php

@ -8,7 +8,9 @@ use App\Configuration;
use Monolog\Logger;
use Monolog\Handler\SyslogHandler;
use Illuminate\Database\Capsule\Manager as Capsule;
use App\Session as DBSession;
use App\User as DBUser;
class Bootstrap
{
@ -252,7 +254,7 @@ class Bootstrap
$l = \Movim\i18n\Locale::start();
if ($user->isLogged()) {
$lang = $user->getConfig('language');
$lang = DBUser::me()->language;
}
if (isset($lang)) {
@ -309,7 +311,6 @@ class Bootstrap
\Modl\Utils::loadModel('Contact');
\Modl\Utils::loadModel('Privacy');
\Modl\Utils::loadModel('RosterLink');
\Modl\Utils::loadModel('Cache');
\Modl\Utils::loadModel('Postn');
\Modl\Utils::loadModel('Info');
\Modl\Utils::loadModel('EncryptedPass');

109
src/Movim/Cache.php

@ -1,109 +0,0 @@
<?php
namespace Movim;
/**
* A fully-static class that deals with caching.
*/
class Cache
{
private static $_instance;
public static function create()
{
if (!is_object(self::$_instance)) {
self::$_instance = new Cache;
}
return self::$_instance;
}
/**
* Helper function to access cache.
*/
public static function c()
{
$cache = self::create();
return call_user_func_array([$cache, 'handle'], func_get_args());
}
/**
* Fetches or commits an object to cache with the provided key.
*
* Prototype: handle(string $key, ...)
*
* The following fetches an object from cache.
* handle('key')
*
* This commits an object to cache.
* handle('key', $object);
*
* Several objects can be commited to cache in this manner:
* handle('key', $object1, $object2, $object3);
* And retrieved as follows:
* list($object1, $object2, $object3) = handle('key');
*/
public function handle($key)
{
$arglist = func_get_args();
$key = $arglist[0];
if (func_num_args() == 1) {
$content = $this->_readCache($key);
if (isset($content) && $content != "") {
return $content;
} else {
return null;
}
}
if (func_num_args() == 2) {
return $this->_writeCache($key, $arglist[1]);
}
// Cutting a piece of the args.
$content = array_slice($arglist, 1);
return $this->_writeCache($key, $content);
}
/**
* Serializes data in a proper fashion.
*/
private function _writeCache($key, $object)
{
$data = str_replace(
"'", "\\'",
base64_encode(gzcompress(serialize($object)))
);
$time = date(\Modl\SQL::SQL_DATE);
$cd = new \Modl\CacheDAO;
$c = new \Modl\Cache;
$c->data = $data;
$c->name = $key;
$c->timestamp = $time;
$cd->set($c);
}
/**
* Unserializes data.
*/
private function _readCache($key)
{
$cd = new \Modl\CacheDAO;
$var = $cd->get($key);
if (isset($var)) {
return unserialize(
gzuncompress(base64_decode(str_replace("\\'", "'", $var->data)))
);
}
return false;
}
}
?>

3
src/Movim/Template/Builder.php

@ -4,6 +4,7 @@ namespace Movim\Template;
use App\Configuration;
use Movim\Controller\Ajax;
use Movim\Widget\Wrapper;
use App\User;
class Builder
{
@ -111,7 +112,7 @@ class Builder
function dir()
{
$this->user->reload(true);
$lang = $this->user->getConfig('language');
$lang = User::me()->language;
if (in_array($lang, ['ar', 'he', 'fa'])) {
$this->dir = 'rtl';

67
src/Movim/User.php

@ -9,23 +9,6 @@ use App\User as DBUser;
class User
{
public $caps;
public $userdir;
public $dbuser;
/**
* Class constructor. Reloads the user's session or attempts to authenticate
* the user.
*/
function __construct($username = false)
{
$s = Session::start();
$this->dbuser = DBUser::firstOrNew(['id' => $s->get('jid')]);
if ($username) {
$s->set('username', $username);
$this->userdir = DOCUMENT_ROOT.'/users/'.$username.'/';
}
}
/**
* @brief Reload the user configuration
@ -36,7 +19,7 @@ class User
if ($session) {
if ($language) {
$lang = $this->getConfig('language');
$lang = DBUser::me()->language;
if (isset($lang)) {
$l = Locale::start();
$l->load($lang);
@ -78,54 +61,6 @@ class User
return $s->get('username');
}
function setConfig(array $config)
{
if (isset($config['language'])) {
$this->dbuser->language = $config['language'];
}
if (isset($config['cssurl'])) {
$this->dbuser->cssurl = $config['cssurl'];
}
if (isset($config['nsfw'])) {
$this->dbuser->nsfw = $config['nsfw'];
}
if (isset($config['nightmode'])) {
$this->dbuser->nightmode = $config['nightmode'];
}
$this->dbuser->save();
$this->reload(true);
}
function getConfig($key = false)
{
if ($key == false) {
return $this->dbuser;
}
return $this->dbuser->{$key};
}
function getDumpedConfig($key = false)
{
if (!file_exists($this->userdir.'config.dump')) {
return [];
}
$config = unserialize(file_get_contents($this->userdir.'config.dump'));
if ($key == false) {
return $config;
}
if (isset($config[$key])) {
return $config[$key];
}
}
function isSupported($key)
{
$this->reload();

Loading…
Cancel
Save