product views

This commit is contained in:
Kerim 2022-06-26 00:11:56 +05:00
parent f037dd7b2d
commit ebbc94d173
581 changed files with 33855 additions and 5 deletions

View File

@ -0,0 +1,14 @@
<?php namespace Akami\Coffe30;
use System\Classes\PluginBase;
class Plugin extends PluginBase
{
public function registerComponents()
{
}
public function registerSettings()
{
}
}

View File

@ -0,0 +1,19 @@
<?php namespace Akami\Coffe30\Controllers;
use Backend\Classes\Controller;
use BackendMenu;
class Slider extends Controller
{
public $implement = [ 'Backend\Behaviors\ListController', 'Backend\Behaviors\FormController', 'Backend\Behaviors\ReorderController' ];
public $listConfig = 'config_list.yaml';
public $formConfig = 'config_form.yaml';
public $reorderConfig = 'config_reorder.yaml';
public function __construct()
{
parent::__construct();
BackendMenu::setContext('Akami.Coffe30', 'main-menu-item', 'side-menu-item');
}
}

View File

@ -0,0 +1,19 @@
<div data-control="toolbar">
<a href="<?= Backend::url('akami/coffe30/slider/create') ?>" class="btn btn-primary oc-icon-plus"><?= e(trans('backend::lang.form.create')) ?></a>
<a href="<?= Backend::url('akami/coffe30/slider/reorder') ?>" class="btn btn-default oc-icon-list"><?= e(trans('backend::lang.reorder.default_title')) ?></a>
<button
class="btn btn-default oc-icon-trash-o"
disabled="disabled"
onclick="$(this).data('request-data', {
checked: $('.control-list').listWidget('getChecked')
})"
data-request="onDelete"
data-request-confirm="<?= e(trans('backend::lang.list.delete_selected_confirm')) ?>"
data-trigger-action="enable"
data-trigger=".control-list input[type=checkbox]"
data-trigger-condition="checked"
data-request-success="$(this).prop('disabled', true)"
data-stripe-load-indicator>
<?= e(trans('backend::lang.list.delete_selected')) ?>
</button>
</div>

View File

@ -0,0 +1,3 @@
<div data-control="toolbar">
<a href="<?= Backend::url('akami/coffe30/slider') ?>" class="btn btn-primary oc-icon-caret-left"><?= e(trans('backend::lang.form.return_to_list')) ?></a>
</div>

View File

@ -0,0 +1,10 @@
name: Slider
form: $/akami/coffe30/models/slider/fields.yaml
modelClass: Akami\Coffe30\Models\Slider
defaultRedirect: akami/coffe30/slider
create:
redirect: 'akami/coffe30/slider/update/:id'
redirectClose: akami/coffe30/slider
update:
redirect: akami/coffe30/slider
redirectClose: akami/coffe30/slider

View File

@ -0,0 +1,12 @@
list: $/akami/coffe30/models/slider/columns.yaml
modelClass: Akami\Coffe30\Models\Slider
title: Slider
noRecordsMessage: 'backend::lang.list.no_records'
showSetup: true
showCheckboxes: true
recordsPerPage: 20
toolbar:
buttons: list_toolbar
search:
prompt: 'backend::lang.list.search_prompt'
recordUrl: 'akami/coffe30/slider/update/:id'

View File

@ -0,0 +1,4 @@
title: Slider
modelClass: Akami\Coffe30\Models\Slider
toolbar:
buttons: reorder_toolbar

View File

@ -0,0 +1,46 @@
<?php Block::put('breadcrumb') ?>
<ul>
<li><a href="<?= Backend::url('akami/coffe30/slider') ?>">Slider</a></li>
<li><?= e($this->pageTitle) ?></li>
</ul>
<?php Block::endPut() ?>
<?php if (!$this->fatalError): ?>
<?= Form::open(['class' => 'layout']) ?>
<div class="layout-row">
<?= $this->formRender() ?>
</div>
<div class="form-buttons">
<div class="loading-indicator-container">
<button
type="submit"
data-request="onSave"
data-hotkey="ctrl+s, cmd+s"
data-load-indicator="<?= e(trans('backend::lang.form.saving')) ?>"
class="btn btn-primary">
<?= e(trans('backend::lang.form.create')) ?>
</button>
<button
type="button"
data-request="onSave"
data-request-data="close:1"
data-hotkey="ctrl+enter, cmd+enter"
data-load-indicator="<?= e(trans('backend::lang.form.saving')) ?>"
class="btn btn-default">
<?= e(trans('backend::lang.form.create_and_close')) ?>
</button>
<span class="btn-text">
<?= e(trans('backend::lang.form.or')) ?> <a href="<?= Backend::url('akami/coffe30/slider') ?>"><?= e(trans('backend::lang.form.cancel')) ?></a>
</span>
</div>
</div>
<?= Form::close() ?>
<?php else: ?>
<p class="flash-message static error"><?= e(trans($this->fatalError)) ?></p>
<p><a href="<?= Backend::url('akami/coffe30/slider') ?>" class="btn btn-default"><?= e(trans('backend::lang.form.return_to_list')) ?></a></p>
<?php endif ?>

View File

@ -0,0 +1 @@
<?= $this->listRender() ?>

View File

@ -0,0 +1,22 @@
<?php Block::put('breadcrumb') ?>
<ul>
<li><a href="<?= Backend::url('akami/coffe30/slider') ?>">Slider</a></li>
<li><?= e($this->pageTitle) ?></li>
</ul>
<?php Block::endPut() ?>
<?php if (!$this->fatalError): ?>
<div class="form-preview">
<?= $this->formRenderPreview() ?>
</div>
<?php else: ?>
<p class="flash-message static error"><?= e($this->fatalError) ?></p>
<?php endif ?>
<p>
<a href="<?= Backend::url('akami/coffe30/slider') ?>" class="btn btn-default oc-icon-chevron-left">
<?= e(trans('backend::lang.form.return_to_list')) ?>
</a>
</p>

View File

@ -0,0 +1,8 @@
<?php Block::put('breadcrumb') ?>
<ul>
<li><a href="<?= Backend::url('akami/coffe30/slider') ?>">Slider</a></li>
<li><?= e($this->pageTitle) ?></li>
</ul>
<?php Block::endPut() ?>
<?= $this->reorderRender() ?>

View File

@ -0,0 +1,54 @@
<?php Block::put('breadcrumb') ?>
<ul>
<li><a href="<?= Backend::url('akami/coffe30/slider') ?>">Slider</a></li>
<li><?= e($this->pageTitle) ?></li>
</ul>
<?php Block::endPut() ?>
<?php if (!$this->fatalError): ?>
<?= Form::open(['class' => 'layout']) ?>
<div class="layout-row">
<?= $this->formRender() ?>
</div>
<div class="form-buttons">
<div class="loading-indicator-container">
<button
type="submit"
data-request="onSave"
data-request-data="redirect:0"
data-hotkey="ctrl+s, cmd+s"
data-load-indicator="<?= e(trans('backend::lang.form.saving')) ?>"
class="btn btn-primary">
<?= e(trans('backend::lang.form.save')) ?>
</button>
<button
type="button"
data-request="onSave"
data-request-data="close:1"
data-hotkey="ctrl+enter, cmd+enter"
data-load-indicator="<?= e(trans('backend::lang.form.saving')) ?>"
class="btn btn-default">
<?= e(trans('backend::lang.form.save_and_close')) ?>
</button>
<button
type="button"
class="oc-icon-trash-o btn-icon danger pull-right"
data-request="onDelete"
data-load-indicator="<?= e(trans('backend::lang.form.deleting')) ?>"
data-request-confirm="<?= e(trans('backend::lang.form.confirm_delete')) ?>">
</button>
<span class="btn-text">
<?= e(trans('backend::lang.form.or')) ?> <a href="<?= Backend::url('akami/coffe30/slider') ?>"><?= e(trans('backend::lang.form.cancel')) ?></a>
</span>
</div>
</div>
<?= Form::close() ?>
<?php else: ?>
<p class="flash-message static error"><?= e(trans($this->fatalError)) ?></p>
<p><a href="<?= Backend::url('akami/coffe30/slider') ?>" class="btn btn-default"><?= e(trans('backend::lang.form.return_to_list')) ?></a></p>
<?php endif ?>

View File

@ -0,0 +1,6 @@
<?php return [
'plugin' => [
'name' => 'Coffe30',
'description' => ''
]
];

View File

@ -0,0 +1,29 @@
<?php namespace Akami\Coffe30\Models;
use Model;
/**
* Model
*/
class Slider extends Model
{
use \October\Rain\Database\Traits\Validation;
/*
* Disable timestamps by default.
* Remove this line if timestamps are defined in the database table.
*/
public $timestamps = false;
/**
* @var string The database table used by the model.
*/
public $table = 'akami_coffe30_slider';
/**
* @var array Validation rules
*/
public $rules = [
];
}

View File

@ -0,0 +1,15 @@
columns:
id:
label: id
type: number
sortable: true
img:
label: img
type: text
searchable: true
sortable: true
url:
label: url
type: text
searchable: true
sortable: true

View File

@ -0,0 +1,9 @@
fields:
img:
label: Img
span: auto
type: mediafinder
url:
label: Url
span: auto
type: text

View File

@ -0,0 +1,16 @@
plugin:
name: 'akami.coffe30::lang.plugin.name'
description: 'akami.coffe30::lang.plugin.description'
author: AKAMI
icon: oc-icon-building-o
homepage: ''
navigation:
main-menu-item:
label: Maglumatlar
url: akami/coffe30/slider
icon: icon-building
sideMenu:
side-menu-item:
label: Slider
url: akami/coffe30/slider
icon: icon-image

View File

@ -0,0 +1,23 @@
<?php namespace Akami\Coffe30\Updates;
use Schema;
use October\Rain\Database\Updates\Migration;
class BuilderTableCreateAkamiCoffe30Slider extends Migration
{
public function up()
{
Schema::create('akami_coffe30_slider', function($table)
{
$table->engine = 'InnoDB';
$table->increments('id')->unsigned();
$table->string('img');
$table->string('url')->nullable();
});
}
public function down()
{
Schema::dropIfExists('akami_coffe30_slider');
}
}

View File

@ -0,0 +1,5 @@
1.0.1:
- 'Initialize plugin.'
1.0.2:
- 'Created table akami_coffe30_slider'
- builder_table_create_akami_coffe30_slider.php

View File

@ -0,0 +1,70 @@
<?php
namespace AndreiShilov\UTMSaver;
use AndreiShilov\UTMSaver\Classes\UTM;
use Cms\Classes\Controller;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use System\Classes\PluginBase;
class Plugin extends PluginBase
{
public function pluginDetails()
{
return [
'name' => 'andreishilov.utmsaver::lang.plugin.name',
'description' => 'andreishilov.utmsaver::lang.plugin.description',
'author' => 'andreishilov.utmsaver::lang.plugin.author',
'icon' => 'icon-magnet'
];
}
public function boot()
{
if (!App::runningInBackend()) {
Event::listen('cms.page.start', function (Controller $controller) {
Facades\UTM::save();
});
}
}
public function register()
{
App::singleton('AndreiShilov.UTM', function () {
return UTM::instance();
});
}
public function registerSettings()
{
return [
'config' => [
'label' => 'andreishilov.utmsaver::lang.settings.label',
'description' => 'andreishilov.utmsaver::lang.settings.description',
'icon' => 'icon-magnet',
'class' => 'AndreiShilov\UTMSaver\Models\Settings',
'permissions' => ['andreishilov.utmsaver.settings'],
]
];
}
public function registerPermissions()
{
return [
'andreishilov.utmsaver.settings' => [
'label' => 'andreishilov.utmsaver::lang.plugin.name',
],
];
}
public function registerMarkupTags()
{
return [
'functions' => [
'utm' => function ($utmTag) {
return Facades\UTM::get($utmTag);
},
]
];
}
}

View File

@ -0,0 +1,74 @@
<?php
namespace AndreiShilov\UTMSaver\Classes;
use AndreiShilov\UTMSaver\Models\Settings;
use Cookie;
use October\Rain\Support\Traits\Singleton;
class UTM
{
use Singleton;
const UTM = [
'utm_source',
'utm_campaign',
'utm_medium',
'utm_term',
'utm_content',
];
/**
* @var array
*/
protected $utm = [];
public function save()
{
foreach (self::UTM as $item) {
$value = Cookie::get($item);
if ($value !== null) {
$this->utm[$item] = $value;
}
}
if (count(request()->all()) > 0) {
$UTM = [];
foreach (request()->all() as $key => $value) {
if (in_array($key, self::UTM)) {
$UTM[$key] = trim($value);
}
}
if (count($UTM) > 0) {
$ttl = Settings::get('cookie_ttl', 30) * 24 * 60;
foreach (self::UTM as $tag) {
if (isset($UTM[$tag])) {
$this->utm[$tag] = $UTM[$tag];
Cookie::queue(Cookie::make($tag, $UTM[$tag], $ttl));
} else {
unset($this->utm[$tag]);
Cookie::forget($tag);
}
}
}
}
}
/**
* @param $utmTag
* @return string|null
*/
public function get($utmTag)
{
return $this->utm[$utmTag] ?? null;
}
/**
* @return array
*/
public function all()
{
return $this->utm;
}
}

View File

@ -0,0 +1,8 @@
{
"name": "andreishilov/utmsaver-plugin",
"type": "october-plugin",
"description": "None",
"require": {
"composer/installers": "~1.0"
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace AndreiShilov\UTMSaver\Facades;
use October\Rain\Support\Facade;
/**
* @method static string get($tag)
* @method static array all()
* @method static void save()
*/
class UTM extends Facade
{
protected static function getFacadeAccessor()
{
return 'AndreiShilov.UTM';
}
}

View File

@ -0,0 +1,22 @@
<?php
return [
'plugin' => [
'name' => 'UTM Saver',
'description' => 'Plugin allows to save visitors utm to cookie',
'author' => 'Andrei Shilov',
],
'config' => [
'cookie_ttl' => [
'title' => 'UTM ttl, days',
'description' => 'Cookies time of living'
],
'cookie_prefix' => [
'title' => 'Prefix cookie',
'description' => 'You can set cookie prefix to avoid conflicts with another modules'
],
],
'settings' => [
'label' => 'UTM Saver',
'description' => 'Setting of UTM Saver module',
],
];

View File

@ -0,0 +1,22 @@
<?php
return [
'plugin' => [
'name' => 'UTM Saver',
'description' => 'Плагин позволяет сохранять utm-метки посетителя в cookie',
'author' => 'Андрей Шилов',
],
'config' => [
'cookie_ttl' => [
'title' => 'UTM ttl, дней',
'description' => 'Время жизни cookie'
],
'cookie_prefix' => [
'title' => 'Префикс cookie',
'description' => 'Можно указать для избежания конфликтов имен cookie с другими модулями'
],
],
'settings' => [
'label' => 'UTM Saver',
'description' => 'Настройки модуля UTM Saver',
],
];

View File

@ -0,0 +1,13 @@
<?php
namespace AndreiShilov\UTMSaver\Models;
use Model;
class Settings extends Model
{
public $implement = ['System.Behaviors.SettingsModel'];
public $settingsCode = 'andreishilov_utmsaver_settings';
public $settingsFields = 'fields.yaml';
}

View File

@ -0,0 +1,7 @@
fields:
cookie_ttl:
label: andreishilov.utmsaver::lang.config.cookie_ttl.title
comment: andreishilov.utmsaver::lang.config.cookie_ttl.description
span: left
type: number
default: 30

View File

@ -0,0 +1,4 @@
1.0.1:
- Initialize plugin.
1.0.2:
- Method \AndreiShilov\UTMSaver\Facades\UTM::all() added

View File

@ -0,0 +1,154 @@
<?php
namespace AndreiShilov\UTMShopaholic;
use AndreiShilov\UTMSaver\Facades\UTM;
use Backend\Widgets\Filter;
use Backend\Widgets\Form;
use Backend\Widgets\Lists;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Lovata\OrdersShopaholic\Classes\Processor\OrderProcessor;
use Lovata\OrdersShopaholic\Controllers\Orders;
use Lovata\OrdersShopaholic\Models\Order;
use October\Rain\Database\Builder;
use October\Rain\Database\Model;
use System\Classes\PluginBase;
use Lang;
class Plugin extends PluginBase
{
public $require = [
'AndreiShilov.UTMSaver',
'Lovata.Shopaholic',
'Lovata.OrdersShopaholic',
];
public function pluginDetails()
{
return [
'name' => 'andreishilov.utmshopaholic::lang.plugin.name',
'description' => 'andreishilov.utmshopaholic::lang.plugin.description',
'author' => 'andreishilov.utmshopaholic::lang.plugin.author',
'icon' => 'icon-magnet'
];
}
public function registerPermissions()
{
return [
'andreishilov.utmshopaholic.widgets' => [
'label' => 'andreishilov.utmshopaholic::lang.plugin.name',
],
];
}
public function registerReportWidgets()
{
return [
'AndreiShilov\UTMShopaholic\ReportWidgets\SourcesOfOrders' => [
'label' => 'andreishilov.utmshopaholic::lang.reportwidget.sourcesoforders.name',
'context' => 'dashboard',
'permissions' => [
'andreishilov.utmshopaholic.widgets',
],
],
];
}
public function boot()
{
Event::listen(OrderProcessor::EVENT_ORDER_CREATED, function ($obOrder) {
if (!App::runningInBackend()) {
UTM::save();
$utmParameters = UTM::all();
if (count($utmParameters) > 0) {
$utm = new Models\UTM($utmParameters);
$utm->order()->associate($obOrder);
$utm->save();
}
}
});
Order::extend(function ($model) {
$model->hasOne['utm'] = [
Models\UTM::class,
'delete' => true
];
$model->addDynamicMethod('scopeHasUtmLike', function (Builder $query, $value) {
$query->whereHas('utm', function (Builder $query) use ($value) {
$query->where('utm_source', 'like', '%' . $value . '%')
->orWhere('utm_campaign', 'like', '%' . $value . '%')
->orWhere('utm_medium', 'like', '%' . $value . '%')
->orWhere('utm_term', 'like', '%' . $value . '%')
->orWhere('utm_content', 'like', '%' . $value . '%');
});
});
});
Event::listen('backend.form.extendFields', function (Form $widget) {
if (!$widget->getController() instanceof Orders || !$widget->model instanceof Order) {
return;
}
$widget->addTabFields([
'utm' => [
'type' => 'partial',
'tab' => 'UTM',
'path' => '$/andreishilov/utmshopaholic/controllers/orders/_field_utmparameters.htm',
]
]);
});
Orders::extend(function ($controller) {
$myConfigPath = '$/andreishilov/utmshopaholic/controllers/orders/config_relation.yaml';
if (!isset($controller->relationConfig)) {
$controller->addDynamicProperty('relationConfig');
}
$controller->relationConfig = $controller->mergeConfig(
$controller->relationConfig,
$myConfigPath
);
});
Orders::extendListColumns(function (Lists $list, Model $model) {
if (!$model instanceof Order) {
return;
}
$utm = [
'utm_source',
'utm_campaign',
'utm_medium',
'utm_term',
'utm_content',
];
foreach ($utm as $parameter) {
$list->addColumns([
'utm[' . $parameter . ']' => [
'label' => Lang::get('andreishilov.utmshopaholic::lang.utm.' . $parameter),
'sortable' => false,
],
]);
}
});
Event::listen('backend.filter.extendScopes', function (Filter $filterWidget) {
if (!$filterWidget->getController() instanceof Orders) {
return;
}
$filterWidget->addScopes([
'utm' => [
'label' => 'utm',
'type' => 'text',
'scope' => 'hasUtmLike',
]
]);
});
}
}

View File

@ -0,0 +1,8 @@
{
"name": "andreishilov/utmshopaholic-plugin",
"type": "october-plugin",
"description": "None",
"require": {
"composer/installers": "~1.0"
}
}

View File

@ -0,0 +1 @@
<?= $this->relationRender('utm') ?>

View File

@ -0,0 +1,8 @@
utm:
label: UTM
view:
form: $/andreishilov/utmshopaholic/models/utm/fields.yaml
toolbarButtons: update|delete
manage:
form: $/andreishilov/utmshopaholic/models/utm/fields.yaml
list: $/andreishilov/utmshopaholic/models/utm/columns.yaml

View File

@ -0,0 +1,22 @@
<?php return [
'plugin' => [
'name' => 'UTM Analytics for Shopaholic',
'description' => 'Plugin provides UTM-analytics for Shopaholic orders',
'author' => 'Andrei Shilov',
],
'reportwidget' => [
'sourcesoforders' => [
'name' => 'Sources of orders',
'parameters' => [
'days' => 'Days'
]
]
],
'utm' => [
'utm_source' => 'UTM Source',
'utm_campaign' => 'UTM Campaign',
'utm_medium' => 'UTM Medium',
'utm_term' => 'UTM Term',
'utm_content' => 'UTM Content',
]
];

View File

@ -0,0 +1,22 @@
<?php return [
'plugin' => [
'name' => 'UTM Аналитика для Shopaholic',
'description' => 'Плагин предоставляет аналитику UTM для заказов Shopaholic',
'author' => 'Андрей Шилов',
],
'reportwidget' => [
'sourcesoforders' => [
'name' => 'Источники заказов',
'parameters' => [
'days' => 'Дней'
]
]
],
'utm' => [
'utm_source' => 'UTM Source',
'utm_campaign' => 'UTM Campaign',
'utm_medium' => 'UTM Medium',
'utm_term' => 'UTM Term',
'utm_content' => 'UTM Content',
]
];

View File

@ -0,0 +1,49 @@
<?php namespace AndreiShilov\UTMShopaholic\Models;
use Lovata\OrdersShopaholic\Models\Order;
use October\Rain\Support\Str;
/**
* Model
*/
class UTM extends \Model
{
protected $fillable = ['order_id', 'utm_source', 'utm_campaign', 'utm_medium', 'utm_term', 'utm_content'];
public $timestamps = false;
/**
* @var string The database table used by the model.
*/
public $table = 'andreishilov_utmshopaholic_utm';
public $belongsTo = [
'order' => [
Order::class
],
];
public function setUtmSourceAttribute($value)
{
$this->attributes['utm_source'] = Str::substr($value, 0 , 128);
}
public function setUtmCampaignAttribute($value)
{
$this->attributes['utm_campaign'] = Str::substr($value, 0 , 128);
}
public function setUtmMediumAttribute($value)
{
$this->attributes['utm_medium'] = Str::substr($value, 0 , 128);
}
public function setUtmTermAttribute($value)
{
$this->attributes['utm_term'] = Str::substr($value, 0 , 512);
}
public function setUtmContentAttribute($value)
{
$this->attributes['utm_content'] = Str::substr($value, 0 , 128);
}
}

View File

@ -0,0 +1,21 @@
columns:
utm_source:
label: UTM Source
type: text
searchable: true
utm_campaign:
label: UTM Campaign
type: text
searchable: true
utm_medium:
label: UTM Medium
type: text
searchable: true
utm_term:
label: UTM Term
type: text
searchable: true
utm_content:
label: UTM Content
type: text
searchable: true

View File

@ -0,0 +1,21 @@
fields:
utm_source:
label: UTM Source
span: full
type: text
utm_campaign:
label: UTM Campaign
span: full
type: text
utm_medium:
label: UTM Medium
span: full
type: text
utm_term:
label: UTM Term
span: full
type: text
utm_content:
label: UTM Content
span: full
type: text

View File

@ -0,0 +1,56 @@
<?php
namespace AndreiShilov\UTMShopaholic\ReportWidgets;
use Backend\Classes\ReportWidgetBase;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Carbon;
use Lovata\OrdersShopaholic\Models\Order;
use Illuminate\Support\Facades\DB;
class SourcesOfOrders extends ReportWidgetBase
{
public function defineProperties()
{
return [
'days' => [
'title' => 'Number of days',
'default' => '30',
'type' => 'string',
'validationPattern' => '^[0-9]+$'
],
];
}
public function render()
{
$options = $this->getProperties();
$dateFrom = Carbon::today()->addDays(-$options['days']);
$query = Order::query()
->join('andreishilov_utmshopaholic_utm', function (JoinClause $join) {
$join->on('andreishilov_utmshopaholic_utm.order_id', '=', 'lovata_orders_shopaholic_orders.id');
})
->groupBy('andreishilov_utmshopaholic_utm.utm_source')
->where('lovata_orders_shopaholic_orders.created_at', '>=', $dateFrom)
->orderBy('amount', 'desc')
->select([
DB::raw('count(lovata_orders_shopaholic_orders.id) as amount'),
'andreishilov_utmshopaholic_utm.utm_source as utm_source'
]);
$items = $query->get();
$this->vars['days'] = $options['days'];
$this->vars['data'] = [
'items' => $items->toArray(),
'total' => 0,
];
foreach ($items as $item) {
$this->vars['data']['total'] += $item['amount'];
}
return $this->makePartial('widget');
}
}

View File

@ -0,0 +1,16 @@
<div class="report-widget">
<h3><?= Lang::get('andreishilov.utmshopaholic::lang.reportwidget.sourcesoforders.name') ?></h3>
<div class="control-chart" data-control="chart-pie" data-size="200" data-center-text="<?php echo $data['total']?>">
<ul>
<?php foreach($data['items'] as $item) {?>
<li><?php echo $item['utm_source']?>
<span><?php echo $item['amount']?></span></li>
<?php } ?>
</ul>
</div>
<p class="report-description">
<?= Lang::get('andreishilov.utmshopaholic::lang.reportwidget.sourcesoforders.parameters.days') ?>
: <?php echo $days?>
</p>
</div>

View File

@ -0,0 +1,32 @@
<?php
namespace AndreiShilov\UTMShopaholic\Updates;
use October\Rain\Database\Schema\Blueprint;
use Schema;
use October\Rain\Database\Updates\Migration;
class CreateUTMTable extends Migration
{
public function up()
{
Schema::create('andreishilov_utmshopaholic_utm', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('order_id')->unsigned()->nullable()->unique();
$table->string('utm_source', 128)->nullable();
$table->string('utm_campaign', 128)->nullable();
$table->string('utm_medium', 128)->nullable();
$table->string('utm_term', 512)->nullable();
$table->string('utm_content', 128)->nullable();
$table->index('utm_source');
$table->index('utm_campaign');
});
}
public function down()
{
Schema::dropIfExists('andreishilov_utmshopaholic_utm');
}
}

View File

@ -0,0 +1,5 @@
1.0.1:
- 'Initialize plugin.'
- 'create_utm_table.php'
1.0.2:
- Shopaholic plugin added to dependencies

View File

@ -0,0 +1,61 @@
<?php namespace Codecycler\InvoiceShopaholic;
use Backend;
use System\Classes\PluginBase;
use Codecycler\InvoiceShopaholic\NotifyRules\GenerateInvoicePdf;
/**
* InvoiceShopaholic Plugin Information File
*/
class Plugin extends PluginBase
{
public $require = [
'Codecycler.NotifyShopaholic',
'RainLab.Notify',
'Lovata.Shopaholic',
'Lovata.OrdersShopaholic',
];
/**
* Returns information about this plugin.
*
* @return array
*/
public function pluginDetails()
{
return [
'name' => 'Invoice for Shopaholic',
'description' => 'Adds a send invoice action to the notify plugin',
'author' => 'Codecycler',
'icon' => 'icon-bell-o',
];
}
/**
* Register method, called when the plugin is first registered.
*
* @return void
*/
public function register()
{
}
/**
* Boot method, called right before the request route.
*
* @return array
*/
public function boot()
{
}
public function registerNotificationRules()
{
return [
'actions' => [
GenerateInvoicePdf::class,
],
];
}
}

View File

@ -0,0 +1,8 @@
{
"name": "codecycler/invoiceshopaholic-plugin",
"type": "october-plugin",
"description": "None",
"require": {
"composer/installers": "~1.0"
}
}

View File

@ -0,0 +1,75 @@
<?php namespace Codecycler\InvoiceShopaholic\NotifyRules;
use Twig;
use Mail;
use System\Models\MailTemplate;
use Renatio\DynamicPDF\Classes\PDF;
use RainLab\Notify\Classes\ActionBase;
use Renatio\DynamicPDF\Models\Template;
use Lovata\OrdersShopaholic\Models\Order;
use Lovata\OrdersShopaholic\Classes\Item\OrderItem;
class GenerateInvoicePdf extends ActionBase
{
public function actionDetails()
{
return [
'name' => 'Generate an invoice and send it to the customer',
'description' => 'Generate an invoice for the given order and send to customer',
'icon' => 'icon-envelope',
];
}
public function triggerAction($params)
{
$sOrderNumber = $params['order_number'];
// Get the invoice by order number
$obOrder = Order::getByNumber($sOrderNumber)->first();
// Generate PDF by template
$filename = storage_path('app/uploads/invoice-' . $sOrderNumber . '.pdf');
//
$data = array_merge($params, [
'obOrder' => $obOrder,
'arOrder' => OrderItem::make($obOrder->id),
]);
//
PDF::loadTemplate($this->host->pdf_template, $data)
->save($filename);
//
Mail::send($this->host->mail_template, $data, function ($message) use ($data, $filename) {
$twig = new Twig\Environment(new Twig\Loader\ArrayLoader([
'subject' => $this->host->email_subject,
'to' => $this->host->email_address,
]));
$message->subject($twig->render('subject', $data));
$message->to($twig->render('to', $data));
$message->attach($filename);
});
}
public function getMailTemplateOptions()
{
$codes = array_keys(MailTemplate::listAllTemplates());
$result = array_combine($codes, $codes);
return $result;
}
public function getPdfTemplateOptions()
{
$codes = Template::all()->pluck('code')->toArray();
$result = array_combine($codes, $codes);
return $result;
}
public function defineFormFields()
{
return 'fields.yaml';
}
}

View File

@ -0,0 +1,23 @@
fields:
mail_template:
label: Mail template
type: dropdown
placeholder: Select template
span: left
pdf_template:
label: PDF template
type: dropdown
placeholder: Select template
span: right
order_number:
label: Order number
type: text
span: left
email_subject:
label: Email subject
type: text
span: left
email_address:
label: Email address
type: text
span: left

View File

@ -0,0 +1,2 @@
1.0.1: First version of InvoiceShopaholic
1.0.2: Added requirements to plugins

View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,79 @@
<?php namespace Codecycler\NotifyShopaholic;
use Event;
use Backend;
use System\Classes\PluginBase;
use RainLab\Notify\Classes\Notifier;
use Lovata\OrdersShopaholic\Classes\Processor\OrderProcessor;
use Codecycler\NotifyShopaholic\NotifyRules\Events\OrderCreated;
use Codecycler\NotifyShopaholic\NotifyRules\Events\OrderUpdated;
use Codecycler\NotifyShopaholic\Classes\Events\ExtendOrderModel;
use Codecycler\NotifyShopaholic\NotifyRules\Conditions\OrderStatus;
/**
* NotifyShopaholic Plugin Information File
*/
class Plugin extends PluginBase
{
public $require = [
'Lovata.Shopaholic',
'Lovata.OrdersShopaholic',
];
/**
* Returns information about this plugin.
*
* @return array
*/
public function pluginDetails()
{
return [
'name' => 'codecycler.notifyshopaholic::lang.plugin.name',
'description' => 'codecycler.notifyshopaholic::lang.plugin.description',
'author' => 'Codecycler',
'icon' => 'icon-bell-o'
];
}
public function boot()
{
Event::subscribe(ExtendOrderModel::class);
}
public function register()
{
$this->bindNotificationEvents();
}
public function registerNotificationRules()
{
return [
'groups' => [
'shopaholic' => [
'label' => 'Shopaholic',
'icon' => 'icon-shopping-cart'
],
],
'events' => [
OrderCreated::class,
OrderUpdated::class,
],
'actions' => [],
'conditions' => [
OrderStatus::class,
],
];
}
public function bindNotificationEvents()
{
if (! class_exists(Notifier::class)) {
return;
}
Notifier::bindEvents([
OrderProcessor::EVENT_ORDER_CREATED => OrderCreated::class,
ExtendOrderModel::EVENT_ORDER_UPDATED => OrderUpdated::class,
]);
}
}

View File

@ -0,0 +1,23 @@
# oc-notifyshopaholic-plugin
This plugin can be used for automating Shopaholic using the `RainLab.Notify` plugin.
## Installation
You can easily install this plugin by requiring it as a dependency in your composer project. Just run `composer require codecycler/oc-notifyshopaholic-plugin` or manually add it to your `composer.json` file to install this plugin.
## Events
### OrderCreated
Binded to `OrderProcessor::EVENT_ORDER_CREATED`
### OrderUpdated
Binded to `Codecycler\NotifyShopaholic\Classes\Events\ExtendOrderModel::EVENT_ORDER_UPDATED` which listens to the `afterUpdate` event for the `Order` model.
## Roadmap
More events, conditions and actions will be developed when needed by our projects.
## Contribution
Please feel free to contribute by creating a PR and submitting it to the **develop** branch.
## License
&copy; 2021, [Codecycler](https://codecycler.com) under [GNU GPL v3](https://opensource.org/licenses/GPL-3.0). <br />
<i>This plugin is sponsored by [Codecycler](https://codecycler.com)</i>

View File

@ -0,0 +1,18 @@
<?php namespace Codecycler\NotifyShopaholic\Classes\Events;
use Event;
use Lovata\OrdersShopaholic\Models\Order;
class ExtendOrderModel
{
const EVENT_ORDER_UPDATED = 'shopaholic.order.updated';
public function subscribe()
{
Order::extend(function ($obOrder) {
$obOrder->bindEvent('model.afterUpdate', function () use ($obOrder) {
Event::fire(self::EVENT_ORDER_UPDATED, $obOrder);
});
});
}
}

View File

@ -0,0 +1,8 @@
{
"name": "codecycler/notifyshopaholic-plugin",
"type": "october-plugin",
"description": "None",
"require": {
"composer/installers": "~1.0"
}
}

View File

@ -0,0 +1,34 @@
<?php return [
'plugin' => [
'name' => 'Shopaholic for Notify',
'description' => 'Shopaholic integration for the RainLab.Notify plugin for October CMS',
],
'events' => [
'order_created' => [
'name' => 'Order created',
'description' => 'When an order is created',
'group' => 'shopaholic',
],
'order_updated' => [
'name' => 'Order updated',
'description' => 'When an order is updated',
'group' => 'shopaholic',
],
],
'rules' => [
'title' => [
'order_number' => 'Order number',
'name' => 'Name',
'last_name' => 'Last name',
'email' => 'Emailaddress',
],
'label' => [
'order_number' => 'The order number',
'name' => 'Name of the user',
'last_name' => 'Last name of the user',
'email' => 'Emailaddress of the user',
],
],
];

View File

@ -0,0 +1,42 @@
<?php namespace Codecycler\NotifyShopaholic\NotifyRules\Conditions;
use RainLab\Notify\Classes\ConditionBase;
use Lovata\OrdersShopaholic\Models\Order;
use Lovata\OrdersShopaholic\Models\Status;
class OrderStatus extends ConditionBase
{
public function getConditionType()
{
return ConditionBase::TYPE_ANY;
}
public function getName()
{
return 'Order status attribute';
}
public function getText()
{
return 'Order status attribute';
}
public function isTrue(&$params)
{
if (!$order = array_get($params, 'order')) {
throw new ApplicationException('Error evaluating the order attribute condition: the order object is not found in the condition parameters.');
}
return $order->status_id == $this->host->status_id;
}
public function getStatusIdOptions()
{
return Status::all()->pluck('name', 'id')->toArray();
}
public function defineFormFields()
{
return 'fields.yaml';
}
}

View File

@ -0,0 +1,5 @@
fields:
status_id:
label: Status
type: dropdown
span: full

View File

@ -0,0 +1,55 @@
<?php namespace Codecycler\NotifyShopaholic\NotifyRules\Events;
use RainLab\Notify\Classes\EventBase;
class OrderCreated extends EventBase
{
public $conditions = [];
public function eventDetails()
{
return [
'name' => e(trans('codecycler.notifyshopaholic::lang.events.order_created.name')),
'description' => e(trans('codecycler.notifyshopaholic::lang.events.order_created.description')),
'group' => e(trans('codecycler.notifyshopaholic::lang.events.order_created.group')),
];
}
public function defineParams()
{
return [
'order_number' => [
'title' => e(trans('codecycler.notifyshopaholic::lang.rules.title.order_number')),
'label' => e(trans('codecycler.notifyshopaholic::lang.rules.label.order_number')),
],
'name' => [
'title' => e(trans('codecycler.notifyshopaholic::lang.rules.title.name')),
'label' => e(trans('codecycler.notifyshopaholic::lang.rules.label.name')),
],
'last_name' => [
'title' => e(trans('codecycler.notifyshopaholic::lang.rules.title.last_name')),
'label' => e(trans('codecycler.notifyshopaholic::lang.rules.label.last_name')),
],
'email' => [
'title' => e(trans('codecycler.notifyshopaholic::lang.rules.title.email')),
'label' => e(trans('codecycler.notifyshopaholic::lang.rules.label.email')),
],
];
}
public static function makeParamsFromEvent(array $args, $eventName = null)
{
$obOrder = array_get($args, 0);
$data = [
'order_number' => $obOrder->order_number,
'name' => $obOrder->getProperty('name'),
'last_name' => $obOrder->getProperty('last_name'),
'email' => $obOrder->getProperty('email'),
'user' => $obOrder->getProperty('email'),
'order' => $obOrder,
];
return $data;
}
}

View File

@ -0,0 +1,55 @@
<?php namespace Codecycler\NotifyShopaholic\NotifyRules\Events;
use RainLab\Notify\Classes\EventBase;
class OrderUpdated extends EventBase
{
public $conditions = [];
public function eventDetails()
{
return [
'name' => e(trans('codecycler.notifyshopaholic::lang.events.order_updated.name')),
'description' => e(trans('codecycler.notifyshopaholic::lang.events.order_updated.description')),
'group' => e(trans('codecycler.notifyshopaholic::lang.events.order_updated.group')),
];
}
public function defineParams()
{
return [
'order_number' => [
'title' => e(trans('codecycler.notifyshopaholic::lang.rules.title.order_number')),
'label' => e(trans('codecycler.notifyshopaholic::lang.rules.label.order_number')),
],
'name' => [
'title' => e(trans('codecycler.notifyshopaholic::lang.rules.title.name')),
'label' => e(trans('codecycler.notifyshopaholic::lang.rules.label.name')),
],
'last_name' => [
'title' => e(trans('codecycler.notifyshopaholic::lang.rules.title.last_name')),
'label' => e(trans('codecycler.notifyshopaholic::lang.rules.label.last_name')),
],
'email' => [
'title' => e(trans('codecycler.notifyshopaholic::lang.rules.title.email')),
'label' => e(trans('codecycler.notifyshopaholic::lang.rules.label.email')),
],
];
}
public static function makeParamsFromEvent(array $args, $eventName = null)
{
$obOrder = array_get($args, 0);
$data = [
'order_number' => $obOrder->order_number,
'name' => $obOrder->getProperty('name'),
'last_name' => $obOrder->getProperty('last_name'),
'email' => $obOrder->getProperty('email'),
'user' => $obOrder->getProperty('email'),
'order' => $obOrder,
];
return $data;
}
}

View File

@ -0,0 +1,7 @@
1.0.1:
- First version of NotifyShopaholic
- Added Order Created event
1.0.2:
- Added installation instructions to the documentation
1.0.3:
- Ready for marketplace!

View File

@ -0,0 +1,7 @@
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit347031eccba95821db30e6a679fe62e3::getLoader();

View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,48 @@
<?php namespace Codecycler\Extend;
use Backend;
use System\Classes\PluginBase;
use Codecycler\Extend\Classes\ExtensionManager;
/**
* Extend Plugin Information File
*/
class Plugin extends PluginBase
{
/**
* Returns information about this plugin.
*
* @return array
*/
public function pluginDetails()
{
return [
'name' => 'Extend',
'description' => 'Extending October CMS plugins tool',
'author' => 'Codecycler',
'icon' => 'icon-external-link-square'
];
}
/**
* Register method, called when the plugin is first registered.
*
* @return void
*/
public function register()
{
ExtensionManager::instance()
->load();
}
/**
* Boot method, called right before the request route.
*
* @return array
*/
public function boot()
{
ExtensionManager::instance()
->bind();
}
}

View File

@ -0,0 +1,5 @@
# Codecycler.Extend / oc-extend-plugin
Use this plugin to easily extend any October CMS plugin. It helps with structure and keeps the code base of your extending plugin clean.
## Documentation & Examples
Please take a look at [the documentation](https://docs.codecycler.com/oc-extend-plugin-392bff68cdf74b01816508db6fe55bf3).

View File

@ -0,0 +1,53 @@
<?php namespace Codecycler\Extend\Classes;
use Event;
use System\Classes\PluginManager;
use October\Rain\Support\Traits\Singleton;
class ExtensionManager
{
use Singleton;
protected $extenders = [];
public function load()
{
//
$plugins = PluginManager::instance()
->getAllPlugins();
//
foreach ($plugins as $plugin) {
if (method_exists($plugin, 'registerExtenders')) {
$this->register($plugin->registerExtenders());
}
}
}
public function register($extenders)
{
if (!is_array($extenders)) {
$extenders = [$extenders];
}
foreach ($extenders as $extender) {
if (in_array($extender, $this->extenders)) {
continue;
}
$this->extenders[] = $extender;
}
}
public function bind()
{
foreach ($this->get() as $extender) {
Event::subscribe($extender);
}
}
public function get()
{
return $this->extenders;
}
}

View File

@ -0,0 +1,187 @@
<?php namespace Codecycler\Extend\Classes;
use Yaml;
use Event;
class PluginExtender
{
private $controller;
private $model;
public function __construct()
{
$this->load();
}
/**
* This method reloads the extension config
*/
public function load()
{
$this->model = $this->model();
$this->controller = $this->controller();
}
public function model()
{
return null;
}
public function controller()
{
return null;
}
public function extendSubscribe()
{
}
public function subscribe()
{
$this->extendFormFields();
$this->extendRelationConfig();
$this->extendRelations();
$this->extendSubscribe();
$this->extendMethods();
}
public function addFields()
{
return [];
}
public function addTabFields()
{
return [];
}
public function addRelationConfig()
{
return [];
}
public function belongsToMany()
{
return [];
}
public function hasMany()
{
return [];
}
public function belongsTo()
{
return [];
}
public function methods()
{
return [];
}
/**
* Private functions required by the extender
*/
private function extendRelationConfig()
{
if (count($this->addRelationConfig()) < 1) {
return;
}
$controller = new $this->controller;
$addRelationController = false;
$configExists = false;
$configEmpty = true;
$relationConfig = $this->addRelationConfig();
if (!in_array('Backend\Behaviors\RelationController', $controller->implement) && !in_array('Backend.Behaviors.RelationController', $controller->implement)) {
$addRelationController = true;
}
if (property_exists($controller, 'relationConfig')) {
$configExists = true;
}
if ($configExists && $controller->relationConfig) {
$configEmpty = false;
}
$controller::extend(function ($c) use ($addRelationController, $configExists, $configEmpty, $relationConfig, $controller) {
if ($addRelationController) {
array_push($c->implement, 'Backend\Behaviors\RelationController');
}
if (!$configExists) {
$c->addDynamicProperty('relationConfig', function ($relationConfig) {
return $relationConfig;
});
} else {
if ($configEmpty) {
$c->relationConfig = $relationConfig;
} else {
if (is_array($c->relationConfig)) {
$c->relationConfig = array_merge($relationConfig, $c->relationConfig);
}
if (is_string($c->relationConfig)) {
$controllerPath = plugins_path(strtolower(str_replace('\\', '/', get_class($controller)))) . '/' . $c->relationConfig;
$currentRelationConfig = Yaml::parseFile($controllerPath);
$c->relationConfig = array_merge($currentRelationConfig, $relationConfig);
}
}
}
});
}
private function extendFormFields()
{
Event::listen('backend.form.extendFields', function ($formWidget, $formData) {
if (!$formWidget->getController() instanceof $this->controller) {
return;
}
if (!$formWidget->model instanceof $this->model) {
return;
}
if ($formWidget->isNested) {
return;
}
$formWidget->addFields($this->addFields());
$formWidget->addTabFields($this->addTabFields());
});
}
private function extendRelations()
{
$model = $this->model;
$belongsToMany = $this->belongsToMany();
$hasMany = $this->hasMany();
$belongsTo = $this->belongsTo();
$model::extend(function ($model) use ($belongsToMany, $hasMany, $belongsTo) {
$model->belongsToMany = array_merge($model->belongsToMany, $belongsToMany);
$model->hasMany = array_merge($model->hasMany, $hasMany);
$model->belongsTo = array_merge($model->belongsTo, $belongsTo);
});
}
private function extendMethods()
{
$model = $this->model;
$methods = $this->methods();
$model::extend(function ($model) use ($methods) {
foreach ($methods as $functionName => $method) {
$model->addDynamicMethod($functionName, $method);
}
});
}
}

View File

@ -0,0 +1,13 @@
{
"name": "codecycler/oc-extend-plugin",
"description": "Extending October CMS plugins tool",
"type": "october-plugin",
"license": "GPL-3.0-only",
"authors": [
{
"name": "Sebastiaan Kloos",
"email": "sebastiaan@codecycler.com"
}
],
"require": {}
}

View File

@ -0,0 +1 @@
1.0.1: First version of Extend

View File

@ -0,0 +1,445 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see http://www.php-fig.org/psr/psr-0/
* @see http://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
// PSR-4
private $prefixLengthsPsr4 = array();
private $prefixDirsPsr4 = array();
private $fallbackDirsPsr4 = array();
// PSR-0
private $prefixesPsr0 = array();
private $fallbackDirsPsr0 = array();
private $useIncludePath = false;
private $classMap = array();
private $classMapAuthoritative = false;
private $missingClasses = array();
private $apcuPrefix;
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', $this->prefixesPsr0);
}
return array();
}
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array $classMap Class to filename map
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 base directories
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
/**
* Unregisters this instance as an autoloader.
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return bool|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*/
function includeFile($file)
{
include $file;
}

View File

@ -0,0 +1,21 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,9 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);

View File

@ -0,0 +1,9 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);

View File

@ -0,0 +1,9 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);

View File

@ -0,0 +1,52 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit347031eccba95821db30e6a679fe62e3
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit347031eccba95821db30e6a679fe62e3', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit347031eccba95821db30e6a679fe62e3', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit347031eccba95821db30e6a679fe62e3::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
return $loader;
}
}

View File

@ -0,0 +1,15 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit347031eccba95821db30e6a679fe62e3
{
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
}, null, ClassLoader::class);
}
}

View File

@ -0,0 +1,32 @@
[
{
"name": "codecycler/oc-extend-plugin",
"version": "dev-main",
"version_normalized": "dev-main",
"source": {
"type": "git",
"url": "https://github.com/codecyclernl/oc-extend-plugin.git",
"reference": "b48e535c547706b594466cdccaf6ff2f2bd1b687"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/codecyclernl/oc-extend-plugin/zipball/b48e535c547706b594466cdccaf6ff2f2bd1b687",
"reference": "b48e535c547706b594466cdccaf6ff2f2bd1b687",
"shasum": ""
},
"time": "2021-03-06T13:48:04+00:00",
"type": "october-plugin",
"installation-source": "source",
"notification-url": "https://packagist.org/downloads/",
"license": [
"GPL-3.0-only"
],
"authors": [
{
"name": "Sebastiaan Kloos",
"email": "sebastiaan@codecycler.com"
}
],
"description": "Extending October CMS plugins tool"
}
]

View File

@ -143,6 +143,7 @@ class Category extends ImportModel
'external_id',
'preview_text',
'description',
'featured'
];
public $cached = [
@ -157,6 +158,7 @@ class Category extends ImportModel
'icon',
'images',
'updated_at',
'featured'
];
public $dates = ['created_at', 'updated_at'];
@ -183,7 +185,7 @@ class Category extends ImportModel
*/
public function scopeGetByParentID($obQuery, $sData)
{
return $obQuery->where('parent_id', $sData);
return $obQuery->where('parent_id', $sData)->addSelect('featured');
}
/**

View File

@ -39,4 +39,8 @@ columns:
label: 'lovata.toolbox::lang.field.updated_at'
type: timetense
sortable: true
invisible: true
invisible: true
featured:
label: Featured
type: text
sortable: true

View File

@ -4,6 +4,11 @@ fields:
span: left
default: 1
type: switch
featured:
label: Featured
span: auto
default: 0
type: switch
name:
label: 'lovata.toolbox::lang.field.name'
span: left
@ -51,7 +56,7 @@ tabs:
preview_image:
label: 'lovata.toolbox::lang.field.preview_image'
mode: image
fileTypes: jpg,jpeg,bmp,png,webp,gif,svg
fileTypes: 'jpg,jpeg,bmp,png,webp,gif,svg'
useCaption: true
thumbOptions:
mode: crop
@ -62,7 +67,7 @@ tabs:
icon:
label: 'lovata.toolbox::lang.field.icon'
mode: image
fileTypes: jpg,jpeg,bmp,png,webp,gif,svg
fileTypes: 'jpg,jpeg,bmp,png,webp,gif,svg'
useCaption: true
thumbOptions:
mode: crop
@ -73,7 +78,7 @@ tabs:
images:
label: 'lovata.toolbox::lang.field.images'
mode: image
fileTypes: jpg,jpeg,bmp,png,webp,gif,svg
fileTypes: 'jpg,jpeg,bmp,png,webp,gif,svg'
useCaption: true
thumbOptions:
mode: crop

View File

@ -27,6 +27,7 @@ class CategoryCollectionTest extends CommonTest
'code' => 'code',
'preview_text' => 'preview_text',
'description' => 'description',
'featured' => 'featured',
];
/**

View File

@ -32,6 +32,7 @@ class CategoryItemTest extends CommonTest
'code' => 'code',
'preview_text' => 'preview_text',
'description' => 'description',
'featured' => 'featured',
];
protected $arProductData = [

View File

@ -0,0 +1,23 @@
<?php namespace Lovata\Shopaholic\Updates;
use Schema;
use October\Rain\Database\Updates\Migration;
class BuilderTableUpdateLovataShopaholicCategories extends Migration
{
public function up()
{
Schema::table('lovata_shopaholic_categories', function($table)
{
$table->boolean('featured')->default(0);
});
}
public function down()
{
Schema::table('lovata_shopaholic_categories', function($table)
{
$table->dropColumn('featured');
});
}
}

View File

@ -28,6 +28,7 @@ class CreateTableCategories extends Migration
$obTable->string('slug')->unique();
$obTable->string('code')->nullable();
$obTable->string('external_id')->nullable();
$obTable->boolean('featured')->default(0);
$obTable->text('preview_text')->nullable();
$obTable->text('description')->nullable();
$obTable->integer('parent_id')->nullable()->unsigned();

View File

@ -136,3 +136,6 @@
- 'Added "lazy" param to tabs config of Products controller'
1.30.2:
- 'Fixed bug with category tree in v2'
1.30.3:
- 'Updated table lovata_shopaholic_categories'
- builder_table_update_lovata_shopaholic_categories.php

1
plugins/rainlab/blog/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.DS_Store

View File

@ -0,0 +1,19 @@
# MIT license
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,172 @@
<?php namespace RainLab\Blog;
use Backend;
use Controller;
use RainLab\Blog\Models\Post;
use System\Classes\PluginBase;
use RainLab\Blog\Classes\TagProcessor;
use RainLab\Blog\Models\Category;
use Event;
class Plugin extends PluginBase
{
public function pluginDetails()
{
return [
'name' => 'rainlab.blog::lang.plugin.name',
'description' => 'rainlab.blog::lang.plugin.description',
'author' => 'Alexey Bobkov, Samuel Georges',
'icon' => 'icon-pencil',
'homepage' => 'https://github.com/rainlab/blog-plugin'
];
}
public function registerComponents()
{
return [
'RainLab\Blog\Components\Post' => 'blogPost',
'RainLab\Blog\Components\Posts' => 'blogPosts',
'RainLab\Blog\Components\Categories' => 'blogCategories',
'RainLab\Blog\Components\RssFeed' => 'blogRssFeed'
];
}
public function registerPermissions()
{
return [
'rainlab.blog.manage_settings' => [
'tab' => 'rainlab.blog::lang.blog.tab',
'label' => 'rainlab.blog::lang.blog.manage_settings'
],
'rainlab.blog.access_posts' => [
'tab' => 'rainlab.blog::lang.blog.tab',
'label' => 'rainlab.blog::lang.blog.access_posts'
],
'rainlab.blog.access_categories' => [
'tab' => 'rainlab.blog::lang.blog.tab',
'label' => 'rainlab.blog::lang.blog.access_categories'
],
'rainlab.blog.access_other_posts' => [
'tab' => 'rainlab.blog::lang.blog.tab',
'label' => 'rainlab.blog::lang.blog.access_other_posts'
],
'rainlab.blog.access_import_export' => [
'tab' => 'rainlab.blog::lang.blog.tab',
'label' => 'rainlab.blog::lang.blog.access_import_export'
],
'rainlab.blog.access_publish' => [
'tab' => 'rainlab.blog::lang.blog.tab',
'label' => 'rainlab.blog::lang.blog.access_publish'
]
];
}
public function registerNavigation()
{
return [
'blog' => [
'label' => 'rainlab.blog::lang.blog.menu_label',
'url' => Backend::url('rainlab/blog/posts'),
'icon' => 'icon-pencil',
'iconSvg' => 'plugins/rainlab/blog/assets/images/blog-icon.svg',
'permissions' => ['rainlab.blog.*'],
'order' => 300,
'sideMenu' => [
'new_post' => [
'label' => 'rainlab.blog::lang.posts.new_post',
'icon' => 'icon-plus',
'url' => Backend::url('rainlab/blog/posts/create'),
'permissions' => ['rainlab.blog.access_posts']
],
'posts' => [
'label' => 'rainlab.blog::lang.blog.posts',
'icon' => 'icon-copy',
'url' => Backend::url('rainlab/blog/posts'),
'permissions' => ['rainlab.blog.access_posts']
],
'categories' => [
'label' => 'rainlab.blog::lang.blog.categories',
'icon' => 'icon-list-ul',
'url' => Backend::url('rainlab/blog/categories'),
'permissions' => ['rainlab.blog.access_categories']
]
]
]
];
}
public function registerSettings()
{
return [
'blog' => [
'label' => 'rainlab.blog::lang.blog.menu_label',
'description' => 'rainlab.blog::lang.blog.settings_description',
'category' => 'rainlab.blog::lang.blog.menu_label',
'icon' => 'icon-pencil',
'class' => 'RainLab\Blog\Models\Settings',
'order' => 500,
'keywords' => 'blog post category',
'permissions' => ['rainlab.blog.manage_settings']
]
];
}
/**
* Register method, called when the plugin is first registered.
*/
public function register()
{
/*
* Register the image tag processing callback
*/
TagProcessor::instance()->registerCallback(function($input, $preview) {
if (!$preview) {
return $input;
}
return preg_replace('|\<img src="image" alt="([0-9]+)"([^>]*)\/>|m',
'<span class="image-placeholder" data-index="$1">
<span class="upload-dropzone">
<span class="label">Click or drop an image...</span>
<span class="indicator"></span>
</span>
</span>',
$input);
});
}
public function boot()
{
/*
* Register menu items for the RainLab.Pages plugin
*/
Event::listen('pages.menuitem.listTypes', function() {
return [
'blog-category' => 'rainlab.blog::lang.menuitem.blog_category',
'all-blog-categories' => 'rainlab.blog::lang.menuitem.all_blog_categories',
'blog-post' => 'rainlab.blog::lang.menuitem.blog_post',
'all-blog-posts' => 'rainlab.blog::lang.menuitem.all_blog_posts',
'category-blog-posts' => 'rainlab.blog::lang.menuitem.category_blog_posts',
];
});
Event::listen('pages.menuitem.getTypeInfo', function($type) {
if ($type == 'blog-category' || $type == 'all-blog-categories') {
return Category::getMenuTypeInfo($type);
}
elseif ($type == 'blog-post' || $type == 'all-blog-posts' || $type == 'category-blog-posts') {
return Post::getMenuTypeInfo($type);
}
});
Event::listen('pages.menuitem.resolveItem', function($type, $item, $url, $theme) {
if ($type == 'blog-category' || $type == 'all-blog-categories') {
return Category::resolveMenuItem($item, $url, $theme);
}
elseif ($type == 'blog-post' || $type == 'all-blog-posts' || $type == 'category-blog-posts') {
return Post::resolveMenuItem($item, $url, $theme);
}
});
}
}

View File

@ -0,0 +1,318 @@
# Blog Plugin
A simple, extensible blogging platform for October CMS.
[Blog & Forum Building Tutorial Video](https://player.vimeo.com/video/97088926)
## Editing posts
The plugin uses the markdown markup for the posts. You can use any Markdown syntax and some special tags for embedding images and videos (requires RainLab Blog Video plugin). To embed an image use the image placeholder:
![1](image)
The number in the first part is the placeholder index. If you use multiple images in a post you should use an unique index for each image:
![1](image)
![2](image)
You can also add classes or ids to images by using the [markdown extra](http://michelf.ca/projects/php-markdown/extra/) syntax:
![1](image){#id .class}
## Excerpt Vs. Read more
Posts are managed by selecting *Blog > Posts* from the menu. Each post can contain an excerpt by entering some text in this field on the *Manage* tab. This content is displayed on the page using the `summary` attribute of the blog post.
{{ post.summary|raw }}
Alternatively this field can be left blank and the excerpt can be captured from the main content (*Edit* tab). Use the special tag `<!-- more -->` to specify a summary from the main content, all content above this tag will be treated as the summary. For example:
This is a great introduction to a great blog post. This text is included as part of the excerpt / summary.
<!-- more -->
Let's dive in to more detail about why this post is so great. This text will not be included in the summary.
Finally, if no excerpt is specified and the "more" tag is not used, the blog post will capture the first 600 characters of the content and use this for the summary.
## Implementing front-end pages
The plugin provides several components for building the post list page (archive), category page, post details page and category list for the sidebar.
### Post list page
Use the `blogPosts` component to display a list of latest blog posts on a page. The component has the following properties:
* **pageNumber** - this value is used to determine what page the user is on, it should be a routing parameter for the default markup. The default value is **{{ :page }}** to obtain the value from the route parameter `:page`.
* **categoryFilter** - a category slug to filter the posts by. If left blank, all posts are displayed.
* **postsPerPage** - how many posts to display on a single page (the pagination is supported automatically). The default value is 10.
* **noPostsMessage** - message to display in the empty post list.
* **sortOrder** - the column name and direction used for the sort order of the posts. The default value is **published_at desc**.
* **categoryPage** - path to the category page. The default value is **blog/category** - it matches the pages/blog/category.htm file in the theme directory. This property is used in the default component partial for creating links to the blog categories.
* **postPage** - path to the post details page. The default value is **blog/post** - it matches the pages/blog/post.htm file in the theme directory. This property is used in the default component partial for creating links to the blog posts.
* **exceptPost** - ignore a single post by its slug or unique ID. The ignored post will not be included in the list, useful for showing other/related posts.
* **exceptCategories** - ignore posts from a comma-separated list of categories, given by their unique slug. The ignored posts will not be included in the list.
The blogPosts component injects the following variables to the page where it's used:
* **posts** - a list of blog posts loaded from the database.
* **postPage** - contains the value of the `postPage` component's property.
* **category** - the blog category object loaded from the database. If the category is not found, the variable value is **null**.
* **categoryPage** - contains the value of the `categoryPage` component's property.
* **noPostsMessage** - contains the value of the `noPostsMessage` component's property.
The component supports pagination and reads the current page index from the `:page` URL parameter. The next example shows the basic component usage on the blog home page:
title = "Blog"
url = "/blog/:page?"
[blogPosts]
postsPerPage = "5"
==
{% component 'blogPosts' %}
The next example shows the basic component usage with the category filter:
title = "Blog Category"
url = "/blog/category/:slug/:page?"
[blogPosts]
categoryFilter = "{{ :slug }}"
==
function onEnd()
{
// Optional - set the page title to the category name
if ($this->category)
$this->page->title = $this->category->name;
}
==
{% if not category %}
<h2>Category not found</h2>
{% else %}
<h2>{{ category.name }}</h2>
{% component 'blogPosts' %}
{% endif %}
The post list and the pagination are coded in the default component partial `plugins/rainlab/blog/components/posts/default.htm`. If the default markup is not suitable for your website, feel free to copy it from the default partial and replace the `{% component %}` call in the example above with the partial contents.
### Post page
Use the `blogPost` component to display a blog post on a page. The component has the following properties:
* **slug** - the value used for looking up the post by its slug. The default value is **{{ :slug }}** to obtain the value from the route parameter `:slug`.
* **categoryPage** - path to the category page. The default value is **blog/category** - it matches the pages/blog/category.htm file in the theme directory. This property is used in the default component partial for creating links to the blog categories.
The component injects the following variables to the page where it's used:
* **post** - the blog post object loaded from the database. If the post is not found, the variable value is **null**.
The next example shows the basic component usage on the blog page:
title = "Blog Post"
url = "/blog/post/:slug"
[blogPost]
==
<?php
function onEnd()
{
// Optional - set the page title to the post title
if ($this->post)
$this->page->title = $this->post->title;
}
?>
==
{% if post %}
<h2>{{ post.title }}</h2>
{% component 'blogPost' %}
{% else %}
<h2>Post not found</h2>
{% endif %}
The post details is coded in the default component partial `plugins/rainlab/blog/components/post/default.htm`.
### Category list
Use the `blogCategories` component to display a list of blog post categories with links. The component has the following properties:
* **slug** - the value used for looking up the current category by its slug. The default value is **{{ :slug }}** to obtain the value from the route parameter `:slug`.
* **displayEmpty** - determines if empty categories should be displayed. The default value is false.
* **categoryPage** - path to the category page. The default value is **blog/category** - it matches the pages/blog/category.htm file in the theme directory. This property is used in the default component partial for creating links to the blog categories.
The component injects the following variables to the page where it's used:
* **categoryPage** - contains the value of the `categoryPage` component's property.
* **categories** - a list of blog categories loaded from the database.
* **currentCategorySlug** - slug of the current category. This property is used for marking the current category in the category list.
The component can be used on any page. The next example shows the basic component usage on the blog home page:
title = "Blog"
url = "/blog/:page?"
[blogCategories]
==
...
<div class="sidebar">
{% component 'blogCategories' %}
</div>
...
The category list is coded in the default component partial `plugins/rainlab/blog/components/categories/default.htm`.
### RSS feed
Use the `blogRssFeed` component to display an RSS feed containing the latest blog posts. The following properties are supported:
* **categoryFilter** - a category slug to filter the posts by. If left blank, all posts are displayed.
* **postsPerPage** - how many posts to display on the feed. The default value is 10.
* **blogPage** - path to the main blog page. The default value is **blog** - it matches the pages/blog.htm file in the theme directory. This property is used in the RSS feed for creating links to the main blog page.
* **postPage** - path to the post details page. The default value is **blog/post** - it matches the pages/blog/post.htm file in the theme directory. This property is used in the RSS feed for creating links to the blog posts.
The component can be used on any page, it will hijack the entire page cycle to display the feed in RSS format. The next example shows how to use it:
title = "RSS Feed"
url = "/blog/rss.xml"
[blogRssFeed]
blogPage = "blog"
postPage = "blog/post"
==
<!-- This markup will never be displayed -->
## Configuration
To overwrite the default configuration create a `config/rainlab/blog/config.php`. You can return only values you want to override.
### Summary
A summary attribute is generated for each post.
If you enter an excerpt manually, it gets used as summary. Alternatively, you can use the `summary_separator` (default is `<!-- more -->`) to mark the end of the summary. If a post contains no separator, the text gets truncated after the number of characters specified in `summary_default_length` (default is 600 characters).
## Markdown guide
October supports [standard markdown syntax](http://daringfireball.net/projects/markdown/) as well as [extended markdown syntax](http://michelf.ca/projects/php-markdown/extra/)
### Classes and IDs
Classes and IDs can be added to images and other elements as shown below:
```
[link](url){#id .class}
![1](image){#id .class}
# October {#id .class}
```
### Fenced code blogs
Markdown extra makes it possible to use fenced code blocks. With fenced code blocks you do not need indentation on the areas you want to mark as code:
```
Code goes here
```
You can also use the `~` symbol:
~~~
Code goes here
~~~
### Tables
A *simple* table can be defined as follows:
```
First Header | Second Header
------------- | -------------
Content Cell | Content Cell
Content Cell | Content Cell
```
If you want to you can also add a leading and tailing pipe:
```
| First Header | Second Header |
| ------------- | ------------- |
| Content Cell | Content Cell |
| Content Cell | Content Cell |
```
To add alignment to the cells you simply need to add a `:` either at the start or end of a separator:
```
| First Header | Second Header |
| :------------ | ------------: |
| Content Cell | Content Cell |
| Content Cell | Content Cell |
```
To center align cell just add `:` on both sides:
```
| First Header | Second Header |
| ------------- | :-----------: |
| Content Cell | Content Cell |
| Content Cell | Content Cell |
```
### Definition lists
Below is an example of a simple definition list:
```
Laravel
: A popular PHP framework
October
: Awesome CMS built on Laravel
```
A term can also have multiple definitions:
```
Laravel
: A popular PHP framework
October
: Awesome CMS built on Laravel
: Supports markdown extra
```
You can also associate more than 1 term to a definition:
```
Laravel
October
: Built using PHP
```
### Footnotes
With markdown extra it is possible to create reference style footnotes:
```
This is some text with a footnote.[^1]
[^1]: And this is the footnote.
```
### Abbreviations
With markdown extra you can add abbreviations to your markup. The use this functionality first create a definition list:
```
*[HTML]: Hyper Text Markup Language
*[PHP]: Hypertext Preprocessor
```
Now markdown extra will convert all occurrences of `HTML` and `PHP` as follows:
```
<abbr title="Hyper Text Markup Language">HTML</abbr>
<abbr title="Hypertext Preprocessor">PHP</abbr>
```

View File

@ -0,0 +1,3 @@
.export-behavior .export-columns {
max-height: 450px !important;
}

View File

@ -0,0 +1,85 @@
.blog-post-preview .editor-preview .preview-content {
padding: 20px;
}
.blog-post-preview .editor-preview span.image-placeholder {
display: block;
}
.blog-post-preview .editor-preview span.image-placeholder .upload-dropzone {
background: #ecf0f1;
display: block;
border: 1px solid #e5e9ec;
padding: 25px;
min-height: 123px;
position: relative;
text-align: center;
cursor: pointer;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.blog-post-preview .editor-preview span.image-placeholder .upload-dropzone span.label {
color: #b1b9be;
font-size: 16px;
display: inline-block;
margin-top: 25px;
}
.blog-post-preview .editor-preview span.image-placeholder .upload-dropzone:before {
display: inline-block;
font-family: FontAwesome;
font-weight: normal;
font-style: normal;
text-decoration: inherit;
-webkit-font-smoothing: antialiased;
*margin-right: .3em;
content: "\f03e";
position: absolute;
left: 25px;
top: 25px;
line-height: 100%;
font-size: 73px;
color: #d1d3d4;
}
.blog-post-preview .editor-preview span.image-placeholder .upload-dropzone.hover,
.blog-post-preview .editor-preview span.image-placeholder .upload-dropzone:hover {
background: #2f99da;
}
.blog-post-preview .editor-preview span.image-placeholder .upload-dropzone.hover:before,
.blog-post-preview .editor-preview span.image-placeholder .upload-dropzone:hover:before,
.blog-post-preview .editor-preview span.image-placeholder .upload-dropzone.hover span.label,
.blog-post-preview .editor-preview span.image-placeholder .upload-dropzone:hover span.label {
color: white;
}
.blog-post-preview .editor-preview span.image-placeholder input[type=file] {
position: absolute;
left: -10000em;
}
.blog-post-preview-container .loading-indicator {
position: absolute;
display: none;
width: 20px;
height: 20px;
padding: 0!important;
background: transparent;
right: 10px;
left: auto;
top: 10px;
}
.blog-post-preview-container.loading-indicator-visible .loading-indicator {
display: block;
}
html.cssanimations .blog-post-preview span.image-placeholder.loading .upload-dropzone:before {
display: none;
}
html.cssanimations .blog-post-preview span.image-placeholder.loading .upload-dropzone .indicator {
display: block;
width: 50px;
height: 50px;
position: absolute;
left: 35px;
top: 35px;
background-image: url('../../../../../modules/system/assets/ui/images/loader-transparent.svg');
background-size: 50px 50px;
background-position: 50% 50%;
-webkit-animation: spin 1s linear infinite;
animation: spin 1s linear infinite;
}

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="64px" height="64px" viewBox="0 0 64 64" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
<!-- Generator: Sketch 3.4.4 (17249) - http://www.bohemiancoding.com/sketch -->
<title>blog-icon</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">
<g id="Group-+-Group" sketch:type="MSLayerGroup">
<g id="Group" sketch:type="MSShapeGroup">
<path d="M0.754,3.84 C0.754,1.719 2.473,0 4.594,0 L32.754,0 L48.754,13.44 L48.754,60.16 C48.754,62.281 47.035,64 44.914,64 L4.594,64 C2.473,64 0.754,62.281 0.754,60.16 L0.754,3.84 Z" id="Fill-392" fill="#FFFFFF"></path>
<path d="M32.754,0 L32.754,9.6 C32.754,11.721 34.473,13.44 36.594,13.44 L48.754,13.44 L32.754,0 Z" id="Fill-393" fill="#F0F1F1"></path>
<path d="M38.0416209,23 L12.3559338,23 C11.4141253,23 10.6435547,22.55 10.6435547,22 C10.6435547,21.45 11.4141253,21 12.3559338,21 L38.0416209,21 C38.9834294,21 39.754,21.45 39.754,22 C39.754,22.55 38.9834294,23 38.0416209,23 Z" id="Fill-397" fill="#E2E4E5"></path>
<path d="M29.4797252,27 C29.4797252,27.55 28.7091546,28 27.767346,28 L12.3559338,28 C11.4141253,28 10.6435547,27.55 10.6435547,27 C10.6435547,26.45 11.4141253,26 12.3559338,26 L27.767346,26 C28.7091546,26 29.4797252,26.45 29.4797252,27" id="Fill-398" fill="#E2E4E5"></path>
<path d="M23.767346,11 L12.3559338,11 C11.4141253,11 10.6435547,10.55 10.6435547,10 C10.6435547,9.45 11.4141253,9 12.3559338,9 L23.767346,9 C24.7091546,9 25.4797252,9.45 25.4797252,10 C25.4797252,10.55 24.7091546,11 23.767346,11 Z" id="Fill-398-Copy" fill="#E1332C"></path>
<path d="M39.754,35 C39.754,35.55 38.9834294,36 38.0416209,36 L12.3559338,36 C11.4141253,36 10.6435547,35.55 10.6435547,35 C10.6435547,34.45 11.4141253,34 12.3559338,34 L38.0416209,34 C38.9834294,34 39.754,34.45 39.754,35" id="Fill-399" fill="#E2E4E5"></path>
<path d="M29.4797252,40 C29.4797252,40.55 28.7091546,41 27.767346,41 L12.3559338,41 C11.4141253,41 10.6435547,40.55 10.6435547,40 C10.6435547,39.45 11.4141253,39 12.3559338,39 L27.767346,39 C28.7091546,39 29.4797252,39.45 29.4797252,40" id="Fill-400" fill="#E2E4E5"></path>
<path d="M39.754,48 C39.754,48.55 38.9834294,49 38.0416209,49 L12.3559338,49 C11.4141253,49 10.6435547,48.55 10.6435547,48 C10.6435547,47.45 11.4141253,47 12.3559338,47 L38.0416209,47 C38.9834294,47 39.754,47.45 39.754,48" id="Fill-401" fill="#E2E4E5"></path>
<path d="M29.4797252,53 C29.4797252,53.55 28.7091546,54 27.767346,54 L12.3559338,54 C11.4141253,54 10.6435547,53.55 10.6435547,53 C10.6435547,52.45 11.4141253,52 12.3559338,52 L27.767346,52 C28.7091546,52 29.4797252,52.45 29.4797252,53" id="Fill-402" fill="#E2E4E5"></path>
</g>
<g id="Group" transform="translate(27.000000, 16.000000)" sketch:type="MSShapeGroup">
<path d="M31.8979,11.4983 L10.6949,35.4653 L4.8179,36.6753 C4.6479,35.8573 4.2249,35.0823 3.5509,34.4863 C2.8769,33.8893 2.0559,33.5643 1.2229,33.4953 L1.7069,27.5143 L22.9099,3.5473 L31.8979,11.4983 Z" id="Fill-647" fill="#F4D0A1"></path>
<path d="M31.8692,11.4729 C31.8852,11.4869 11.1512,34.9499 11.1512,34.9499 C11.7392,33.7029 11.5032,32.1759 10.4362,31.2309 C9.3092,30.2349 7.6512,30.2359 6.5312,31.1689 C7.2692,29.8979 7.0682,28.2519 5.9422,27.2549 C4.8622,26.3009 3.2942,26.2619 2.1802,27.0819 C2.1442,27.1089 22.8852,3.5759 22.8852,3.5759 C22.8992,3.5599 31.8692,11.4729 31.8692,11.4729 Z" id="Fill-648" fill="#FC5B55"></path>
<path d="M31.8979,11.4983 L22.9099,3.5473 L24.2349,2.0493 L33.2229,10.0003 L31.8979,11.4983 Z" id="Fill-649" fill="#FACB1B"></path>
<path d="M32.7497,1.5706 L32.6597,1.4916 C30.2027,-0.6824 26.4487,-0.4524 24.2747,2.0046 L24.2357,2.0496 L33.2227,10.0006 L33.2627,9.9556 C35.4367,7.4986 35.2067,3.7446 32.7497,1.5706" id="Fill-650" fill="#F89392"></path>
<path d="M11.1258,34.9796 C11.7438,33.7326 11.5138,32.1846 10.4358,31.2306 C9.3118,30.2366 7.6588,30.2356 6.5388,31.1626 C6.5198,31.1786 27.3788,7.5516 27.3788,7.5516 C27.3928,7.5356 31.8698,11.4736 31.8698,11.4736 C31.8848,11.4866 11.1258,34.9796 11.1258,34.9796 Z" id="Fill-651" fill="#E1332C"></path>
<path d="M4.8181,36.6754 L0.9001,37.4824 L1.2231,33.4954 C2.0561,33.5644 2.8771,33.8894 3.5511,34.4864 C4.2251,35.0824 4.6481,35.8574 4.8181,36.6754" id="Fill-652" fill="#3E3E3F"></path>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.6 KiB

View File

@ -0,0 +1,185 @@
+function ($) { "use strict";
var PostForm = function () {
this.$form = $('#post-form')
this.$markdownEditor = $('[data-field-name=content] [data-control=markdowneditor]:first', this.$form)
this.$preview = $('.editor-preview', this.$markdownEditor)
this.formAction = this.$form.attr('action')
this.sessionKey = $('input[name=_session_key]', this.$form).val()
if (this.$markdownEditor.length > 0) {
this.codeEditor = this.$markdownEditor.markdownEditor('getEditorObject')
this.$markdownEditor.on('initPreview.oc.markdowneditor', $.proxy(this.initPreview, this))
this.initDropzones()
this.initFormEvents()
this.addToolbarButton()
}
this.initLayout()
}
PostForm.prototype.addToolbarButton = function() {
this.buttonClickCount = 1
var self = this,
$button = this.$markdownEditor.markdownEditor('findToolbarButton', 'image')
if (!$button.length) return
$button.data('button-action', 'insertLine')
$button.data('button-template', '\n\n![1](image)\n')
$button.on('click', function() {
$button.data('button-template', '\n\n!['+self.buttonClickCount+'](image)\n')
self.buttonClickCount++
})
}
PostForm.prototype.initPreview = function() {
this.initImageUploaders()
}
PostForm.prototype.updateScroll = function() {
// Reserved in case MarkdownEditor uses scrollbar plugin
// this.$preview.data('oc.scrollbar').update()
}
PostForm.prototype.initImageUploaders = function() {
var self = this
$('span.image-placeholder .upload-dropzone', this.$preview).each(function(){
var
$placeholder = $(this).parent(),
$link = $('span.label', $placeholder),
placeholderIndex = $placeholder.data('index')
var uploaderOptions = {
url: self.formAction,
clickable: [$(this).get(0), $link.get(0)],
previewsContainer: $('<div />').get(0),
paramName: 'file',
headers: {}
}
/*
* Add CSRF token to headers
*/
var token = $('meta[name="csrf-token"]').attr('content')
if (token) {
uploaderOptions.headers['X-CSRF-TOKEN'] = token
}
var dropzone = new Dropzone($(this).get(0), uploaderOptions)
dropzone.on('error', function(file, error) {
alert('Error uploading file: ' + error)
})
dropzone.on('success', function(file, data){
if (data.error)
alert(data.error)
else {
self.pauseUpdates()
var $img = $('<img src="'+data.path+'">')
$img.load(function(){
self.updateScroll()
})
$placeholder.replaceWith($img)
self.codeEditor.replace('!['+data.file+']('+data.path+')', {
needle: '!['+placeholderIndex+'](image)'
})
self.resumeUpdates()
}
})
dropzone.on('complete', function(){
$placeholder.removeClass('loading')
})
dropzone.on('sending', function(file, xhr, formData) {
formData.append('X_BLOG_IMAGE_UPLOAD', 1)
formData.append('_session_key', self.sessionKey)
$placeholder.addClass('loading')
})
})
}
PostForm.prototype.pauseUpdates = function() {
this.$markdownEditor.markdownEditor('pauseUpdates')
}
PostForm.prototype.resumeUpdates = function() {
this.$markdownEditor.markdownEditor('resumeUpdates')
}
PostForm.prototype.initDropzones = function() {
$(document).bind('dragover', function (e) {
var dropZone = $('span.image-placeholder .upload-dropzone'),
foundDropzone,
timeout = window.dropZoneTimeout
if (!timeout)
dropZone.addClass('in');
else
clearTimeout(timeout);
var found = false,
node = e.target
do {
if ($(node).hasClass('dropzone')) {
found = true
foundDropzone = $(node)
break
}
node = node.parentNode;
} while (node != null);
dropZone.removeClass('in hover')
if (found)
foundDropzone.addClass('hover')
window.dropZoneTimeout = setTimeout(function () {
window.dropZoneTimeout = null
dropZone.removeClass('in hover')
}, 100)
})
}
PostForm.prototype.initFormEvents = function() {
$(document).on('ajaxSuccess', '#post-form', function(event, context, data){
if (context.handler == 'onSave' && !data.X_OCTOBER_ERROR_FIELDS) {
$(this).trigger('unchange.oc.changeMonitor')
}
})
}
PostForm.prototype.initLayout = function() {
$('#Form-secondaryTabs .tab-pane.layout-cell:not(:first-child)').addClass('padded-pane')
$('#Form-secondaryTabs .nav-tabs > li:not(:first-child)').addClass('tab-content-bg')
}
PostForm.prototype.replacePlaceholder = function(placeholder, placeholderHtmlReplacement, mdCodePlaceholder, mdCodeReplacement) {
this.pauseUpdates()
placeholder.replaceWith(placeholderHtmlReplacement)
this.codeEditor.replace(mdCodeReplacement, {
needle: mdCodePlaceholder
})
this.updateScroll()
this.resumeUpdates()
}
$(document).ready(function(){
var form = new PostForm()
if ($.oc === undefined)
$.oc = {}
$.oc.blogPostForm = form
})
}(window.jQuery);

View File

@ -0,0 +1,99 @@
@import "../../../../../modules/backend/assets/less/core/boot.less";
.blog-post-preview .editor-preview {
.preview-content {
padding: 20px;
}
span.image-placeholder {
display: block;
.upload-dropzone {
background: #ecf0f1;
display: block;
border: 1px solid #e5e9ec;
padding: 25px;
min-height: 123px;
position: relative;
text-align: center;
cursor: pointer;
.box-sizing(border-box);
span.label {
color: #b1b9be;
font-size: 16px;
display: inline-block;
margin-top: 25px;
}
&:before {
display: inline-block;
.icon(@picture-o);
position: absolute;
left: 25px;
top: 25px;
line-height: 100%;
font-size: 73px;
color: #d1d3d4;
}
&.hover, &:hover {
background: #2f99da;
&:before, span.label {
color: white;
}
}
}
input[type=file] {
position: absolute;
left: -10000em;
}
}
}
.blog-post-preview-container {
.loading-indicator {
position: absolute;
display: none;
width: 20px;
height: 20px;
padding: 0!important;
background: transparent;
right: 10px;
left: auto;
top: 10px;
}
&.loading-indicator-visible {
.loading-indicator {
display: block;
}
}
}
html.cssanimations {
.blog-post-preview {
span.image-placeholder.loading {
.upload-dropzone {
&:before {
display: none;
}
.indicator {
display: block;
width: 50px;
height: 50px;
position: absolute;
left: 35px;
top: 35px;
background-image:url('../../../../../modules/system/assets/ui/images/loader-transparent.svg');
background-size: 50px 50px;
background-position: 50% 50%;
.animation(spin 1s linear infinite);
}
}
}
}
}

View File

@ -0,0 +1,39 @@
<?php namespace RainLab\Blog\Classes;
/**
* Blog Markdown tag processor.
*
* @package rainlab\blog
* @author Alexey Bobkov, Samuel Georges
*/
class TagProcessor
{
use \October\Rain\Support\Traits\Singleton;
/**
* @var array Cache of processing callbacks.
*/
private $callbacks = [];
/**
* Registers a callback function that handles blog post markup.
* The callback function should accept two arguments - the HTML string
* generated from Markdown contents and the preview flag determining whether
* the function should return a markup for the blog post preview form or for the
* front-end.
* @param callable $callback A callable function.
*/
public function registerCallback(callable $callback)
{
$this->callbacks[] = $callback;
}
public function processTags($markup, $preview)
{
foreach ($this->callbacks as $callback) {
$markup = $callback($markup, $preview);
}
return $markup;
}
}

View File

@ -0,0 +1,113 @@
<?php namespace RainLab\Blog\Components;
use Db;
use Carbon\Carbon;
use Cms\Classes\Page;
use Cms\Classes\ComponentBase;
use RainLab\Blog\Models\Category as BlogCategory;
class Categories extends ComponentBase
{
/**
* @var Collection A collection of categories to display
*/
public $categories;
/**
* @var string Reference to the page name for linking to categories.
*/
public $categoryPage;
/**
* @var string Reference to the current category slug.
*/
public $currentCategorySlug;
public function componentDetails()
{
return [
'name' => 'rainlab.blog::lang.settings.category_title',
'description' => 'rainlab.blog::lang.settings.category_description'
];
}
public function defineProperties()
{
return [
'slug' => [
'title' => 'rainlab.blog::lang.settings.category_slug',
'description' => 'rainlab.blog::lang.settings.category_slug_description',
'default' => '{{ :slug }}',
'type' => 'string',
],
'displayEmpty' => [
'title' => 'rainlab.blog::lang.settings.category_display_empty',
'description' => 'rainlab.blog::lang.settings.category_display_empty_description',
'type' => 'checkbox',
'default' => 0,
],
'categoryPage' => [
'title' => 'rainlab.blog::lang.settings.category_page',
'description' => 'rainlab.blog::lang.settings.category_page_description',
'type' => 'dropdown',
'default' => 'blog/category',
'group' => 'rainlab.blog::lang.settings.group_links',
],
];
}
public function getCategoryPageOptions()
{
return Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName');
}
public function onRun()
{
$this->currentCategorySlug = $this->page['currentCategorySlug'] = $this->property('slug');
$this->categoryPage = $this->page['categoryPage'] = $this->property('categoryPage');
$this->categories = $this->page['categories'] = $this->loadCategories();
}
/**
* Load all categories or, depending on the <displayEmpty> option, only those that have blog posts
* @return mixed
*/
protected function loadCategories()
{
$categories = BlogCategory::with('posts_count')->getNested();
if (!$this->property('displayEmpty')) {
$iterator = function ($categories) use (&$iterator) {
return $categories->reject(function ($category) use (&$iterator) {
if ($category->getNestedPostCount() == 0) {
return true;
}
if ($category->children) {
$category->children = $iterator($category->children);
}
return false;
});
};
$categories = $iterator($categories);
}
/*
* Add a "url" helper attribute for linking to each category
*/
return $this->linkCategories($categories);
}
/**
* Sets the URL on each category according to the defined category page
* @return void
*/
protected function linkCategories($categories)
{
return $categories->each(function ($category) {
$category->setUrl($this->categoryPage, $this->controller);
if ($category->children) {
$this->linkCategories($category->children);
}
});
}
}

View File

@ -0,0 +1,156 @@
<?php namespace RainLab\Blog\Components;
use Event;
use BackendAuth;
use Cms\Classes\Page;
use Cms\Classes\ComponentBase;
use RainLab\Blog\Models\Post as BlogPost;
class Post extends ComponentBase
{
/**
* @var RainLab\Blog\Models\Post The post model used for display.
*/
public $post;
/**
* @var string Reference to the page name for linking to categories.
*/
public $categoryPage;
public function componentDetails()
{
return [
'name' => 'rainlab.blog::lang.settings.post_title',
'description' => 'rainlab.blog::lang.settings.post_description'
];
}
public function defineProperties()
{
return [
'slug' => [
'title' => 'rainlab.blog::lang.settings.post_slug',
'description' => 'rainlab.blog::lang.settings.post_slug_description',
'default' => '{{ :slug }}',
'type' => 'string',
],
'categoryPage' => [
'title' => 'rainlab.blog::lang.settings.post_category',
'description' => 'rainlab.blog::lang.settings.post_category_description',
'type' => 'dropdown',
'default' => 'blog/category',
],
];
}
public function getCategoryPageOptions()
{
return Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName');
}
public function init()
{
Event::listen('translate.localePicker.translateParams', function ($page, $params, $oldLocale, $newLocale) {
$newParams = $params;
if (isset($params['slug'])) {
$records = BlogPost::transWhere('slug', $params['slug'], $oldLocale)->first();
if ($records) {
$records->translateContext($newLocale);
$newParams['slug'] = $records['slug'];
}
}
return $newParams;
});
}
public function onRun()
{
$this->categoryPage = $this->page['categoryPage'] = $this->property('categoryPage');
$this->post = $this->page['post'] = $this->loadPost();
if (!$this->post) {
$this->setStatusCode(404);
return $this->controller->run('404');
}
}
public function onRender()
{
if (empty($this->post)) {
$this->post = $this->page['post'] = $this->loadPost();
}
}
protected function loadPost()
{
$slug = $this->property('slug');
$post = new BlogPost;
$query = $post->query();
if ($post->isClassExtendedWith('RainLab.Translate.Behaviors.TranslatableModel')) {
$query->transWhere('slug', $slug);
} else {
$query->where('slug', $slug);
}
if (!$this->checkEditor()) {
$query->isPublished();
}
$post = $query->first();
/*
* Add a "url" helper attribute for linking to each category
*/
if ($post && $post->exists && $post->categories->count()) {
$post->categories->each(function($category) {
$category->setUrl($this->categoryPage, $this->controller);
});
}
return $post;
}
public function previousPost()
{
return $this->getPostSibling(-1);
}
public function nextPost()
{
return $this->getPostSibling(1);
}
protected function getPostSibling($direction = 1)
{
if (!$this->post) {
return;
}
$method = $direction === -1 ? 'previousPost' : 'nextPost';
if (!$post = $this->post->$method()) {
return;
}
$postPage = $this->getPage()->getBaseFileName();
$post->setUrl($postPage, $this->controller);
$post->categories->each(function($category) {
$category->setUrl($this->categoryPage, $this->controller);
});
return $post;
}
protected function checkEditor()
{
$backendUser = BackendAuth::getUser();
return $backendUser && $backendUser->hasAccess('rainlab.blog.access_posts');
}
}

View File

@ -0,0 +1,259 @@
<?php namespace RainLab\Blog\Components;
use Lang;
use Redirect;
use BackendAuth;
use Cms\Classes\Page;
use Cms\Classes\ComponentBase;
use October\Rain\Database\Model;
use October\Rain\Database\Collection;
use RainLab\Blog\Models\Post as BlogPost;
use RainLab\Blog\Models\Category as BlogCategory;
use RainLab\Blog\Models\Settings as BlogSettings;
class Posts extends ComponentBase
{
/**
* A collection of posts to display
*
* @var Collection
*/
public $posts;
/**
* Parameter to use for the page number
*
* @var string
*/
public $pageParam;
/**
* If the post list should be filtered by a category, the model to use
*
* @var Model
*/
public $category;
/**
* Message to display when there are no messages
*
* @var string
*/
public $noPostsMessage;
/**
* Reference to the page name for linking to posts
*
* @var string
*/
public $postPage;
/**
* Reference to the page name for linking to categories
*
* @var string
*/
public $categoryPage;
/**
* If the post list should be ordered by another attribute
*
* @var string
*/
public $sortOrder;
public function componentDetails()
{
return [
'name' => 'rainlab.blog::lang.settings.posts_title',
'description' => 'rainlab.blog::lang.settings.posts_description'
];
}
public function defineProperties()
{
return [
'pageNumber' => [
'title' => 'rainlab.blog::lang.settings.posts_pagination',
'description' => 'rainlab.blog::lang.settings.posts_pagination_description',
'type' => 'string',
'default' => '{{ :page }}',
],
'categoryFilter' => [
'title' => 'rainlab.blog::lang.settings.posts_filter',
'description' => 'rainlab.blog::lang.settings.posts_filter_description',
'type' => 'string',
'default' => '',
],
'postsPerPage' => [
'title' => 'rainlab.blog::lang.settings.posts_per_page',
'type' => 'string',
'validationPattern' => '^[0-9]+$',
'validationMessage' => 'rainlab.blog::lang.settings.posts_per_page_validation',
'default' => '10',
],
'noPostsMessage' => [
'title' => 'rainlab.blog::lang.settings.posts_no_posts',
'description' => 'rainlab.blog::lang.settings.posts_no_posts_description',
'type' => 'string',
'default' => Lang::get('rainlab.blog::lang.settings.posts_no_posts_default'),
'showExternalParam' => false,
],
'sortOrder' => [
'title' => 'rainlab.blog::lang.settings.posts_order',
'description' => 'rainlab.blog::lang.settings.posts_order_description',
'type' => 'dropdown',
'default' => 'published_at desc',
],
'categoryPage' => [
'title' => 'rainlab.blog::lang.settings.posts_category',
'description' => 'rainlab.blog::lang.settings.posts_category_description',
'type' => 'dropdown',
'default' => 'blog/category',
'group' => 'rainlab.blog::lang.settings.group_links',
],
'postPage' => [
'title' => 'rainlab.blog::lang.settings.posts_post',
'description' => 'rainlab.blog::lang.settings.posts_post_description',
'type' => 'dropdown',
'default' => 'blog/post',
'group' => 'rainlab.blog::lang.settings.group_links',
],
'exceptPost' => [
'title' => 'rainlab.blog::lang.settings.posts_except_post',
'description' => 'rainlab.blog::lang.settings.posts_except_post_description',
'type' => 'string',
'validationPattern' => '^[a-z0-9\-_,\s]+$',
'validationMessage' => 'rainlab.blog::lang.settings.posts_except_post_validation',
'default' => '',
'group' => 'rainlab.blog::lang.settings.group_exceptions',
],
'exceptCategories' => [
'title' => 'rainlab.blog::lang.settings.posts_except_categories',
'description' => 'rainlab.blog::lang.settings.posts_except_categories_description',
'type' => 'string',
'validationPattern' => '^[a-z0-9\-_,\s]+$',
'validationMessage' => 'rainlab.blog::lang.settings.posts_except_categories_validation',
'default' => '',
'group' => 'rainlab.blog::lang.settings.group_exceptions',
],
];
}
public function getCategoryPageOptions()
{
return Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName');
}
public function getPostPageOptions()
{
return Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName');
}
public function getSortOrderOptions()
{
$options = BlogPost::$allowedSortingOptions;
foreach ($options as $key => $value) {
$options[$key] = Lang::get($value);
}
return $options;
}
public function onRun()
{
$this->prepareVars();
$this->category = $this->page['category'] = $this->loadCategory();
$this->posts = $this->page['posts'] = $this->listPosts();
/*
* If the page number is not valid, redirect
*/
if ($pageNumberParam = $this->paramName('pageNumber')) {
$currentPage = $this->property('pageNumber');
if ($currentPage > ($lastPage = $this->posts->lastPage()) && $currentPage > 1) {
return Redirect::to($this->currentPageUrl([$pageNumberParam => $lastPage]));
}
}
}
protected function prepareVars()
{
$this->pageParam = $this->page['pageParam'] = $this->paramName('pageNumber');
$this->noPostsMessage = $this->page['noPostsMessage'] = $this->property('noPostsMessage');
/*
* Page links
*/
$this->postPage = $this->page['postPage'] = $this->property('postPage');
$this->categoryPage = $this->page['categoryPage'] = $this->property('categoryPage');
}
protected function listPosts()
{
$category = $this->category ? $this->category->id : null;
$categorySlug = $this->category ? $this->category->slug : null;
/*
* List all the posts, eager load their categories
*/
$isPublished = !$this->checkEditor();
$posts = BlogPost::with(['categories', 'featured_images'])->listFrontEnd([
'page' => $this->property('pageNumber'),
'sort' => $this->property('sortOrder'),
'perPage' => $this->property('postsPerPage'),
'search' => trim(input('search')),
'category' => $category,
'published' => $isPublished,
'exceptPost' => is_array($this->property('exceptPost'))
? $this->property('exceptPost')
: preg_split('/,\s*/', $this->property('exceptPost'), -1, PREG_SPLIT_NO_EMPTY),
'exceptCategories' => is_array($this->property('exceptCategories'))
? $this->property('exceptCategories')
: preg_split('/,\s*/', $this->property('exceptCategories'), -1, PREG_SPLIT_NO_EMPTY),
]);
/*
* Add a "url" helper attribute for linking to each post and category
*/
$posts->each(function($post) use ($categorySlug) {
$post->setUrl($this->postPage, $this->controller, ['category' => $categorySlug]);
$post->categories->each(function($category) {
$category->setUrl($this->categoryPage, $this->controller);
});
});
return $posts;
}
protected function loadCategory()
{
if (!$slug = $this->property('categoryFilter')) {
return null;
}
$category = new BlogCategory;
$category = $category->isClassExtendedWith('RainLab.Translate.Behaviors.TranslatableModel')
? $category->transWhere('slug', $slug)
: $category->where('slug', $slug);
$category = $category->first();
return $category ?: null;
}
protected function checkEditor()
{
$backendUser = BackendAuth::getUser();
return $backendUser &&
$backendUser->hasAccess('rainlab.blog.access_posts') &&
BlogSettings::get('show_all_posts', true);
}
}

View File

@ -0,0 +1,159 @@
<?php namespace RainLab\Blog\Components;
use Lang;
use Response;
use Cms\Classes\Page;
use Cms\Classes\ComponentBase;
use RainLab\Blog\Models\Post as BlogPost;
use RainLab\Blog\Models\Category as BlogCategory;
class RssFeed extends ComponentBase
{
/**
* A collection of posts to display
* @var Collection
*/
public $posts;
/**
* If the post list should be filtered by a category, the model to use.
* @var Model
*/
public $category;
/**
* Reference to the page name for the main blog page.
* @var string
*/
public $blogPage;
/**
* Reference to the page name for linking to posts.
* @var string
*/
public $postPage;
public function componentDetails()
{
return [
'name' => 'rainlab.blog::lang.settings.rssfeed_title',
'description' => 'rainlab.blog::lang.settings.rssfeed_description'
];
}
public function defineProperties()
{
return [
'categoryFilter' => [
'title' => 'rainlab.blog::lang.settings.posts_filter',
'description' => 'rainlab.blog::lang.settings.posts_filter_description',
'type' => 'string',
'default' => '',
],
'sortOrder' => [
'title' => 'rainlab.blog::lang.settings.posts_order',
'description' => 'rainlab.blog::lang.settings.posts_order_description',
'type' => 'dropdown',
'default' => 'created_at desc',
],
'postsPerPage' => [
'title' => 'rainlab.blog::lang.settings.posts_per_page',
'type' => 'string',
'validationPattern' => '^[0-9]+$',
'validationMessage' => 'rainlab.blog::lang.settings.posts_per_page_validation',
'default' => '10',
],
'blogPage' => [
'title' => 'rainlab.blog::lang.settings.rssfeed_blog',
'description' => 'rainlab.blog::lang.settings.rssfeed_blog_description',
'type' => 'dropdown',
'default' => 'blog/post',
'group' => 'rainlab.blog::lang.settings.group_links',
],
'postPage' => [
'title' => 'rainlab.blog::lang.settings.posts_post',
'description' => 'rainlab.blog::lang.settings.posts_post_description',
'type' => 'dropdown',
'default' => 'blog/post',
'group' => 'rainlab.blog::lang.settings.group_links',
],
];
}
public function getBlogPageOptions()
{
return Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName');
}
public function getPostPageOptions()
{
return Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName');
}
public function getSortOrderOptions()
{
$options = BlogPost::$allowedSortingOptions;
foreach ($options as $key => $value) {
$options[$key] = Lang::get($value);
}
return $options;
}
public function onRun()
{
$this->prepareVars();
$xmlFeed = $this->renderPartial('@default');
return Response::make($xmlFeed, '200')->header('Content-Type', 'text/xml');
}
protected function prepareVars()
{
$this->blogPage = $this->page['blogPage'] = $this->property('blogPage');
$this->postPage = $this->page['postPage'] = $this->property('postPage');
$this->category = $this->page['category'] = $this->loadCategory();
$this->posts = $this->page['posts'] = $this->listPosts();
$this->page['link'] = $this->pageUrl($this->blogPage);
$this->page['rssLink'] = $this->currentPageUrl();
}
protected function listPosts()
{
$category = $this->category ? $this->category->id : null;
/*
* List all the posts, eager load their categories
*/
$posts = BlogPost::with('categories')->listFrontEnd([
'sort' => $this->property('sortOrder'),
'perPage' => $this->property('postsPerPage'),
'category' => $category
]);
/*
* Add a "url" helper attribute for linking to each post and category
*/
$posts->each(function($post) {
$post->setUrl($this->postPage, $this->controller);
});
return $posts;
}
protected function loadCategory()
{
if (!$categoryId = $this->property('categoryFilter')) {
return null;
}
if (!$category = BlogCategory::whereSlug($categoryId)->first()) {
return null;
}
return $category;
}
}

View File

@ -0,0 +1,10 @@
{% if __SELF__.categories|length > 0 %}
<ul class="category-list">
{% partial __SELF__ ~ "::items"
categories = __SELF__.categories
currentCategorySlug = __SELF__.currentCategorySlug
%}
</ul>
{% else %}
<p>No categories were found.</p>
{% endif %}

View File

@ -0,0 +1,18 @@
{% for category in categories %}
{% set postCount = category.post_count %}
<li {% if category.slug == currentCategorySlug %}class="active"{% endif %}>
<a href="{{ category.url }}">{{ category.name }}</a>
{% if postCount %}
<span class="badge">{{ postCount }}</span>
{% endif %}
{% if category.children|length > 0 %}
<ul>
{% partial __SELF__ ~ "::items"
categories=category.children
currentCategorySlug=currentCategorySlug
%}
</ul>
{% endif %}
</li>
{% endfor %}

View File

@ -0,0 +1,27 @@
{% set post = __SELF__.post %}
<div class="content">{{ post.content_html|raw }}</div>
{% if post.featured_images|length %}
<div class="featured-images text-center">
{% for image in post.featured_images %}
<p>
<img
data-src="{{ image.filename }}"
src="{{ image.path }}"
alt="{{ image.description }}"
style="max-width: 100%" />
</p>
{% endfor %}
</div>
{% endif %}
<p class="info">
Posted
{% if post.categories|length %} in
{% for category in post.categories %}
<a href="{{ category.url }}">{{ category.name }}</a>{% if not loop.last %}, {% endif %}
{% endfor %}
{% endif %}
on {{ post.published_at|date('M d, Y') }}
</p>

View File

@ -0,0 +1,40 @@
{% set posts = __SELF__.posts %}
<ul class="post-list">
{% for post in posts %}
<li>
<h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
<p class="info">
Posted
{% if post.categories|length %} in {% endif %}
{% for category in post.categories %}
<a href="{{ category.url }}">{{ category.name }}</a>{% if not loop.last %}, {% endif %}
{% endfor %}
on {{ post.published_at|date('M d, Y') }}
</p>
<p class="excerpt">{{ post.summary|raw }}</p>
</li>
{% else %}
<li class="no-data">{{ __SELF__.noPostsMessage }}</li>
{% endfor %}
</ul>
{% if posts.lastPage > 1 %}
<ul class="pagination">
{% if posts.currentPage > 1 %}
<li><a href="{{ this.page.baseFileName|page({ (__SELF__.pageParam): (posts.currentPage-1) }) }}">&larr; Prev</a></li>
{% endif %}
{% for page in 1..posts.lastPage %}
<li class="{{ posts.currentPage == page ? 'active' : null }}">
<a href="{{ this.page.baseFileName|page({ (__SELF__.pageParam): page }) }}">{{ page }}</a>
</li>
{% endfor %}
{% if posts.lastPage > posts.currentPage %}
<li><a href="{{ this.page.baseFileName|page({ (__SELF__.pageParam): (posts.currentPage+1) }) }}">Next &rarr;</a></li>
{% endif %}
</ul>
{% endif %}

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>{{ this.page.meta_title ?: this.page.title }}</title>
<link>{{ link }}</link>
<description>{{ this.page.meta_description ?: this.page.description }}</description>
<atom:link href="{{ rssLink }}" rel="self" type="application/rss+xml" />
{% for post in posts %}
<item>
<title>{{ post.title }}</title>
<link>{{ post.url }}</link>
<guid>{{ post.url }}</guid>
<pubDate>{{ post.published_at.toRfc2822String }}</pubDate>
<description>{{ post.summary }}</description>
</item>
{% endfor %}
</channel>
</rss>

Some files were not shown because too many files have changed in this diff Show More