This commit is contained in:
2026-02-17 14:56:23 +01:00
commit 68f7a95fdf
695 changed files with 154611 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
<?php
namespace DynCom\mysyde\common\abstracts;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 18.06.2015
* Time: 10:09
*/
abstract class TemplateInserterBase {
protected $template;
protected $fieldData;
protected $allowTags = false;
/**
* TemplateInserterBase constructor.
* @param GenericTemplateInterface $template
* @param array $fieldData
* @param bool $allowTags
*/
public function __construct(GenericTemplateInterface $template, array $fieldData, $allowTags = false) {
$this->template = $template;
$this->fieldData = (($this->_validateFieldData($fieldData)) ? $fieldData : array());
$this->allowTags = (bool)$allowTags;
}
/**
* @param array $fieldData
* @return mixed
*/
abstract protected function _validateFieldData(array $fieldData);
abstract public function insertData();
}

View File

@@ -0,0 +1,83 @@
<?php
namespace DynCom\mysyde\common\abstracts;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/22/2015
* Time: 12:11 PM
*/
abstract class URLBase {
protected $protocol;
protected $user;
protected $password;
protected $domain;
protected $port;
protected $path;
protected $queryParams;
protected $anchor;
/**
* @return string
*/
public function getQueryString() {
$queryString = '';
if(is_array($this->queryParams)) {
$queryString .= '?';
$i = 0;
foreach($this->queryParams as $paramArr) {
$paramName = $paramArr['paramName'];
$paramVal = $paramArr['paramValue'];
if($i > 0) {
$queryString .= '&';
}
$queryString .= $paramName . '=' . $paramVal;
++$i;
}
}
return $queryString;
}
/**
* @return string
*/
public function getFullURL() {
if(null === ($this->domain)) {
throw new \RuntimeException('No domain-name set.');
}
if(null === ($this->protocol)) {
throw new \RuntimeException('No protocol set.');
}
//Protocol
$url = $this->protocol . '://';
//User/Pass
if(null !== $this->user) {
$url .= $this->user . ':';
if(null !== $this->password) {
$url .= $this->password;
}
$url .= '@';
}
//Domain
$url .= $this->domain;
//Port
if(null !== $this->port) {
$url .= ':' . $this->port;
}
//Path
if(null !== $this->path) {
$url .= $this->path;
}
//QueryString
if(null !== $this->queryParams) {
$url .= $this->getQueryString();
}
//Anchor
if(null !== $this->anchor) {
$url .= '#' . $this->anchor;
}
return $url;
}
}

View File

@@ -0,0 +1,300 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\traits\arrayMappableTrait;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 10.07.2015
* Time: 14:32
*/
class Address
{
use arrayMappableTrait;
protected $config;
/**
* Address constructor.
*/
public function __construct() {
$this->config = new AddressConfig();
}
public $salutation;
public $name;
public $name_2;
public $contact;
public $address;
public $address_extra;
public $address_street;
public $address_no;
public $post_code;
public $city;
public $country;
public $state;
public $phone_no;
public $surname;
public $lastname;
public $company_name;
/**
* @param array $rules
*/
public function setFieldValidationRules(array $rules) {
$this->config = clone $this->config;
$this->config->setFieldValidationRules($rules);
}
/**
* @return array
*/
public function getFieldValidationRules() {
return $this->config->getFieldValidationRules();
}
/**
* @param array $statusArr
* @return bool
*/
public function isValid(array $validationRules = null, array &$statusArr = []) {
$validationRules = $validationRules ?? $this->config->getFieldValidationRules();
$validator = new NewValidator($validationRules, $this->getAllFieldsAsArray());
return $validator->isValid($statusArr);
}
/**
* @param array $arr
* @return Address
*/
public static function fromArray(array $arr) {
$newAddr = new Address();
$newAddr->mapFromArray($arr);
$statusArr = [];
if(!$newAddr->isValid($statusArr)) {
throw new \InvalidArgumentException('Data for Address is not valid: Field status: ' . print_r($statusArr,1));
}
return $newAddr;
}
/**
* @return AddressConfig
*/
public function getConfig(): AddressConfig
{
return $this->config;
}
public function withSalutation(string $salutation): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['salutation'] = $salutation;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
public function withContact(string $contact): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['contact'] = $contact;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
public function withAddressStreet(string $addressStreet): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['address_street'] = $addressStreet;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
public function withAddressNo(string $addressNo): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['address_no'] = $addressNo;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
public function withAddressExtra(string $addressExtra): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['address_extra'] = $addressExtra;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
public function withCity(string $city): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['city'] = $city;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
public function withPostCode(string $postCode): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['post_code'] = $postCode;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
public function withCountry(string $country): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['country'] = $country;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
public function withState(string $state): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['state'] = $state;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
public function withPhoneNo(string $phoneNo): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['address_no'] = $phoneNo;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
public function withSurname(string $surname): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['surname'] = $surname;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
public function withLastName(string $lastName): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['lastname'] = $lastName;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
public function withCompanyName(string $companyName): Address
{
$arr = $this->getAllFieldsAsArray();
$arr['company_name'] = $companyName;
$newAddr = Address::fromArray($arr);
return $newAddr;
}
/**
* @return string|null
*/
public function getSalutation(): ?string
{
return $this->salutation;
}
/**
* @return string|null
*/
public function getContact(): ?string
{
return $this->contact;
}
/**
* @return string|null
*/
public function getAddressExtra(): ?string
{
return $this->address_extra;
}
/**
* @return string|null
*/
public function getAddressStreet(): ?string
{
return $this->address_street;
}
/**
* @return string|null
*/
public function getAddressNo(): ?string
{
return $this->address_no;
}
/**
* @return string|null
*/
public function getPostCode(): ?string
{
return $this->post_code;
}
/**
* @return string|null
*/
public function getCity(): ?string
{
return $this->city;
}
/**
* @return string|null
*/
public function getCountry(): ?string
{
return $this->country;
}
/**
* @return string|null
*/
public function getState(): ?string
{
return $this->state;
}
/**
* @return string|null
*/
public function getPhoneNo(): ?string
{
return $this->phone_no;
}
/**
* @return string|null
*/
public function getSurname(): ?string
{
return $this->surname;
}
/**
* @return string|null
*/
public function getLastname(): ?string
{
return $this->lastname;
}
/**
* @return string|null
*/
public function getCompanyName(): ?string
{
return $this->company_name;
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\GenericCollectionInterface;
use DynCom\mysyde\common\traits\genericCollectionTrait;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 10.07.2015
* Time: 23:57
*/
class AddressCollection implements GenericCollectionInterface
{
use genericCollectionTrait;
}

View File

@@ -0,0 +1,45 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 11.07.2015
* Time: 00:03
*/
class AddressConfig
{
protected $modelName = 'Address';
protected $fieldValidationData = [
'name' => 'name|required|maxlen:50',
'name_2' => 'name|maxlen:50',
'contact' => 'maxlen:50',
'address' => 'addrstreetplusno|required|maxlen:50',
'address_2' => 'addrstreetplusno|maxlen:50',
'address_street' => 'addrstreet|maxlen:50',
'address_no' => 'addrstreetno|maxlen:10',
'post_code' => 'required|addrzip|maxlen:20',
'city' => 'required|addrcity|maxlen:50',
'country' => 'required|maxlen:10',
'phone_no' => 'maxlen:80',
'state' => 'alpha|maxlen:30',
'surname' => 'name|maxlen:30',
'lastname' => 'name|maxlen:30',
'company_name' => 'maxlen:45',
];
/**
* @return array
*/
public function getFieldValidationRules() {
return $this->fieldValidationData;
}
/**
* @param array $rules
*/
public function setFieldValidationRules(array $rules) {
$this->fieldValidationData = $rules;
}
}

View File

@@ -0,0 +1,589 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Class Adminmenu
* @package DynCom\mysyde\common\classes
*/
class Adminmenu {
private static $adminMenu = NULL;
/**
* Adminmenu constructor.
*/
private function __construct() {
}
/**
* @param int $_active
* @return array|null
*/
public static function get($_active = 0 ) {
if (self::$adminMenu === NULL) {
$translation = \DynCom\mysyde\common\classes\Registry::get('translation');
self::$adminMenu = array(
'default' => array(
'name' => $translation->get('top_structure'),
'include' => CMS_PATH . "admin/dashboard_structure.php",
'linklistmenu' => FALSE,
),
// kollektionen
'collections' => array(
'name' => $translation->get('top_collections'),
'include' => MODULE_PATH . "collection/dashboard_collections.php",
'linklistmenu' => FALSE
),
// dashboard
'dashboard' => array(
'name' => $translation->get('top_dashboard'),
'include' => CMS_PATH . "admin/dashboard_startpage.php",
'linklistmenu' => FALSE
),
// Struktur
'structure' => array(
'name' => $translation->get('top_structure'),
'include' => CMS_PATH . "admin/dashboard_structure.php",
'linklistmenu' => FALSE,
'subsites' => array(
'sites' => array(
'name' => $translation->get('left_sites'),
'include' => CMS_PATH . "admin/edit_page.inc.php",
'linklistmenu' => TRUE,
'icon' => 'seiten.png'
),
'navigation' => array(
'name' => $translation->get('left_navigation'),
'include' => CMS_PATH . "admin/edit_main_navigation.inc.php",
'linklistmenu' => TRUE,
'icon' => 'navigation.png'
),
'files' => array(
'name' => $translation->get('left_files'),
'include' => CMS_PATH . "admin/filegallery.inc.php",
'linklistmenu' => TRUE,
'icon' => 'dateien.png'
),
'video_uploud' => array(
'name' => $translation->get('video_uploud'),
'include' => CMS_PATH . "admin/video_uploud/video_uploud.inc.php",
'linklistmenu' => TRUE,
'icon' => 'dateien.png'
),
'components' => array(
'name' => $translation->get('left_components'),
'include' => CMS_PATH . "admin/edit_component.inc.php",
'linklistmenu' => TRUE,
'icon' => 'bausteine.png'
),
)
),
// inhalte
'contents' => array(
'name' => $translation->get('top_contents'),
'include' => CMS_PATH . "admin/dashboard_contents.php",
'linklistmenu' => FALSE,
'subsites' => array(
'textcontent' => array(
'name' => $translation->get('left_text'),
'include' => MODULE_PATH . "textcontent/textcontent.php",
'admin_start_parameter' => "textcontent_edit",
'linklistmenu' => TRUE
),
'slideshow' => array(
'name' => $translation->get('left_slideshows'),
'include' => MODULE_PATH . "slideshow/slideshow.php",
'admin_start_parameter' => "slideshow_edit",
'linklistmenu' => TRUE
),
'multistep_forms' => array(
'name' => $translation->get('left_multistep_contactforms'),
'include' => MODULE_PATH . "contactform/contactform.php",
'admin_start_parameter' => "multi_contactform_edit",
'linklistmenu' => TRUE
),
'slidecontent' => array(
'name' => $translation->get('left_slidecontent'),
'include' => MODULE_PATH . "slidecontent/slidecontent.php",
'admin_start_parameter' => "slidecontent_edit",
'linklistmenu' => TRUE
),
'filegallery' => array(
'name' => $translation->get('left_filecontent'),
'include' => MODULE_PATH . "filegallery/filegallery.php",
'admin_start_parameter' => "filegallery_edit",
'linklistmenu' => TRUE
),
'gallery' => array(
'name' => $translation->get('left_imagegallery'),
'include' => MODULE_PATH . "gallery/gallery.php",
'admin_start_parameter' => "gallery_edit",
'linklistmenu' => TRUE
),
'magicscroll' => array(
'name' => $translation->get('left_scrollbars'),
'include' => MODULE_PATH . "magicscroll/magicscroll.php",
'admin_start_parameter' => "magicscroll_edit",
'linklistmenu' => TRUE
),
'googlemaps' => array(
'name' => $translation->get('left_googlemaps'),
'include' => MODULE_PATH . "googlemaps/googlemaps.php",
'admin_start_parameter' => "googlemaps_edit",
'linklistmenu' => TRUE
),
'facebook' => array(
'name' => $translation->get('left_facebook'),
'include' => MODULE_PATH . "facebook/facebook.php",
'admin_start_parameter' => "facebook_edit",
'linklistmenu' => TRUE
),
'youtube' => array(
'name' => $translation->get('left_youtube'),
'include' => MODULE_PATH . "youtube/youtube.php",
'admin_start_parameter' => "youtube_edit",
'linklistmenu' => TRUE
),
'iframe' => array(
'name' => $translation->get('left_extern'),
'include' => MODULE_PATH . "iframe/iframe.php",
'admin_start_parameter' => "iframe_edit",
'linklistmenu' => TRUE
),
)
),
// Statistik
'statistics' => array(
'name' => $translation->get('top_statistic'),
'include' => CMS_PATH . "admin/statistic.inc.php",
'linklistmenu' => FALSE,
'subsites' => array(
'mail_stat' => array(
'name' => $translation->get('left_mail_stat'),
'include' => CMS_PATH . "admin/mail_log.inc.php",
'linklistmenu' => TRUE
),
'access_stat' => array(
'name' => $translation->get('left_access_stat'),
'include' => CMS_PATH . "admin/statistic_access.inc.php",
'linklistmenu' => TRUE
)
)
),
// MODULE
'module' => array(
'name' => $translation->get('top_module'),
'include' => CMS_PATH . "admin/module.inc.php",
'linklistmenu' => FALSE
),
//FAQ
'faq' => array(
'name' => $translation->get('top_faq'),
'include' => MODULE_PATH . "faq/dashboard_faq.php",
'linklistmenu' => FALSE,
'subsites' => array(
'faq_main' => array(
'name' => $translation->get('left_faq'),
'include' => MODULE_PATH . "faq/faq.php",
'admin_start_parameter' => "faq_edit",
'linklistmenu' => TRUE
),
'config' => array(
'name' => $translation->get('left_faq_config'),
'include' => MODULE_PATH . "faq/faq.php",
'admin_start_parameter' => "faq_edit_setup",
'linklistmenu' => TRUE
)
)
),
// Contactform
'contactform' => array(
'name' => $translation->get('left_contactforms'),
'include' => MODULE_PATH . "contactform/contactform.php",
'admin_start_parameter' => "contactform_edit",
'linklistmenu' => TRUE
),
//Photo Approve
'photo_approve' => array(
'name' => $translation->get('photo_approve'),
'include' => MODULE_PATH . "photo_approve/photo_approve.inc.php",
'admin_start_parameter' => "photo_approve",
'linklistmenu' => TRUE
),
// Ticketcenter
'ticketcenter' => array(
'name' => $translation->get('left_tickets'),
'include' => MODULE_PATH . "ticketcenter/ticketcenter.inc.php",
'linklistmenu' => TRUE,
'subsites' => array(
'category' => array(
'name' => $translation->get('category'),
'include' => MODULE_PATH . "ticketcenter/category.inc.php",
'admin_start_parameter' => "",
'linklistmenu' => TRUE
),
'process' => array(
'name' => $translation->get('Process'),
'include' => MODULE_PATH . "ticketcenter/process.inc.php",
'admin_start_parameter' => "",
'linklistmenu' => TRUE
),
'status' => array(
'name' => $translation->get('Status'),
'include' => MODULE_PATH . "ticketcenter/status.inc.php",
'admin_start_parameter' => "",
'linklistmenu' => TRUE
)
)
),
// Bewerbermanagement
'bewerber' => array(
'name' => $translation->get('top_bewerbermanagement'),
'include' => MODULE_PATH . "bewerber/user/bewerber.php",
'linklistmenu' => FALSE,
'admin_start_parameter' => "bewerber_edit",
'subsites' => array(
'bewerbung' => array(
'name' => $translation->get('left_bewerbung'),
'include' => MODULE_PATH . "bewerber/user/bewerber.php",
'linklistmenu' => TRUE,
'admin_start_parameter' => "bewerbung_edit",
),
'stufe' => array(
'name' => $translation->get('left_stufe'),
'include' => MODULE_PATH . "bewerber/stufe.php",
'linklistmenu' => TRUE,
'admin_start_parameter' => "stufe_edit",
),
'process' => array(
'name' => $translation->get('left_process'),
'include' => MODULE_PATH . "bewerber/process/process.php",
'linklistmenu' => TRUE,
'admin_start_parameter' => "process_edit",
),
)
),
// Knowledgecenter
'knowledge' => array(
'name' => $translation->get('top_knowledgecenter'),
'include' => MODULE_PATH . "knowledgecenter/dashboard_knowledge.php",
'linklistmenu' => FALSE,
'subsites' => array(
'category' => array(
'name' => $translation->get('top_knowledge_category'),
'include' => MODULE_PATH . "knowledgecenter/knowledge.inc.php",
'linklistmenu' => TRUE
)
)
),
// E-Learning
'learning' => array(
'name' => $translation->get('top_learning'),
'include' => MODULE_PATH . "learning/dashboard_learning.php",
'linklistmenu' => FALSE,
'subsites' => array(
'category' => array(
'name' => $translation->get('learning_category'),
'include' => MODULE_PATH . "learning/learning.inc.php",
'linklistmenu' => TRUE
),
'unit' => array(
'name' => $translation->get('learning_unit'),
'include' => MODULE_PATH . "learning/learning_unit.inc.php",
'linklistmenu' => TRUE
)
)
),
// Zertifikate
'certificate' => array(
'name' => $translation->get('top_certificate'),
'include' => MODULE_PATH . "certificate/certificate.inc.php",
'linklistmenu' => TRUE
),
// Community Board
'community_board' => array(
'name' => $translation->get('top_community_board'),
'include' => MODULE_PATH . "knwoledgecenter/dashboard_knowledge.php",
'linklistmenu' => FALSE,
'subsites' => array(
'community_board_post' => array(
'name' => $translation->get('community_board_post'),
'include' => MODULE_PATH . "community_board/community_board_post.inc.php",
'linklistmenu' => TRUE
),
'community_board_category' => array(
'name' => $translation->get('community_board_category'),
'include' => MODULE_PATH . "community_board/community_board_category.inc.php",
'linklistmenu' => TRUE
)
)
),
// Infoboard
'infoboard' => array(
'name' => $translation->get('top_infoboard'),
'include' => MODULE_PATH . "infoboard/infoboard.inc.php",
'linklistmenu' => TRUE
),
// Essenslieferung
'meal_delivery' => array(
'name' => $translation->get('top_meal_delivery'),
'include' => MODULE_PATH . "intranet/meal_delivery_listform.inc.php",
'linklistmenu' => TRUE
),
// Infopoint
'infopoint' => array(
'name' => $translation->get('left_infopoint'),
'include' => MODULE_PATH . "infopoint/dashboard_infopoint.php",
'linklistmenu' => TRUE,
'subsites' => array(
'pages' => array(
'name' => $translation->get('infopoint_pages'),
'include' => MODULE_PATH . "infopoint/infopoint.php",
'admin_start_parameter' => "infopoint_pages",
'linklistmenu' => TRUE
),
'screens' => array(
'name' => $translation->get('infopoint_screens'),
'include' => MODULE_PATH . "infopoint/infopoint.php",
'admin_start_parameter' => "infopoint_screens",
'linklistmenu' => TRUE
),
'presets' => array(
'name' => $translation->get('infopoint_presets'),
'include' => MODULE_PATH . "infopoint/infopoint.php",
'admin_start_parameter' => "infopoint_presets",
'linklistmenu' => TRUE
),
)
),
// Intranet
'intranet' => array(
'name' => $translation->get('top_intranet'),
'subsites' => array(
'config_contact' => array(
'name' => $translation->get('top_contact'),
'include' => INTRANET_PATH . "admin/edit_contact.inc.php",
'linklistmenu' => TRUE
),
'config_mandant' => array(
'name' => $translation->get('top_mandant'),
'include' => INTRANET_PATH . "admin/edit_mandant.inc.php",
'linklistmenu' => TRUE
),
'config_department' => array(
'name' => $translation->get('top_department'),
'include' => INTRANET_PATH . "admin/edit_department.inc.php",
'linklistmenu' => TRUE
),
'config_space' => array(
'name' => $translation->get('top_space'),
'include' => INTRANET_PATH . "admin/edit_space.inc.php",
'linklistmenu' => TRUE
),
'config_role' => array(
'name' => $translation->get('top_role'),
'include' => INTRANET_PATH . "admin/edit_role.inc.php",
'linklistmenu' => TRUE
),
'config_facility' => array(
'name' => $translation->get('top_role'),
'include' => INTRANET_PATH . "admin/edit_facility.inc.php",
'linklistmenu' => TRUE
),
'config_permission' => array(
'name' => $translation->get('top_permission'),
'include' => INTRANET_PATH . "admin/edit_permission.inc.php",
'linklistmenu' => TRUE
)
)
),
// Konfiguration
'config' => array(
'name' => '<img src="/layout/admin/img/2015/settings.png" />',
'subsites' => array(
'config_websites' => array(
'name' => $translation->get('top_websites'),
'include' => CMS_PATH . "admin/edit_site.inc.php",
'linklistmenu' => TRUE
),
'config_language' => array(
'name' => $translation->get('top_languages'),
'include' => CMS_PATH . "admin/edit_language.inc.php",
),
'config_users' => array(
'name' => $translation->get('top_users'),
'include' => CMS_PATH . "admin/edit_admin_user.inc.php",
'linklistmenu' => FALSE
),
'config_layouts' => array(
'name' => $translation->get('top_layouts'),
'include' => CMS_PATH . "admin/edit_layout.inc.php",
'linklistmenu' => TRUE
),
'log' => array(
'name' => $translation->get('top_log'),
'include' => CMS_PATH . "admin/mysyde_log.php",
'linklistmenu' => TRUE
),
'config_collections' => array(
'name' => $translation->get('top_collections'),
'include' => MODULE_PATH . "collection/collection.php",
'admin_start_parameter' => "collection_edit_setup",
'linklistmenu' => TRUE
),
'config_geoip' => array(
'name' => $translation->get('geoip'),
'include' => CMS_PATH . "admin/ip_geo_location.inc.php",
),
'config_url_management' => array(
'name' => $translation->get('url_management'),
'include' => CMS_PATH . "admin/edit_url_management.inc.php",
),
'config_google_recaptcha' => array(
'name' => $translation->get('recaptcha'),
'include' => CMS_PATH . "admin/recaptcha.php",
),
'sitemap' => array(
'name' => $translation->get('sitemap'),
'include' => MODULE_PATH . "sitemap/sitemap.inc.php",
'linklistmenu' => FALSE,
'admin_start_parameter' => "sitemap_edit",
),
)
),
// Hilfe
'help' => array(
'name' => '<img src="/layout/admin/img/2015/help.png" />',
'subsites' => array(
'help_license' => array(
'name' => $translation->get('top_license'),
'include' => CMS_PATH . "admin/licence.inc.php",
'linklistmenu' => FALSE
),
'help_systeminfo' => array(
'name' => $translation->get('top_systeminfo'),
'include' => CMS_PATH . "admin/phpinfo.php",
'linklistmenu' => FALSE
),
'help_help' => array(
'name' => $translation->get('top_help'),
'include' => CMS_PATH . "admin/help.php",
'linklistmenu' => FALSE
),
)
)
);
}
if ($GLOBALS['admin_user']['right_create_user'] == 1 | $GLOBALS['admin_user']['is_super_user'] == 1) {
self::$adminMenu['config']['subsites']['config_users']['linklistmenu'] = TRUE;
}
// kollektionsmenu
self::create_collections_menu();
// Shopmenu
self::create_shop_menu();
return self::$adminMenu;
}
protected static function create_collections_menu() {
$query = "SELECT * FROM main_collection_setup WHERE (main_language_id = " . (int)$GLOBALS["language"]['id'] . " OR all_languages = 1)";
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
if (@mysqli_num_rows($result) == 0) {
return;
}
self::$adminMenu['collections']['subsites'] = array();
while ($row = @mysqli_fetch_array($result)) {
self::$adminMenu['collections']['subsites'][$row['id']] = array(
'name' => $row['description'],
'include' => MODULE_PATH . "collection/collection.php",
'admin_start_parameter' => "collection_edit",
'linklistmenu' => TRUE
);
}
$query = "SELECT ms.id, ms.main_language_id, ms.code, ms.description, ms.linked, ms.icon, ms.modified_user, ms.modified_date, ms.all_languages, ms.show_filter FROM main_collection_setup as ms INNER JOIN main_collection_setup_websites as mcsw on ms.id = mcsw.main_collection_setup_id WHERE mcsw.main_site_id = ".$GLOBALS['site']['id']." AND ms.is_multidomain = 1";
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
while ($row = @mysqli_fetch_array($result)) {
self::$adminMenu['collections']['subsites'][$row['id']] = array(
'name' => $row['description'],
'include' => MODULE_PATH . "collection/collection.php",
'admin_start_parameter' => "collection_edit",
'linklistmenu' => TRUE
);
}
}
protected static function create_shop_menu() {
$translation = \DynCom\mysyde\common\classes\Registry::get('translation');
$query = "SHOW TABLES LIKE 'shop_shop'";
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
if (@mysqli_num_rows($result) == 0) {
return; //---> Shop nicht vorhanden
}
self::$adminMenu['statistics']['subsites']["order_stat"] = array(
'name' => $translation->get('left_order_stat'),
'include' => CMS_PATH . "admin/order_statistic.inc.php",
'linklistmenu' => TRUE
);
self::$adminMenu['statistics']['subsites']["search_stat"] = array(
'name' => $translation->get('left_search_stat'),
'include' => CMS_PATH . "admin/search_query_statistic.inc.php",
'linklistmenu' => TRUE
);
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/23/2015
* Time: 1:17 PM
*/
class BasicControlFlowHandler {
/**
* @param array $controlFlowArray
*/
public function evaluateControlFlowArray( array &$controlFlowArray ) {
foreach($controlFlowArray as &$controlFlowElement) {
$this->_evaluateControlFlowArrayElementRecursive($controlFlowElement);
}
}
/**
* @param array $controlFlowElement
*/
protected function _evaluateControlFlowArrayElementRecursive(array &$controlFlowElement) {
$count = count($controlFlowElement);
if(!is_array($controlFlowElement) || !($count > 0 && $count < 4)) {
throw new \InvalidArgumentException('Every entry to the controlFlowArray must be an array with 3 entries: condition, iftrue, iffalse.');
}
$condition = $controlFlowElement[0];
$ifTrueAction = (isset($controlFlowElement[1]) ? $controlFlowElement[1]:function(){});
$ifFalseAction = (isset($controlFlowElement[2]) ? $controlFlowElement[2]:function(){});
if(is_callable(($condition))) {$condition = $condition();}
if((bool)$condition === true) {
if(is_callable($ifTrueAction)) {
$ifTrueAction();
} elseif(is_array($ifTrueAction)) {
$this->_evaluateControlFlowArrayElementRecursive($ifTrueAction);
};
} elseif((bool)$condition === false) {
if(is_callable($ifFalseAction)) {
$ifFalseAction();
} elseif(is_array($ifFalseAction)) {
$this->_evaluateControlFlowArrayElementRecursive($ifFalseAction);
}
}
}
}

View File

@@ -0,0 +1,477 @@
<?php
/**
* Created by PhpStorm.
* User: lorenz
* Date: 12.07.2017
* Time: 13:18
*/
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\classes\Site;
use GuzzleHttp;
class CleverReachConnector
{
private $account;
private $login;
private $pass;
private $groupId;
private $authToken;
private $client;
private $addTokenParam = false;
private $hasUrlParams = false;
private $globalAttributes = array();
private $groupAttributes = array();
private $error = false;
private $errorMessages = array();
private $optInFormId = null;
const CLEVERREACH_BASE_URL = 'https://rest.cleverreach.com/v2/';
/**
* CleverReachConnector constructor.
* @param $account
* @param $login
* @param $pass
* @param $group
*/
public function __construct($account, $login, $pass, $group)
{
$this->account = $account;
$this->login = $login;
$this->pass = $pass;
if (!isset($this->client) || !($this->client instanceof GuzzleHttp\Client)) {
$this->client = new GuzzleHttp\Client(['http_errors' => false]);
}
$this->login();
if (is_int($group)) {
$this->setGroupById($group);
} elseif (is_string($group)) {
$this->setGroupByName($group);
}
$this->setGlobalAttributes();
$this->setLocalAttributes();
$this->getOptInFormId();
}
/**
* @return mixed
*/
public function getGroupId()
{
return $this->groupId;
}
/**
* @return bool
*/
public function isError(): bool
{
return $this->error;
}
/**
* @return array
*/
public function getErrorMessages(): array
{
return $this->errorMessages;
}
/**
* @param string $method
* @param string $operation
* @param array $data
*/
private function request(string $method = 'POST', string $operation, array $data = []) {
$response = null;
if (isset($this->authToken) || !$this->addTokenParam) {
$response = $this->client->request($method, '' . self::CLEVERREACH_BASE_URL . $operation . ($this->addTokenParam ? $this->getTokenParam() : ''), ['body' => json_encode($data)]);
}
unset($this->addTokenParam);
unset($this->hasUrlParams);
return $response;
}
private function getResponseStatusCode($response) {
return $response->getStatusCode();
}
private function getResponseBodyContent($response) {
return json_decode($response->getBody()->getContents());
}
private function getTokenParam() {
return ($this->hasUrlParams ? '&' : '?') . 'token=' . $this->authToken;
}
private function setErrorMessage($errorMessage,$response = null) {
$errorMessage = (!is_null($response) ? $errorMessage . " - Statuscode: " . $this->getResponseStatusCode($response) : $errorMessage);
return $errorMessage;
}
private function login() {
if (isset($this->login) && isset($this->account) && isset($this->pass)) {
$response = $this->request('POST','login.json',["client_id" => $this->account,"login" => $this->login,"password" => $this->pass],false);
if ($this->getResponseStatusCode($response) == 200) {
$this->authToken = $this->getResponseBodyContent($response);
} else {
$this->error = true;
$this->errorMessages["login"] = $this->setErrorMessage("Login Error",$response);
}
}
}
public function refresh() {
$response = $this->request('POST','refresh.json');
if ($this->getResponseStatusCode($response) == 200) {
$this->authToken = $this->getResponseBodyContent($response);
} else {
$this->error = true;
$this->errorMessages["refresh"] = $this->setErrorMessage("Login Error",$response);
}
}
public function getOptInFormId() {
$this->addTokenParam = true;
$response = $this->request('GET','forms.json');
if ($this->getResponseStatusCode($response) == 200) {
$forms = $this->getResponseBodyContent($response);
foreach ($forms as $form) {
if ($form->name === "DOI") {
$this->optInFormId = $form->id;
return;
}
}
}
$this->error = true;
$this->errorMessages["getOptInFormId"] = $this->setErrorMessage("getOptInFormId Error",$response);
}
public function getClients() {
$this->addTokenParam = true;
$response = $this->request('GET','clients.json');
if ($this->getResponseStatusCode($response) == 200) {
return $this->getResponseBodyContent($response);
}
$this->error = true;
$this->errorMessages["getClients"] = $this->setErrorMessage("Client Error",$response);
return false;
}
public function createGroup(string $name) {
$this->addTokenParam = true;
$response = $this->request('POST','groups.json',["name" => $name]);
if ($this->getResponseStatusCode($response) == 200) {
return $this->getResponseBodyContent($response);
}
$this->error = true;
$this->errorMessages["createGroup"] = $this->setErrorMessage("Create Group Error",$response);
return false;
}
private function getGroups() {
$this->addTokenParam = true;
$response = $this->request('GET','groups.json');
if ($this->getResponseStatusCode($response) == 200) {
return $this->getResponseBodyContent($response);
}
$this->error = true;
$this->errorMessages["getGroups"] = $this->setErrorMessage("Get Groups Error",$response);
return false;
}
public function getGroup(int $groupId) {
}
private function setGroupById(int $groupId) {
$this->setGroup($groupId);
}
private function setGroupByName(string $groupName) {
$this->setGroup(null,$groupName);
}
private function setGroup(int $groupId = null, string $groupName = null) {
if (is_null($this->groupId)) {
if (!is_null($groupId) || !is_null($groupName)) {
if (!is_null($groupId)) {
$this->groupId = $groupId;
} else {
$cleverReachGroups = $this->getGroups();
foreach ($cleverReachGroups as $cleverReachGroup) {
if ($cleverReachGroup->name == $groupName) {
$this->groupId = $cleverReachGroup->id;
return;
}
}
$group = $this->createGroup($groupName);
$this->groupId = $group->id;
}
} else {
$this->error = true;
$this->errorMessages["setGroup"] = $this->setErrorMessage("Set Group Error");
}
}
}
private function checkGlobalAttributes() {
}
private function checkGroupAttributes() {
}
public function getReceiversForGroup(int $groupId) {
}
public function upsertReceivers(array $receivers) {
foreach ($receivers as &$receiver) {
$actualReceiverResponse = $this->getReceiverByMail($receiver["email"]);
if ($this->getResponseStatusCode($actualReceiverResponse) == 200) {
$actualReceiver = $this->getResponseBodyContent($actualReceiverResponse);
if ($receiver["activated"] == 0 && $actualReceiver->activated <> 0) {
$receiver["activated"] = $actualReceiver->activated;
}
if ($actualReceiver->registered <> 0) {
$receiver["registered"] = $actualReceiver->registered;
}
if (!isset($actualReceiver->global_attributes->coupon) || $actualReceiver->global_attributes->coupon == "") {
$receiver["global_attributes"]["coupon"] = array(
"value" => get_nl_coupon(),
"type" => 'text',
"description" => 'Coupon',
);
}
} else {
$receiver["global_attributes"]["coupon"] = array(
"value" => get_nl_coupon(),
"type" => 'text',
"description" => 'Coupon',
);
}
$globalAttributesToAdd = array_diff_key($receiver["global_attributes"],$this->globalAttributes);
foreach ($globalAttributesToAdd as $attributeName => $attributeValue) {
$result = $this->addAttribute($attributeName,$attributeValue["description"],$attributeValue["type"]);
if ($result) {
$this->globalAttributes[$result->name] = $result->id;
}
}
foreach ($receiver["global_attributes"] as $key => &$value) {
$value = $value["value"];
}
unset($value);
$groupAttributesToAdd = array_diff_key($receiver["attributes"],$this->groupAttributes);
foreach ($groupAttributesToAdd as $attributeName => $attributeValue) {
$result = $this->addAttribute($attributeName,$attributeValue["description"],$attributeValue["type"],true);
if ($result) {
$this->groupAttributes[$result->name] = $result->id;
}
}
foreach ($receiver["attributes"] as $key => &$value) {
$value = $value["value"];
}
unset($value);
}
unset($receiver);
$this->addTokenParam = true;
$response = $this->request('POST','groups.json/' . $this->groupId . '/receivers/upsert',["postdata" => $receivers]);
if ($this->getResponseStatusCode($response) == 200) {
$this->sendOptInMail($receivers);
return $this->getResponseBodyContent($response);
}
$this->error = true;
$this->errorMessages["upsertReceivers"] = $this->setErrorMessage("Upsert Receivers Error",$response);
return false;
}
public function unsubscrineReceivers(array $receivers) {
foreach ($receivers as $receiver) {
$this->addTokenParam = true;
$response = $this->request('PUT','groups.json/' . $this->groupId . '/receivers/' . urlencode($receiver["email"]) . '/setinactive',["postdata" => $receivers]);
if ($this->getResponseStatusCode($response) != 200) {
$this->error = true;
$this->errorMessages["unsubscrineReceivers"] = $this->setErrorMessage("Unsubscribe Receivers Error",$response);
}
}
if ($this->error) {
return false;
}
return true;
}
private function sendOptInMail($receivers) {
if (!is_null($this->optInFormId)) {
foreach ($receivers as $receiver) {
if ($receiver["activated"] == 0 && $receiver["send_doi_mail"]) {
$this->addTokenParam = true;
$data = array(
"email" => $receiver["email"],
"groups_id" => $this->groupId,
"doidata" => array(
"user_ip" => $_SERVER["REMOTE_ADDR"],
"referer" => $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"],
"user_agent" => $_SERVER["HTTP_USER_AGENT"]
)
);
$this->addTokenParam = true;
$response = $this->request('POST','forms.json/' . $this->optInFormId . '/send/activate',$data);
if ($this->getResponseStatusCode($response) != 200) {
$this->error = true;
$this->errorMessages["sendOptInMail"] = $this->setErrorMessage("sendOptInMail Error",$response);
}
}
}
} else {
$this->error = true;
$this->errorMessages["sendOptInMail"] = $this->setErrorMessage("No DOI form found");
}
}
public function addReceiverOrderItemById(int $id, string $orderItem) {
return $this->addReceiverOrderItem($id,$orderItem);
}
public function addReceiverOrderItemByMail(string $email, string $orderItem) {
return $this->addReceiverOrderItem($email,$orderItem);
}
private function addReceiverOrderItem($identifier, string $orderItem) {
}
public function getReceiverById(int $id) {
return $this->getReceiver($id);
}
public function getReceiverByMail(string $email) {
return $this->getReceiver($email);
}
private function getReceiver($identifier) {
$this->addTokenParam = true;
$this->hasUrlParams = true;
$response = $this->request('GET','receivers.json/' . $identifier . '?group_id=' . $this->groupId);
return $response;
}
public function deleteReceiverById(int $id) {
return $this->deleteReceiver($id);
}
public function deleteReceiverByMail(string $email) {
return $this->deleteReceiver($email);
}
private function deleteReceiver($identifier) {
}
public function createAttribute(array $attributeData, int $groupId = null) {
}
public function activateReceiverById(int $id, int $groupId) {
return $this->activateReceiver($id,$groupId);
}
public function activateReceiverByMail(string $email, int $groupId) {
return $this->activateReceiver($email,$groupId);
}
private function activateReceiver($identifier, int $groupId) {
}
public function deActivateReceiverById(int $id, int $groupId) {
return $this->deActivateReceiver($id,$groupId);
}
public function deActivateReceiverByMail(string $email, int $groupId) {
return $this->deActivateReceiver($email,$groupId);
}
private function deActivateReceiver($identifier, int $groupId) {
}
public function sendForm(int $formId, bool $activate, array $data) {
}
public function getGlobalAttributes() {
$this->addTokenParam = true;
$response = $this->request('GET','attributes.json');
if ($this->getResponseStatusCode($response) == 200) {
return $this->getResponseBodyContent($response);
}
$this->error = true;
$this->errorMessages["getGlobalAttributes"] = $this->setErrorMessage("Get Global Atrributes Error",$response);
return false;
}
private function setGlobalAttributes() {
$attributes = $this->getGlobalAttributes();
if ($attributes) {
foreach ($attributes as $attribute) {
$this->globalAttributes[$attribute->name] = $attribute->id;
}
}
}
public function getGroupAttributes() {
$this->addTokenParam = true;
$this->hasUrlParams = true;
$response = $this->request('GET','attributes.json?group_id=' . $this->groupId);
if ($this->getResponseStatusCode($response) == 200) {
return $this->getResponseBodyContent($response);
}
$this->error = true;
$this->errorMessages["getLocalAttributes"] = $this->setErrorMessage("Get Local Atrributes Error",$response);
return false;
}
private function setLocalAttributes() {
$attributes = $this->getGroupAttributes();
if ($attributes) {
foreach ($attributes as $attribute) {
$this->groupAttributes[$attribute->name] = $attribute->id;
}
}
}
public function addAttribute($name,$description,$type,$groupBound = false) {
$this->addTokenParam = true;
$dataAr = ["name" => $name, "description" => $description, "type" => $type];
if ($groupBound) {
$dataAr["groups_id"] = $this->groupId;
}
$response = $this->request('POST','attributes.json',$dataAr);
if ($this->getResponseStatusCode($response) == 200) {
return $this->getResponseBodyContent($response);
}
$this->error = true;
$this->errorMessages["addAttribute"] = $this->setErrorMessage("Add Atrributes Error",$response);
return false;
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Class CollectionTypes
* @package DynCom\mysyde\common\classes
*/
class CollectionTypes {
private static $collectionTypes = NULL;
/**
* CollectionTypes constructor.
*/
private function __construct() {
}
/**
* @return array|null
*/
public static function get() {
if (self::$collectionTypes === NULL) {
$translation = \DynCom\mysyde\common\classes\Registry::get('translation');
self::$collectionTypes = array(
1 => array( // Text
'description' => $translation->get("text"),
'class' => 'inhalt_text',
'code' => 'textcontent'
),
2 => array( // Textarea
'description' => $translation->get("textarea"),
'class' => 'inhalt_slideshow',
'code' => 'textarea'
),
6 => array( // DropDown
'description' => $translation->get("optionfield"),
'class' => 'inhalt_slideshow',
'code' => 'dropdown'
),
7 => array( // Checkbox
'description' => $translation->get("checkbox"),
'class' => 'inhalt_slideshow',
'code' => 'checkbox'
),
3 => array( // Datum
'description' => $translation->get("date"),
'class' => 'inhalt_contact',
'code' => 'date'
),
4 => array( // Link
'description' => $translation->get("link"),
'class' => 'inhalt_accordion',
'code' => 'link'
),
5 => array( // Bild
'description' => $translation->get("image"),
'class' => 'inhalt_files',
'code' => 'image'
),
8 => array( // Icon Dropdown
'description' => $translation->get("icon"),
'class' => 'inhalt_slideshow',
'code' => 'icon'
),
9 => array( // Contact Dropdown
'description' => $translation->get("contact"),
'class' => 'inhalt_text',
'code' => 'contact'
),
10 => array( // Uhrzeit
'description' => $translation->get("time"),
'class' => 'inhalt_contact',
'code' => 'time'
),
);
}
return self::$collectionTypes;
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Michael Bauer
* Date: 7/14/2015
* Time: 12:04 AM
*/
class DOMNodeView
{
}

View File

@@ -0,0 +1,36 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\ViewModel;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/23/2015
* Time: 11:22 PM
*/
class DOMViewModelTest implements ViewModel {
/**
* @return array
*/
public function getData() {
$tmpDoc = new \DOMDocument();
$el = $tmpDoc->createElement('a');
$el->setAttribute('href','#inserted-field3');
$el->setAttribute('id','inserted-field3');
$txtNode1 = $tmpDoc->createTextNode('inserted-field3');
$el->appendChild($txtNode1);
$domDoc = new \DOMDocument();
$span = $domDoc->createElement('span');
$span->setAttribute('id','inserted-field4');
$domDoc->appendChild($span);
$arr = [
'insertField1' => 'inserted-field1',
'insertField2' => '<span id="inserted-field2">TestInsertion2</span>',
'insertField3' => $el,
'insertField4' => $domDoc
];
return $arr;
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 15.07.2015
* Time: 12:46
*/
class EMail
{
protected $email;
/**
* EMail constructor.
* @param $email
*/
public function __construct($email) {
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
throw new \InvalidArgumentException(
"A valid eMail must be passed to the constructor."
);
}
$this->email = $email;
}
public function getAddress() {
return $this->email;
}
/**
* @return mixed
*/
public function getDomain() {
return explode('@',$this->email)[1];
}
}

View File

@@ -0,0 +1,189 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* A class to handle secure encryption and decryption of arbitrary data
*
* Note that this is not just straight encryption. It also has a few other
* features in it to make the encrypted data far more secure. Note that any
* other implementations used to decrypt data will have to do the same exact
* operations.
*
* Security Benefits:
*
* - Uses Key stretching
* - Hides the Initialization Vector
* - Does HMAC verification of source data
*
*/
class Encryption
{
/**
* @var string $cipher The mcrypt cipher to use for this instance
*/
protected $cipher = '';
/**
* @var int $mode The mcrypt cipher mode to use
*/
protected $mode = '';
/**
* @var int $rounds The number of rounds to feed into PBKDF2 for key generation
*/
protected $rounds = 100;
/**
* Constructor!
*
* @param string $cipher The MCRYPT_* cypher to use for this instance
* @param int $mode The MCRYPT_MODE_* mode to use for this instance
* @param int $rounds The number of PBKDF2 rounds to do on the key
*/
public function __construct($cipher, $mode, $rounds = 100)
{
$this->cipher = $cipher;
$this->mode = $mode;
$this->rounds = (int)$rounds;
}
/**
* Decrypt the data with the provided key
*
* @param string $data The encrypted datat to decrypt
* @param string $key The key to use for decryption
*
* @returns string|false The returned string if decryption is successful
* false if it is not
*/
// public function decrypt($data, $key)
// {
// $salt = substr($data, 0, 128);
// $enc = substr($data, 128, -64);
// $mac = substr($data, -64);
// list ($cipherKey, $macKey, $iv) = $this->getKeys($salt, $key);
// if (!hash_equals(hash_hmac('sha512', $enc, $macKey, true), $mac)) {
// return false;
// }
// $dec = mcrypt_decrypt($this->cipher, $cipherKey, $enc, $this->mode, $iv);
// $data = $this->unpad($dec);
// return $data;
// }
/**
* Encrypt the supplied data using the supplied key
*
* @param string $data The data to encrypt
* @param string $key The key to encrypt with
*
* @returns string The encrypted data
*/
// public function encrypt($data, $key)
// {
// $salt = mcrypt_create_iv(128, MCRYPT_DEV_URANDOM);
// list ($cipherKey, $macKey, $iv) = $this->getKeys($salt, $key);
// $data = $this->pad($data);
// $enc = mcrypt_encrypt($this->cipher, $cipherKey, $data, $this->mode, $iv);
// $mac = hash_hmac('sha512', $enc, $macKey, true);
// return $salt . $enc . $mac;
// }
/**
* Generates a set of keys given a random salt and a master key
*
* @param string $salt A random string to change the keys each encryption
* @param string $key The supplied key to encrypt with
*
* @returns array An array of keys (a cipher key, a mac key, and a IV)
*/
protected function getKeys($salt, $key)
{
// $ivSize = mcrypt_get_iv_size($this->cipher, $this->mode);
// $keySize = mcrypt_get_key_size($this->cipher, $this->mode);
$length = 2 * $keySize + $ivSize;
$key = $this->pbkdf2('sha512', $key, $salt, $this->rounds, $length);
$cipherKey = substr($key, 0, $keySize);
$macKey = substr($key, $keySize, $keySize);
$iv = substr($key, 2 * $keySize);
return array($cipherKey, $macKey, $iv);
}
/**
* Stretch the key using the PBKDF2 algorithm
*
* @see http://en.wikipedia.org/wiki/PBKDF2
*
* @param string $algo The algorithm to use
* @param string $key The key to stretch
* @param string $salt A random salt
* @param int $rounds The number of rounds to derive
* @param int $length The length of the output key
*
* @returns string The derived key.
*/
protected function pbkdf2($algo, $key, $salt, $rounds, $length)
{
$size = strlen(hash($algo, '', true));
$len = ceil($length / $size);
$result = '';
for ($i = 1; $i <= $len; $i++) {
$tmp = hash_hmac($algo, $salt . pack('N', $i), $key, true);
$res = $tmp;
for ($j = 1; $j < $rounds; $j++) {
$tmp = hash_hmac($algo, $tmp, $key, true);
$res ^= $tmp;
}
$result .= $res;
}
return substr($result, 0, $length);
}
/**
* @param $data
* @return string
*/
protected function pad($data)
{
// $length = mcrypt_get_block_size($this->cipher, $this->mode);
$padAmount = $length - strlen($data) % $length;
if ($padAmount == 0) {
$padAmount = $length;
}
return $data . str_repeat(chr($padAmount), $padAmount);
}
/**
* @param $data
* @return bool|string
*/
protected function unpad($data)
{
// $length = mcrypt_get_block_size($this->cipher, $this->mode);
$last = ord($data[strlen($data) - 1]);
if ($last > $length) return false;
if (substr($data, -1 * $last) !== str_repeat(chr($last), $last)) {
return false;
}
return substr($data, 0, -1 * $last);
}
/**
* @param $a
* @param $b
* @return bool
*/
function hash_equals($a, $b) {
// $key = mcrypt_create_iv(128, MCRYPT_DEV_URANDOM);
return hash_hmac('sha512', $a, $key) === hash_hmac('sha512', $b, $key);
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\FlattenedGettable;
use DynCom\mysyde\dcShop\traits\genericDecoratorTrait;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 16.07.2015
* Time: 13:12
*/
class FlattenedGettableDecorator implements FlattenedGettable
{
use genericDecoratorTrait;
/**
* FlattenedGettableDecorator constructor.
* @param $entityToDecorate
*/
public function __construct($entityToDecorate) {
if(!is_object($entityToDecorate)) {
throw new \InvalidArgumentException(
"entityToDecorate must be an object"
);
}
$this->decoratedEntity = $entityToDecorate;
}
/**
* @return string
*/
public function getDecoratedEntityClassName() {
return get_class($this->decoratedEntity);
}
/**
* @return array
*/
public function getFlattened() {
$ref = new \ReflectionClass($this->decoratedEntity);
$arr = [];
foreach ($ref->getProperties() as $property) {
$name = $property->name;
$val = $this->decoratedEntity->$name;
$this->addFieldToArray($name,$val,$arr);
}
return $arr;
}
/**
* @param $fieldName
* @param $fieldValue
* @param array $array
*/
protected function addFieldToArray($fieldName, &$fieldValue, array &$array) {
$val = $this->$fieldName;
$fieldAdded = false;
if(is_object($val)) {;
if($val instanceof FlattenedGettable) {
$subFieldArr = $val->getFlattened();
foreach ($subFieldArr as $subFieldName => &$subFieldValue) {
$this->addFieldToArray($subFieldName, $subFieldValue, $array);
}
unset($subFieldValue);
$fieldAdded = true;
}
}
if(!$fieldAdded) {
$array[$fieldName] = clone $fieldValue;
}
}
}

View File

@@ -0,0 +1,798 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\ViewModel;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/13/2015
* Time: 12:56 AM
*/
class Form {
/**
* @var \DOMNode
*/
protected $el;
protected $elText;
protected $isValid = null;
protected $fieldValidity = array();
protected $prefillFromSuperglobal = false;
protected $id = null;
protected $fields = null;
protected $fieldNames = null;
protected $fieldLabels = array();
protected $fieldRules = array();
protected $IDWrapperIDMap;
protected $isRendered = false;
protected $rendered;
protected $elementsByID = [];
/**
* @param \DOMElement $el
*/
public function __construct( \DOMElement $el ) {
if($el->tagName !== 'form') {
throw new \InvalidArgumentException('Parameter must be \DOMElement with tagName \'form\'.');
}
$this->el = $el;
$this->el->ownerDocument->validateOnParse = true;
$this->id = $el->getAttribute('id');
}
/**
* @param boolean $prefillFromSuperglobal
*/
public function setPrefillFromSuperglobal($prefillFromSuperglobal)
{
$this->prefillFromSuperglobal = (bool)$prefillFromSuperglobal;
}
/**
* @param FormElement $formElement
* @param null $parentElementID
* @param null $inputLabelText
*/
public function addElement(FormElement $formElement, $parentElementID = null, $inputLabelText = null) {
$newEl = $formElement->getEl();
$doc = &$this->el->ownerDocument;
@$doc->validate();
$formMethod = $this->el->getAttribute('method');
$formMethodArray = array();
$fieldType = $newEl->tagName;
$fieldName = $newEl->getAttribute('name');
$fieldValue = $newEl->getAttribute('value');
if(null !== $inputLabelText && $fieldName) {
$this->fieldLabels[$fieldName] = $inputLabelText;
}
$fieldID = $newEl->getAttribute('id');
$fieldIsHidden = ($newEl->getAttribute('type') === 'hidden');
$parent = null;
if($parentElementID) {
$parent = $this->elementsByID[$parentElementID];
}
if($this->prefillFromSuperglobal) {
if(strcasecmp($formMethod,'post') === 0) { $formMethod = 'post'; $formMethodArray = &$_POST;}
if(strcasecmp($formMethod,'get') === 0) { $formMethod = 'get'; $formMethodArray = &$_GET;}
if (($fieldType === 'input' || $fieldType === 'textarea') && isset($formMethodArray[$fieldName]) && !(mb_strlen($fieldValue, 'UTF-8') > 0)) {
$fieldValue = $formMethodArray[$fieldName];
$newEl->setAttribute('value', $fieldValue);
}
if ($fieldType === 'select' && isset($formMethodArray[$fieldName]) && !(mb_strlen($fieldValue, 'UTF-8') > 0)) {
$optionValue = $formMethodArray[$fieldName];
$this->setSelectedOptionByValue($newEl,$optionValue);
}
}
if(($fieldType === 'input' || $fieldType === 'textarea' || $fieldType === 'select') && !$fieldIsHidden) {
$this->fields[$fieldName] = $newEl->ownerDocument->saveXML($newEl);
$this->fieldNames[] = $fieldName;
if(null !== $inputLabelText) {
$label = $doc->createElement('label');
$label->setAttribute('for',$fieldName);
$textNode = $doc->createTextNode($inputLabelText);
$label->appendChild($textNode);
}
}
$fieldEL = $newEl;
if(($fieldType === 'input' || $fieldType === 'textarea' || $fieldType === 'select' || $fieldType === 'submit') && !$fieldIsHidden) {
$elWrappingDiv = $doc->createElement('div');
$totalID = '';
if($fieldName !== '') {
$totalID = 'input_' . $fieldName . '_wrapper';
} elseif($fieldID !== '') {
$totalID = 'input_' . $fieldID . '_wrapper';
}
$elWrappingDiv->setAttribute('id',$totalID);
$elWrappingDiv->setIdAttribute('id',true);
$elWrappingDiv->setAttribute('class','form_input_wrapper');
$this->el->appendChild($elWrappingDiv);
$elWrappingDiv->appendChild($newEl);
$fieldEL = $elWrappingDiv;
if($totalID !== '' && $fieldID !== '') {
$this->IDWrapperIDMap[$fieldID] = $totalID;
}
}
if(isset($label)) {
$labelWrappingDiv = $doc->createElement('div');
$labelWrappingDiv->setAttribute('class','form_label_wrapper');
$totalID = '';
if($fieldName !== '') {
$totalID = 'combined_' . $fieldName . '_wrapper';
} elseif($fieldID !== '') {
$totalID = 'combined_' . $fieldID . '_wrapper';
}
$labelWrappingDiv->setAttribute('id',$totalID);
$labelWrappingDiv->setIdAttribute('id',true);
$labelWrappingDiv->appendChild($label);
$totalWrappingDiv = $doc->createElement('div');
@$totalWrappingDiv->setAttribute('id',$totalID);
@$totalWrappingDiv->setIdAttribute('id',true);
$totalWrappingDiv->appendChild($labelWrappingDiv);
$totalWrappingDiv->appendChild($fieldEL);
$fieldEL = $totalWrappingDiv;
if($totalID !== '' && $fieldID !== '') {
$this->IDWrapperIDMap[$fieldID] = $totalID;
}
}
if(null !== $parent) {
$finalEl = $parent->appendChild($fieldEL);
} else {
$finalEl = $this->el->appendChild($fieldEL);
}
if($fieldID) {
$this->elementsByID[$fieldID] = &$finalEl;
}
}
/**
* @param \DOMElement $el
* @param $value
*/
public function setSelectedOptionByValue(\DOMElement $el, $value) {
foreach($el->getElementsByTagName('option') as $option) {
if($option instanceof \DOMElement) {
$currValue = $option->getAttribute('value');
$option->removeAttribute('selected');
if ($currValue === $value) {
$option->setAttribute('selected', 'selected');
}
}
}
}
/**
* @param \DOMText $textNode
* @param $id
*/
public function setElementTextNodeByID(\DOMText $textNode, $id ) {
$doc = $this->el->ownerDocument;
$el = $doc->getElementById($id);
if($el) {
$el->insertBefore($textNode,$el->firstChild);
}
}
/**
* @param $id
* @return bool
*/
public function removeElementByID($id ) {
$removalID = ($this->IDWrapperIDMap[$id]?:$id);
$doc = $this->el->ownerDocument;
$removalEl = $doc->getElementById($removalID);
if($removalEl) {
$removalParent = $removalEl->parentNode;
return ($removalParent->removeChild($removalEl) === $removalEl);
}
return false;
}
/**
* @param array $rulesArr
*/
public function setFieldRules(array $rulesArr ) {
foreach($rulesArr as $fieldName => $rulesString) {
$sep = Validator::CONF_RULE_SEPARATOR;
$rules = explode($sep,$rulesString);
foreach($rules as $rule) {
$this->setFieldRule($fieldName,$rule);
}
}
}
/**
* @param $fieldName
* @param $rule
*/
public function setFieldRule($fieldName, $rule ) {
$ruleArr = explode(':',$rule,2);
$ruleName = $ruleArr[0];
if(!array_key_exists($fieldName,$this->fields)) {
throw new \InvalidArgumentException(
sprintf(
'%s is not the name of an input-Field in this form. Available fields are %s',
$fieldName,
print_r(array_keys($this->fields),1)
)
);
}
if(!Validator::isValidDefaultInlineRuleName($ruleName)) {
throw new \InvalidArgumentException(
sprintf(
'\'%s\' is not the name of a validation-rule.',
$ruleName
)
);
}
$this->fieldRules[$fieldName][$ruleName] = $rule;
}
public function render() {
$doc = $this->el->ownerDocument;
$this->addRequiredFieldClass();
$this->setInvalidFieldClass();
$this->rendered = $doc->saveHTML();
$this->isRendered = true;
}
public function getRenderedContent() {
$this->render();
return $this->rendered;
}
protected function addRequiredFieldClass() {
$doc = $this->getDOMDocument();
if(is_array($this->fieldRules)) {
$XPath = new \DOMXPath($doc);
$inputNodeList = $XPath->query('//input[@type!="hidden"] | //select | //textarea');
$nodeArr = [];
$inputCount = $inputNodeList->length;
for ($i = 0; $i < $inputCount; ++$i) {
$currNode = $inputNodeList->item($i);
$name = $currNode->attributes->getNamedItem('name');
if($name) {
$fieldName = $name->nodeValue;
$nodeArr[$fieldName] = $currNode;
}
}
if(count($nodeArr) > 0) {
foreach ($this->fieldRules as $fieldName => $ruleArr) {
foreach ($ruleArr as $ruleName => $rule) {
if ($ruleName === 'required') {
$labelNodeList = $XPath->query('//label[@for="' . $fieldName . '"]');
$labelCount = $labelNodeList->length;
if($labelCount === 1) {
$label = $labelNodeList->item(0);
$labelParent = $label->parentNode;
$labelClassAttr = $label->attributes->getNamedItem('class');
$labelParentClassAttr = $labelParent->attributes->getNamedItem('class');
if(!$labelClassAttr) {
$labelClassAttr = $label->appendChild(new \DOMAttr('class'));
}
$value = ($labelClassAttr->nodeValue) ?: '';
if(strpos($value,' required_input_label') === false) {
$value .= ' required_input_label';
}
$labelClassAttr->nodeValue = $value;
$parentValue = $labelParentClassAttr->nodeValue ?: '';
if(strpos($parentValue,' required_input_label_wrapper') === false) {
$parentValue .= ' required_input_label_wrapper';
}
$labelParentClassAttr->nodeValue = $parentValue;
}
$currNode = $nodeArr[$fieldName];
$classAttr = $currNode->attributes->getNamedItem('class');
if(!$classAttr) {
$classAttr = $currNode->appendChild(new \DOMAttr('class'));
}
$value = $classAttr->nodeValue ?: '';
if(strpos($value,' required_input') === false) {
$value .= ' required_input';
}
$classAttr->nodeValue = $value;
$parent = $currNode->parentNode;
$parentClassAttr = $parent->attributes->getNamedItem('class');
if (stristr($parentClassAttr->nodeValue, 'form_input_wrapper') &&
(strpos($parentClassAttr->nodeValue,' required_input_wrapper') === false)) {
$parentClassAttr->nodeValue .= ' required_input_wrapper';
}
}
}
}
}
}
}
/**
* @return \DOMDocument
*/
public function getDOMDocument() {
return $this->el->ownerDocument;
}
/**
* @return \DOMElement
*/
public function getEl() {
return $this->el;
}
/**
* @return \DOMDocument
*/
public function getOwnerDocument() {
return $this->el->ownerDocument;
}
/**
* @return null
*/
public function getFieldNames() {
return $this->fieldNames;
}
/**
* @return array
*/
public function getNamesValidatedFields() {
return array_keys($this->fieldRules);
}
/**
* @return array
*/
public function __sleep() {
$doc = $this->el->ownerDocument;
$this->elText = $doc->saveXML($this->el);
$this->el = null;
$propertiesToSerialize = array(
'elText',
'fields',
'fieldNames',
'fieldLabels',
'fieldRules',
'IDWrapperIDMap'
);
return $propertiesToSerialize;
}
public function __wakeup() {
$tmpDoc = new \DOMDocument();
@$tmpDoc->loadXML($this->elText);
$el = $tmpDoc->documentElement;
$this->el = $el;
}
/**
* @return array
*/
public function validateRequestAgainstRules() {
$method = $this->el->getAttribute('method');
$sourceArr = &$_REQUEST;
if(strcasecmp($method,'post') === 0) {
$sourceArr = &$_POST;
} elseif(strcasecmp($method,'get') === 0) {
$sourceArr = &$_GET;
}
$fieldNames = array_keys($this->fields);
$fieldData = array();
foreach($fieldNames as $name) {
if(isset($sourceArr[$name])) {
$fieldData[$name] = $sourceArr[$name];
}
}
$rules = $this->getFieldRules();
$ruleFields = array_keys($rules);
$validator = new Validator($rules, $fieldData);
$fieldStatusArr = array();
$isValid = $validator->isValid($fieldStatusArr);
foreach($ruleFields as $name) {
$fieldLabel = (array_key_exists($name,$this->fieldLabels) ? $this->fieldLabels[$name] : '');
$fieldStatusArr[$name]['fieldLabel'] = $fieldLabel;
}
$this->fieldValidity = $fieldStatusArr;
$this->setInvalidFieldClass();
$this->isValid = $isValid;
return $fieldStatusArr;
}
/**
* @return array
*/
public function getFieldRules() {
$returnArr = array();
foreach($this->fieldRules as $fieldName => $ruleArr) {
$ruleStr = '';
$i = 0;
foreach($ruleArr as $ruleName) {
if($i > 0) {
$ruleStr .= Validator::CONF_RULE_SEPARATOR;
}
$ruleStr .= $ruleName;
if($ruleStr !== '') {
$returnArr[$fieldName] = $ruleStr;
}
++$i;
}
}
return $returnArr;
}
/**
* @return null
*/
public function isRequestValid() {
if(null === $this->isValid) {
throw new \LogicException(
sprintf(
'%s needs to be called before %s can be called.',
'"validateRequestAgainstRules"',
__METHOD__
)
);
}
return $this->isValid;
}
/**
* @return null|string
*/
public function getID() {
return $this->id;
}
/**
* @return array
*/
public function getFieldStatusArr() {
return $this->fieldValidity;
}
public function validatePrefillAndAddErrors() {
$statusArr = $this->validateInputValuesAgainstRules();
$fields = array_keys($statusArr);
foreach($fields as $fieldName) {
$errorMsgs = $this->getFieldErrorMsgs($fieldName);
foreach($errorMsgs as $msg) {
$this->addUserFormError($msg);
}
}
}
/**
* @return array
*/
public function validateInputValuesAgainstRules() {
$inputs = $this->el->getElementsByTagName('input');
$nodeCount = $inputs->length;
$rules = $this->getFieldRules();
$ruleFields = array_keys($rules);
$fieldData = array();
for($i = 0;$i < $nodeCount;++$i) {
$currEl = $inputs->item($i);
$name = $currEl->getAttribute('name');
$value = $currEl->getAttribute('value');
if($name && $value && in_array($name,$ruleFields)) {
$fieldData[$name] = $value;
}
}
if((count($fieldData) > 0) && (count($rules) > 0)) {
$validator = new Validator($rules, $fieldData);
$fieldStatusArr = array();
$isValid = $validator->isValid($fieldStatusArr);
$this->fieldValidity = $fieldStatusArr;
$this->setInvalidFieldClass();
$this->isValid = $isValid;
return $fieldStatusArr;
} else {
return array();
}
}
protected function setInvalidFieldClass() {
if($this->fieldValidity) {
$doc = $this->getOwnerDocument();
$XPath = new \DOMXPath($doc);
$inputNodeList = $XPath->query('//input[@type!="hidden"] | //select | //textarea');
$nodeArr = [];
$inputCount = $inputNodeList->length;
for ($i = 0; $i < $inputCount; ++$i) {
$currNode = $inputNodeList->item($i);
$name = $currNode->attributes->getNamedItem('name');
if($name) {
$fieldName = $name->nodeValue;
$nodeArr[$fieldName] = $currNode;
}
}
foreach($this->fieldValidity as $fieldName => $fieldStatus) {
if(isset($fieldStatus['unmatchedRules'])) {
$currNode = $nodeArr[$fieldName];
$labelNodeList = $XPath->query('//label[@for="' . $fieldName . '"]');
$labelCount = $labelNodeList->length;
if($labelCount === 1) {
$label = $labelNodeList->item(0);
$labelParent = $label->parentNode;
$labelClassAttr = $label->attributes->getNamedItem('class');
if(!$labelClassAttr) {
$labelClassAttr = $label->appendChild(new \DOMAttr('class'));
}
$labelParentClassAttr = $labelParent->attributes->getNamedItem('class');
if(!$labelParentClassAttr) {
$labelParentClassAttr = $labelParent->appendChild(new \DOMAttr('class'));
}
$labelValue = $labelClassAttr->nodeValue ?: '';
$labelValue .= 'invalid_input_label';
$labelClassAttr->nodeValue = $labelValue;
$labelParentValue = $labelParentClassAttr->nodeValue ?: '';
$labelParentValue .= ' invalid_input_label_wrapper';
$labelParentClassAttr->nodeValue = $labelParentValue;
}
$classAttr = $currNode->attributes->getNamedItem('class');
$classAttr->nodeValue .= ' invalid_input';
$parent = $currNode->parentNode;
$parentClassAttr = $parent->attributes->getNamedItem('class');
if (stristr($parentClassAttr->nodeValue, 'form_input_wrapper')) {
$parentClassAttr->nodeValue .= ' invalid_input_wrapper';
}
}
}
}
}
/**
* @param $fieldName
* @return array
*/
public function getFieldErrorMsgs($fieldName ) {
$msgArr = array();
if(isset($this->fieldValidity[$fieldName]['unmatchedRules'])) {
$label = ((isset($this->fieldLabels[$fieldName])) ? $this->fieldLabels[$fieldName]:$fieldName);
foreach($this->fieldValidity[$fieldName]['unmatchedRules'] as $ruleArr) {
$errorMsgRaw = $ruleArr['ruleError'];
$errorMsg = str_replace('%fieldname%','<strong>'.$label.'</strong>',$errorMsgRaw);
$errorMsg = str_replace('%validationparam%','<strong>'.$ruleArr['ruleValue'].'</strong>',$errorMsg);
$msgArr[] = $errorMsg;
}
}
return $msgArr;
}
/**
* @param $errorText
*/
public function addUserFormError($errorText) {
$doc = $this->el->ownerDocument;
$errorDiv = $doc->createElement('div');
$errorDiv->setAttribute('class','form_error form_error_' . $this->id);
$errorDivText = $doc->createTextNode(strip_tags($errorText));
$errorDiv->appendChild($errorDivText);
$this->el->insertBefore($errorDiv,$this->el->firstChild);
}
/**
* @param array $arr
*/
public function doPrefillFromArray(array &$arr) {
$XPath = new \DOMXPath($this->el->ownerDocument);
$inputNodeList = $XPath->query('//input[@type!=\'button\' and @type!=\'submit\' and not(starts-with(@name,\'fmd\'))] | //textarea | //select');
$inputCount = $inputNodeList->length;
for($i=0;$i<$inputCount;++$i) {
$currNode = $inputNodeList->item($i);
$nameAttr = $currNode->attributes->getNamedItem('name');
$nameAttr = $nameAttr ?: $currNode->attributes->getNamedItem('id');
$currNodeName = $nameAttr->nodeValue;
$newVal = (array_key_exists($currNodeName,$arr)) ? $arr[$currNodeName] : null;
if(isset($newVal) && mb_strlen($currNodeName,'UTF-8') > 0) {
if($currNode->nodeName === 'select') {
$this->setSelectedOptionByValue($currNode,$newVal);
} else {
$valueAttr = $currNode->attributes->getNamedItem('value');
$valueAttr = $valueAttr ?: $currNode->appendChild(new \DOMAttr('value'));
$prevVal = $valueAttr->nodeValue;
$newVal = $newVal ?: $prevVal;
$valueAttr->nodeValue = $newVal;
}
}
}
}
/**
* @param ViewModel $viewModel
*/
public function doPrefillFromViewModel(ViewModel $viewModel) {
$arr = $viewModel->getData();
$this->doPrefillFromArray($arr);
}
public function doPrefillFromSuperglobal() {
$formMethod = $this->el->getAttribute('method');
$formMethodArray = array();
if(strcasecmp($formMethod,'post') === 0) { $formMethod = 'post'; $formMethodArray = &$_POST;}
if(strcasecmp($formMethod,'get') === 0) { $formMethod = 'get'; $formMethodArray = &$_GET;}
$this->doPrefillFromArray($formMethodArray);
}
/**
* @return bool
*/
public function removeMetaDataFields() {
return $this->removeElementsByXPathQuery('//input[starts-with(@name,\'fmd\')]');
}
/**
* @param $query
* @return bool
*/
public function removeElementsByXPathQuery($query) {
$xpath = new \DOMXPath($this->el->ownerDocument);
$somethingRemoved = false;
foreach($xpath->query($query) as $e ) {
// Delete this node
$e->parentNode->removeChild($e);
$somethingRemoved = true;
}
return $somethingRemoved;
}
/**
* @param $id
* @param $class
*/
public function wrapInDIV($id, $class) {
$div = $this->el->ownerDocument->createElement('div');
$div->setAttribute('id',strip_tags($id));
$div->setAttribute('class',strip_tags($class));
$this->el->ownerDocument->appendChild($div);
$div->appendChild($this->el);
}
/**
* @var array
*/
protected $registeredViewModels = [];
/**
* @param ViewModel $viewModel
* @param array $fieldInputMappings
* @throws \InvalidArgumentException
*/
public function registerViewModel(ViewModel $viewModel, array $fieldInputMappings) {
$viewModelClassName = get_class($viewModel);
$viewModelInitValues = $viewModel->getData();
//$this->viewModelInitValues[$viewModelClassName] = $viewModel->getData();
$viewModelFields = array_keys($viewModelInitValues);
$formFields = array_keys($this->fields);
$mappingFormFields = array_keys($fieldInputMappings);
$mappingViewModelFields = array_values($fieldInputMappings);
$allFormFieldsValid = count(array_intersect($mappingFormFields, $formFields)) === count($mappingFormFields);
$allViewModelFieldsValid = count(array_intersect($mappingViewModelFields,$viewModelFields)) === count($mappingViewModelFields);
if(!$allFormFieldsValid) {
throw new \InvalidArgumentException('The keys of paramter fieldInputMappings must all be inputs registered with the form.');
}
if(!$allViewModelFieldsValid) {
throw new \InvalidArgumentException('The values of paramter fieldInputMappings must all be fields of the viewModel.');
}
$this->registeredViewModels[$viewModelClassName]['initValuesArray'] = $viewModelInitValues;
$this->registeredViewModels[$viewModelClassName]['fieldMappings'] = $fieldInputMappings;
}
/**
* @param ViewModel $viewModel
* @param array $fieldFilter
*/
public function prefillFromViewModel(ViewModel $viewModel, array $fieldFilter = []) {
$viewModelClassName = get_class($viewModel);
if(!array_key_exists('fieldMappings',$this->registeredViewModels[$viewModelClassName])) {
throw new \InvalidArgumentException("ViewModel $viewModelClassName has not already been registered successfully.");
}
$viewModelFieldMappings = $this->registeredViewModels[$viewModelClassName]['fieldMappings'];
$mapToFields = array_keys($viewModelFieldMappings);
$mapFromViewModelFields = array_values($viewModelFieldMappings);
$mappingData = [];
$viewModelData = $viewModel->getData();
foreach($mapToFields as $fieldName) {
$mappingData[$fieldName] = $viewModelData[$fieldName];
}
$XPath = new \DOMXPath($this->el->ownerDocument);
$inputNodeList = $XPath->query('//input[not(starts-with(@name,\'fmd\'))] | //textarea | //select');
$inputCount = $inputNodeList->length;
for($i=0;$i<$inputCount;++$i) {
$currNode = $inputNodeList->item($i);
$currNodeName = '';
@$currNodeName = $currNode->attributes->getNamedItem('name')->nodeValue;
if(array_key_exists($currNodeName,$mappingData) && isset($formMethodArray[$currNodeName]) && mb_strlen($currNodeName, 'UTF-8') > 0) {
if ($currNode->nodeName === 'select') {
$val = $mappingData[$currNodeName];
$this->setSelectedOptionByValue($currNode, $val);
} else {
@$currNode->setAttribute('value', $mappingData[$currNodeName]);
}
}
}
}
/**
* @return bool
*/
public function isFormRendered() {
return $this->isRendered;
}
/**
* @param $fieldName
* @param $fieldValue
*/
public function setFieldData($fieldName, $fieldValue) {
if(!in_array($fieldName,$this->fieldNames,false)) {
throw new \InvalidArgumentException(
'No field of name ' . strip_tags($fieldName) . ' is registered in the current form.'
);
}
$XPath = new \DOMXPath(($this->el->ownerDocument));
$nodeList = $XPath->query('//input[@name=\'' . $fieldName . '\']');
if(!$nodeList->length > 0) {
$nodeList = $XPath->query('//select[@name=\'' . $fieldName . '\']');
if(!$nodeList->length > 0) {
$nodeList = $XPath->query('//textarea[@name=\'' . $fieldName . '\']');
}
}
if($nodeList->length === 1) {
$field = $nodeList->item(0);
$tagName = $field->nodeName;
switch($tagName) {
case 'input':
@$field->setAttribute('value', strip_tags($fieldValue));
break;
case 'select':
$this->setSelectedOptionByValue($field,$fieldValue);
break;
case 'textarea':
@$field->setAttribute('value', strip_tags($fieldValue));
break;
default: break;
}
}
}
/**
* @return array
*/
public function getAllFieldData() {
$XPath = new \DOMXPath(($this->el->ownerDocument));
$nodeList = $XPath->query('//input | //select | //textarea');
$arr = [];
$len = $nodeList->length;
for($i=0;$i < $len;++$i) {
$currItem = $nodeList->item($i);
@$nameAttr = $currItem->attributes->getNamedItem('name');
@$valueAttr = $currItem->attributes->getNamedItem('value');
@$nameVal = $nameAttr->nodeValue;
@$valueVal = $valueAttr->nodeValue;
if($nameVal && $valueVal) {
$arr[$nameVal] = $valueVal;
}
}
return $arr;
}
}

View File

@@ -0,0 +1,892 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\ViewModel;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/13/2015
* Time: 12:16 AM
*/
class FormBuilder
{
// const FORMBUILDER_ENCRYPTION_ALGORITHM = MCRYPT_TWOFISH;
const ELEMENT_HIDDEN = 'hidden'; //input
const ELEMENT_TEXT = 'text'; //input
const ELEMENT_TEXTAREA = 'textarea';
const ELEMENT_SELECT = 'select';
const ELEMENT_OPTION = 'option';
const ELEMENT_PASSWORD = 'password'; //input
const ELEMENT_EMAIL = 'email'; //input
const ELEMENT_FILE = 'file'; //input
const ELEMENT_SUBMIT = 'submit'; //input
const ELEMENT_FIELDSET = 'fieldset';
const ELEMENT_BUTTON = 'button'; //input
const ELEMENT_COLOR = 'color'; //input
const ELEMENT_DATE = 'date'; //input
const ELEMENT_DATETIME = 'datetime'; //input
const ELEMENT_DATETIME_LOCAL = 'local'; //input
const ELEMENT_IMAGE = 'image'; //input
const ELEMENT_NUMBER = 'number'; //input
const ELEMENT_RADIO = 'radio'; //input
const ELEMENT_SEARCH = 'search'; //input
const ELEMENT_TEL = 'tel'; //input
const ELEMENT_TIME = 'time'; //input
const ELEMENT_WEEK = 'week'; //input
const ELEMENT_MONTH = 'month'; //input
const ELEMENT_CHECKBOX = 'checkbox'; //input
const ELEMENT_LEGEND = 'legend';
const ELEMENT_RANGE = 'range'; //input
const ELEMENT_DIV = 'div';
const ELEMENT_SPAN = 'span';
const ELEMENT_ANCHOR = 'anchor';
const ELEMENT_H1 = 'h1';
const ELEMENT_H2 = 'h2';
const ELEMENT_H3 = 'h3';
const ELEMENT_HR = 'hr';
const ELEMENT_TEXTNODE = 'textnode';
/**
* @var array
*/
private $constants = array(
self::ELEMENT_HIDDEN => array('tagname' => 'input', 'attributes' => array('type' => 'hidden')),
self::ELEMENT_TEXT => array('tagname' => 'input', 'attributes' => array('type' => 'text')),
self::ELEMENT_TEXTAREA => array('tagname' => 'input', 'attributes' => array()),
self::ELEMENT_SELECT => array('tagname' => 'select', 'attributes' => array('autocomplete' => 'off')),
self::ELEMENT_OPTION => array('tagname' => 'option', 'attributes' => array()),
self::ELEMENT_PASSWORD => array('tagname' => 'input','attributes' => array('type' => 'password')),
self::ELEMENT_EMAIL => array('tagname' => 'input','attributes' => array('type' => 'email')),
self::ELEMENT_FILE => array('tagname' => 'input','attributes' => array('type' => 'file')),
self::ELEMENT_SUBMIT => array('tagname' => 'input','attributes' => array('type' => 'submit')),
self::ELEMENT_FIELDSET => array('tagname' => 'fieldset','attributes' => array()),
self::ELEMENT_BUTTON => array('tagname' => 'input','attributes' => array('type' => 'button')),
self::ELEMENT_COLOR => array('tagname' => 'input','attributes' => array('type' => 'color')),
self::ELEMENT_DATE => array('tagname' => 'input','attributes' => array('type' => 'date')),
self::ELEMENT_DATETIME => array('tagname' => 'input','attributes' => array('type' => 'datetime')),
self::ELEMENT_DATETIME_LOCAL => array('tagname' => 'input','attributes' => array('type' => 'datetime-local')),
self::ELEMENT_IMAGE => array('tagname' => 'input', 'attributes' => array('type' => 'image')),
self::ELEMENT_NUMBER => array('tagname' => 'input', 'attributes' => array('type' => 'number')),
self::ELEMENT_RADIO => array('tagname' => 'input', 'attributes' => array('type' => 'radio')),
self::ELEMENT_SEARCH => array('tagname' => 'input', 'attributes' => array('type' => 'search')),
self::ELEMENT_TEL => array('tagname' => 'input', 'attributes' => array('type' => 'tel')),
self::ELEMENT_TIME => array('tagname' => 'input', 'attributes' => array('type' => 'time')),
self::ELEMENT_WEEK => array('tagname' => 'input', 'attributes' => array('type' => 'week')),
self::ELEMENT_MONTH => array('tagname' => 'input', 'attributes' => array('type' => 'month')),
self::ELEMENT_CHECKBOX => array('tagname' => 'input', 'attributes' => array('type' => 'checkbox')),
self::ELEMENT_LEGEND => array('tagname' => 'legend', 'attributes' => array()),
self::ELEMENT_RANGE => array('tagname' => 'input', 'attributes' => array('type' => 'range')),
self::ELEMENT_DIV => array('tagname' => 'div', 'attributes' => array()),
self::ELEMENT_SPAN => array('tagname' => 'span', 'attributes' => array()),
self::ELEMENT_H1 => array('tagname' => 'h1', 'attributes' => array()),
self::ELEMENT_H2 => array('tagname' => 'h2', 'attributes' => array()),
self::ELEMENT_H3 => array('tagname' => 'h3', 'attributes' => array()),
self::ELEMENT_HR => array('tagname' => 'hr', 'attributes' => array()),
self::ELEMENT_TEXTNODE => array('tagname' => '', 'attributes' => array()),
self::ELEMENT_ANCHOR => array('tagname' => 'a', 'attributes' => array())
);
/**
* see setAttributes method for usage example
* @var array
*/
protected $bannedAttributes = array(
'type' => 'type is set by FormBuilder',
'style' => 'Front-end is not the job of a builder',
'onclick' => 'Learn JS'//add other on* attributes
);
/**
* @var Form
*/
protected $form;//the actual form we're building
protected $id;
protected $isRendered = false;
protected $processedPostForms = array();
protected $processedGetForms = array();
protected $processedRequestForms = array();
/**
* @param $id
* @param array $options
*/
public function __construct($id, array $options = null)
{//allow for user to pass specifics, like form attributes
$this->id = strip_tags($id);
$domImpl = new \DOMImplementation();
$doc = $domImpl->createDocument(null, 'html',
$domImpl->createDocumentType('html',
'-//W3C//DTD XHTML 1.0 Transitional//EN',
'/mysyde/common/xhtml11.dtd'));
$doc->formatOutput = true;
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$doc->validateOnParse = true;
$formNode = $doc->createElement('form');
$formNode->setAttribute('id',$this->id);
$formNode->setIdAttribute('id',true);
if ($options && isset($options))
{
$formNode = $this->setAttributes(
$formNode,
$options
);
}
$html = $doc->getElementsByTagName('html')->item(0);
$formNode = $html->appendChild($formNode);
$this->form = new Form($formNode);//create Form wrapper...
}
/**
* @param $newID
* @param array|null $options
*/
public function reset($newID, array $options = null) {
$this->form = null;
$this->id = null;
$this->isRendered = false;
$this->processedPostForms = [];
$this->processedGetForms = [];
$this->processedRequestForms = [];
$this->id = strip_tags($newID);
$doc = new \DOMDocument('1.0', 'UTF-8');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$doc->validateOnParse = true;
$doc->validateOnParse = true;
$formNode = $doc->createElement('form');
$formNode->setAttribute('id',$this->id);
$formNode->setIdAttribute('id',true);
if ($options && isset($options))
{
$formNode = $this->setAttributes(
$formNode,
$options
);
}
$this->form = new Form($formNode);//create Form wrapper...
}
/**
* @param $type
* @return array
*/
protected function _getDefaultAttrs($type) {
return($this->constants[$type]['attributes'])?:array();
}
/**
* @param $type
* @return string
*/
protected function _getTagnameForType($type) {
return($this->constants[$type]['tagname'])?:'';
}
/**
* @param $type
* @param array $attributes
* @param null $parentElementID
* @param null $labelText
* @param array $selectOptions
* @return \DOMElement|FormElement
* @throws \InvalidArgumentException
*/
public function addField($type, array $attributes = array(), $parentElementID = null, $labelText = null, array $selectOptions = array())
{
$locAttributes = $attributes;
if (!array_key_exists($type,$this->constants))
{//optionally allow for direct \DOMElement injection here, but I wouldn't
throw new \InvalidArgumentException(
sprintf(
'%s is not a valid type (use %s::ELEMENT_* constants)',
$type,
__CLASS__
)
);
}
$constantsArr = $this->constants[$type];
$tagname = $constantsArr['tagname'];
$defaultAttributes = $constantsArr['attributes'];
$formEl = $this->form->getOwnerDocument();
$test = $formEl->createElement('div');
$doc = $formEl;
foreach($locAttributes as $attrName => $attrVal) {
if (array_key_exists($attrName,$this->bannedAttributes))
{
throw new \InvalidArgumentException(
sprintf(
'%s attribute not allowed: %s',
$attrName,
$this->bannedAttributes[$attrName]
)
);
}
}
//Set default attributes, overwriting potential user-set value for default(/constant)-attributes
foreach ($defaultAttributes as $name => $val) {
$locAttributes[$name] = $val;
}
//Set id from name if latter is set while former is not
if(!array_key_exists('id',$locAttributes) && array_key_exists('name',$locAttributes)) {
$locAttributes['id'] = $this->id . '_' . $locAttributes['name'];
}
if($type !== self::ELEMENT_TEXTNODE) {
$el = $doc->createElement($tagname);
$el = $this->setAttributes(
$el,
$locAttributes
);
if($type === self::ELEMENT_SELECT) {
foreach($selectOptions as $value => $textContent) {
$opt = $doc->createElement('option');
$textEl = $doc->createTextNode($textContent);
$opt->appendChild($textEl);
$opt->setAttribute('value',strip_tags($value));
$el->appendChild($opt);
}
}
$el = new FormElement($el,$labelText);//set in wrapper
$this->form->addElement($el, $parentElementID, $labelText);
} elseif($type === self::ELEMENT_TEXTNODE) {
$el = $doc->createTextNode($labelText);
$this->form->setElementTextNodeByID($el,$parentElementID);
}
return $el;
}
/**
* Set attributes for el
* @param \DOMElement $el
* @param array $attributes
* @return \DOMElement
*/
protected function setAttributes(\DOMElement $el, array $attributes)
{
foreach ($attributes as $name => $val)
{
//strip_tags to make sure
$attr = new \DOMAttr($name, strip_tags($val));
$el->setAttributeNode($attr);
if($name === 'id') {
$el->setIdAttribute('id',false);
}
}
return $el;
}
/**
* @param $id
* @return bool
*/
public function removeFieldByID($id) {
return $this->form->removeElementByID($id);
}
/**
* @param $fieldName
* @param $rule
*/
public function setFieldRule($fieldName, $rule ) {
$this->form->setFieldRule($fieldName,$rule);
}
/**
* @param array $rulesArr
*/
public function setFieldRulesWithRuleString(array $rulesArr ) {
$this->form->setFieldRules($rulesArr);
}
/**
* @return array
*/
public function getFieldRules() {
return $this->form->getFieldRules();
}
/**
* @param array $arr
* @param $key
* @return array
*/
public function encodeArrayForHTTP(array $arr , $key ) {
// $encryption = new Encryption(self::FORMBUILDER_ENCRYPTION_ALGORITHM, MCRYPT_MODE_CBC);
$arrStr = serialize($arr);
$arrLen = strlen($arrStr);
//$BF = new ctBlowfish();
//$encoded = $BF->ctEncrypt($arrStr,$arrLen,$key);
$encoded = urlencode(base64_encode($encryption->encrypt($arrStr,$key)));
return array('encodedData' => $encoded,'length' => $arrLen);
}
/**
* @param $str
* @param $len
* @param $key
* @return mixed
*/
public function decodeArrayString($str, $len, $key ) {
//$BF = new ctBlowfish();
//$decoded = $BF->ctDecrypt($str,(int)$len,$key);
// $encryption = new Encryption(self::FORMBUILDER_ENCRYPTION_ALGORITHM, MCRYPT_MODE_CBC);
$decoded = $encryption->decrypt(base64_decode(urldecode($str)),$key);
$arr = unserialize($decoded);
return $arr;
}
/**
* @param null $metaDataEncryptionKey
* @return $this
*/
public function render($metaDataEncryptionKey = null) {
$this->form->removeMetaDataFields();
if($metaDataEncryptionKey) {
$rulesArray = $this->form->getFieldRules();
$formMetaDataArray = array(
'fields' => $this->form->getFieldNames(),
'rules' => $rulesArray,
'serializedFormObj' => serialize(clone $this->form)
);
$metaDataEncodingArr = $this->encodeArrayForHTTP($formMetaDataArray, $metaDataEncryptionKey);
$metaDataEncoded = $metaDataEncodingArr['encodedData'];
$metaDataLength = $metaDataEncodingArr['length'];
$fieldNameData = 'fmd_' . $this->id;
$fieldNameLen = 'fmdl_' . $this->id;
$this->addField(self::ELEMENT_HIDDEN,array('id' => $fieldNameData, 'name' => $fieldNameData, 'value' => $metaDataEncoded));
$this->addField(self::ELEMENT_HIDDEN,array('id' => $fieldNameLen, 'name' => $fieldNameLen, 'value' => $metaDataLength));
}
if(!$this->form->isFormRendered()) {
$this->form->render();
$this->isRendered = true;
}
return $this;
}
public function getRenderedString() {
if (!$this->isRendered) {
throw new \BadMethodCallException("'getRenderedString' can only be called after 'render' has been called");
}
return $this->form->getRenderedContent();
}
/**
* @param $metaDataEncryptionKey
* @param string $postGetRequest
* @return array
*/
public function getFormsFromRequest($metaDataEncryptionKey, $postGetRequest = 'request') {
if(!(mb_strlen($metaDataEncryptionKey,'UTF-8') > 0)) {
throw new \InvalidArgumentException(
'Parameter metaDataEncryptionKey must not be empty.'
);
}
$sourceArrRef = &$_REQUEST;
$targetArrRef = &$this->processedRequestForms;
if(strcasecmp('post',$postGetRequest) === 0) {
$sourceArrRef = &$_POST;
$targetArrRef = &$this->processedPostForms;
} elseif (strcasecmp('get',$postGetRequest) === 0) {
$sourceArrRef = &$_GET;
$targetArrRef = &$this->processedGetForms;
}
$forms = array();
$formData = array();
$arrKeys = array_keys($sourceArrRef);
foreach($arrKeys as $key) {
$fid = '';
$fmd = '';
$fmdl = 0;
if(Validator::strStartsWith($key,'fmd_')) {
$fid = explode('_',$key,2)[1];
$fmd = $sourceArrRef[$key];
$currSourceArrIndex = 'fmdl_' . $fid;
$fmdl = (isset($sourceArrRef[$currSourceArrIndex]) ? (int)$sourceArrRef[$currSourceArrIndex]:0);
if($fid !== '' && $fmd !== '' && $fmdl !== 0) {
$formData[] = array('id' => $fid, 'encryptedData' => $fmd, 'length' => $fmdl);
}
}
}
foreach($formData as $formDataArr) {
$arr = $this->decodeArrayString($formDataArr['encryptedData'],$formDataArr['length'],$metaDataEncryptionKey);
if(isset($arr['serializedFormObj'])) {
try{
$locForm = unserialize($arr['serializedFormObj']);
$locForm->validateRequestAgainstRules();
$forms[] = $locForm;
}catch(\Exception $e) {
//Do nothing
}
}
}
$targetArrRef = $forms;
return $forms;
}
/**
* @param string|null $id
* @param string|null $class
* @param string|null $parentId
* @param string|null $text
* @param array $additionalOptions
* @return \DOMElement|FormElement
*/
public function addDIV($id = null, $class = null, $parentId = null, $text = null, array $additionalOptions = array()) {
if(null !== $id) {
$additionalOptions['id'] = (string)$id;
}
if(null !== $class) {
$additionalOptions['class'] = (string)$class;
}
$el = $this->addField(self::ELEMENT_DIV,$additionalOptions,$parentId);
$domEl = $el->getEl();
$text = strip_tags($text);
if(mb_strlen($text) > 0) {
$textNode = $domEl->ownerDocument->createTextNode($text);
$domEl->appendChild($textNode);
}
return $el;
}
/**
* @param null $id
* @param null $class
* @param string $href
* @param null $parentId
* @param null $text
* @param array $additionalOptions
* @return \DOMElement|FormElement
*/
public function addAnchor($id = null, $class = null, $href = '', $parentId = null, $text = null, array $additionalOptions = array()) {
if(null !== $id) {
$additionalOptions['id'] = (string)$id;
}
if(null !== $class) {
$additionalOptions['class'] = (string)$class;
}
$additionalOptions['href'] = filter_var($href,FILTER_SANITIZE_URL);
$el = $this->addField(self::ELEMENT_ANCHOR,$additionalOptions,$parentId);
$domEl = $el->getEl();
$text = strip_tags($text);
if(mb_strlen($text) > 0) {
$textNode = $domEl->ownerDocument->createTextNode($text);
$domEl->appendChild($textNode);
}
return $el;
}
/**
* @param null $id
* @param null $class
* @param null $parentId
* @param string $text
* @param array $additionalOptions
* @return \DOMElement|FormElement
* @throws \InvalidArgumentException
*/
public function addSpan($id = null, $class = null, $parentId = null, $text = null, array $additionalOptions = array()) {
if(null !== $id) {
$additionalOptions['id'] = (string)$id;
}
if(null !== $class) {
$additionalOptions['class'] = (string)$class;
}
$el = $this->addField(self::ELEMENT_SPAN,$additionalOptions,$parentId);
$domEl = $el->getEl();
$text = strip_tags($text);
if(mb_strlen($text) > 0) {
$textNode = $domEl->ownerDocument->createTextNode($text);
$domEl->appendChild($textNode);
}
return $el;
}
/**
* @param $name
* @param null $id
* @param null $class
* @param null $parentId
* @param null $value
* @param null $labelText
* @param array $additionalOptions
* @return \DOMElement|FormElement
*/
public function addTextInput($name, $id = null, $class = null, $parentId = null, $value = null, $labelText = null, array $additionalOptions = array()) {
if(mb_strlen($name) > 0) {
$additionalOptions['name'] = $name;
}
if(null !== $id) {
$additionalOptions['id'] = (string)$id;
}
if(null !== $class) {
$additionalOptions['class'] = (string)$class;
}
if(null !== $value) {
$additionalOptions['value'] = (string)$value;
}
$text = htmlentities(strip_tags($value), ENT_QUOTES, 'UTF-8');
if(mb_strlen($text) > 0) {
$additionalOptions['value'] = $text;
}
$el = $this->addField(self::ELEMENT_TEXT,$additionalOptions,$parentId,$labelText);
return $el;
}
/**
* @param $name
* @param null $id
* @param null $class
* @param null $parentId
* @param null $value
* @param null $labelText
* @param array $additionalOptions
* @return \DOMElement|FormElement
*/
public function addTextArea($name, $id = null, $class = null, $parentId = null, $value = null, $labelText = null, array $additionalOptions = array()) {
if(mb_strlen($name) > 0) {
$additionalOptions['name'] = $name;
}
if(null !== $id) {
$additionalOptions['id'] = (string)$id;
}
if(null !== $class) {
$additionalOptions['class'] = (string)$class;
}
$text = htmlentities(strip_tags($labelText), ENT_QUOTES, 'UTF-8');
if(mb_strlen($text) > 0) {
$additionalOptions['value'] = $text;
}
$el = $this->addField(self::ELEMENT_TEXTAREA,$additionalOptions,$parentId,$labelText);
return $el;
}
/**
* @param $name
* @param null $value
* @param array $additionalOptions
* @return \DOMElement|FormElement
*/
public function addHidden($name, $value = null, array $additionalOptions = array()) {
if(mb_strlen($name) > 0) {
$additionalOptions['name'] = $name;
}
$text = strip_tags($value);
if(mb_strlen($text) > 0) {
$additionalOptions['value'] = $text;
}
$el = $this->addField(self::ELEMENT_HIDDEN,$additionalOptions);
return $el;
}
/**
* @param $name
* @param null $id
* @param null $class
* @param null $parentId
* @param null $value
* @param null $labelText
* @param array $additionalOptions
* @return \DOMElement|FormElement
*/
public function addNumberInput($name, $id = null, $class = null, $parentId = null, $value = null, $labelText = null, array $additionalOptions = array()) {
if(mb_strlen($name) > 0) {
$additionalOptions['name'] = $name;
}
if(null !== $id) {
$additionalOptions['id'] = (string)$id;
}
if(null !== $class) {
$additionalOptions['class'] = (string)$class;
}
$text = htmlentities(strip_tags($value), ENT_QUOTES, 'UTF-8');
if(mb_strlen($text) > 0) {
$additionalOptions['value'] = $value;
}
$el = $this->addField(self::ELEMENT_NUMBER,$additionalOptions,$parentId,$labelText);
return $el;
}
/**
* @param $name
* @param null $id
* @param null $class
* @param null $parentId
* @param null $value
* @param null $labelText
* @param array $additionalOptions
* @return \DOMElement|FormElement
*/
public function addDateInput($name, $id = null, $class = null, $parentId = null, $value = null, $labelText = null, array $additionalOptions = array()) {
if(mb_strlen($name) > 0) {
$additionalOptions['name'] = $name;
}
if(null !== $id) {
$additionalOptions['id'] = (string)$id;
}
if(null !== $class) {
$additionalOptions['class'] = (string)$class;
}
$text = htmlentities(strip_tags($labelText), ENT_QUOTES, 'UTF-8');
if(mb_strlen($text) > 0) {
$additionalOptions['value'] = $text;
}
$el = $this->addField(self::ELEMENT_DATE,$additionalOptions,$parentId,$labelText);
return $el;
}
/**
* @param $name
* @param null $id
* @param null $class
* @param null $parentId
* @param null $preselectVal
* @param null $labelText
* @param array $selectOptions
* @param array $additionalOptions
* @return \DOMElement|FormElement
*/
public function addSelect($name, $id = null, $class = null, $parentId = null, $preselectVal = null, $labelText = null, array $selectOptions = array(), array $additionalOptions = array()) {
if(mb_strlen($name) > 0) {
$additionalOptions['name'] = $name;
}
if(null !== $id) {
$additionalOptions['id'] = (string)$id;
}
if(null !== $class) {
$additionalOptions['class'] = (string)$class;
}
$el = $this->addField(self::ELEMENT_SELECT,$additionalOptions,$parentId,$labelText,$selectOptions);
if(null !== $preselectVal) {
$this->form->setSelectedOptionByValue($el->getEl(), $preselectVal);
}
return $el;
}
/**
* @param $name
* @param null $id
* @param null $class
* @param null $parentId
* @param null $value
* @param bool $isChecked
* @param null $labelText
* @param array $additionalOptions
* @return \DOMElement|FormElement
*/
public function addRadioInput($name, $id = null, $class = null, $parentId = null, $value = null, $isChecked = false, $labelText = null, array $additionalOptions = array()) {
if(mb_strlen($name) > 0) {
$additionalOptions['name'] = $name;
}
if(null !== $id) {
$additionalOptions['id'] = (string)$id;
}
if(null !== $class) {
$additionalOptions['class'] = (string)$class;
}
$text = htmlentities(strip_tags($labelText), ENT_QUOTES, 'UTF-8');
if(mb_strlen($text) > 0) {
$additionalOptions['value'] = $text;
}
if($isChecked) {
$additionalOptions['checked'] = 'checked';
}
$el = $this->addField(self::ELEMENT_RADIO,$additionalOptions,$parentId,$labelText);
return $el;
}
/**
* @param $name
* @param null $id
* @param null $class
* @param null $parentId
* @param null $value
* @param bool $isChecked
* @param array|null $labelText
* @param array $additionalOptions
* @return \DOMElement|FormElement
*/
public function addCheckboxInput($name, $id = null, $class = null, $parentId = null, $value = null, $isChecked = false, array $labelText = null, array $additionalOptions = array()) {
if(mb_strlen($name) > 0) {
$additionalOptions['name'] = $name;
}
if(null !== $id) {
$additionalOptions['id'] = (string)$id;
}
if(null !== $class) {
$additionalOptions['class'] = (string)$class;
}
$text = htmlentities(strip_tags($labelText), ENT_QUOTES, 'UTF-8');
if(mb_strlen($text) > 0) {
$additionalOptions['value'] = $text;
}
if($isChecked) {
$additionalOptions['checked'] = 'checked';
}
$el = $this->addField(self::ELEMENT_CHECKBOX,$additionalOptions,$parentId,$labelText);
return $el;
}
/**
* @param $name
* @param null $id
* @param null $class
* @param null $parentId
* @param null $value
* @param null $labelText
* @param array $additionalOptions
* @return \DOMElement|FormElement
*/
public function addEmailInput($name, $id = null, $class = null, $parentId = null, $value = null, $labelText = null, array $additionalOptions = array()) {
if(mb_strlen($name) > 0) {
$additionalOptions['name'] = $name;
}
if(null !== $id) {
$additionalOptions['id'] = (string)$id;
}
if(null !== $class) {
$additionalOptions['class'] = (string)$class;
}
$text = htmlentities(strip_tags($labelText), ENT_QUOTES, 'UTF-8');
if(mb_strlen($text) > 0) {
$additionalOptions['value'] = $text;
}
$el = $this->addField(self::ELEMENT_EMAIL,$additionalOptions,$parentId,$labelText);
return $el;
}
/**
* @param $name
* @param null $id
* @param null $class
* @param null $parentId
* @param null $value
* @param null $labelText
* @param array $additionalOptions
* @return \DOMElement|FormElement
*/
public function addTelInput($name, $id = null, $class = null, $parentId = null, $value = null, $labelText = null, array $additionalOptions = array()) {
if(mb_strlen($name) > 0) {
$additionalOptions['name'] = $name;
}
if(null !== $id) {
$additionalOptions['id'] = (string)$id;
}
if(null !== $class) {
$additionalOptions['class'] = (string)$class;
}
$text = htmlentities(strip_tags($labelText), ENT_QUOTES, 'UTF-8');
if(mb_strlen($text) > 0) {
$additionalOptions['value'] = $text;
}
$el = $this->addField(self::ELEMENT_TEL,$additionalOptions,$parentId,$labelText);
return $el;
}
public function validatePrefillAndAddErrors() {
$this->form->validatePrefillAndAddErrors();
}
/**
* @return Form
*/
public function getForm() {
return $this->form;
}
/**
* @return \DOMDocument
*/
public function getDOM() {
return $this->form->getDOMDocument();
}
/**
* @return \DOMElement
*/
public function getMainDOMNode() {
return $this->form->getEl();
}
public function prefillFromSuperglobal() {
$this->form->doPrefillFromSuperglobal();
}
/**
* @param array $arr
*/
public function prefillFromArray(array &$arr) {
$this->form->doPrefillFromArray($arr);
}
/**
* @param ViewModel $viewModel
* @param array $fieldInputMappings
*/
public function registerViewModel(ViewModel $viewModel, array $fieldInputMappings) {
$this->form->registerViewModel($viewModel,$fieldInputMappings);
}
/**
* @param ViewModel $viewModel
*/
public function prefillFromViewModel(ViewModel $viewModel) {
$this->form->doPrefillFromViewModel($viewModel);
}
/**
* @param $key
* @param $value
*/
public function addData($key, $value) {
$fieldNames = $this->form->getFieldNames();
if(in_array($key,$fieldNames,false)) {
throw new \InvalidArgumentException(
"Cannot set data. There is already an input with the name " . strip_tags($key) . "."
);
}
$this->addHidden($key, $value);
}
/**
* @param array $arr
*/
public function addDataArray(array $arr) {
foreach($arr as $key => $value) {
$this->addData($key,$value);
}
}
/**
* @param $id
* @param $classname
* @param $text
* @param $parentId
* @return \DOMElement|FormElement
*/
public function addSubmitButton($id, $classname, $text, $parentId)
{
$el = $this->addField(self::ELEMENT_SUBMIT,['value' => $text],$parentId,null);
return $el;
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/13/2015
* Time: 12:52 AM
*/
class FormElement {
/**
* @var \DOMElement
*/
protected $el;
protected $validationRuleNames;
protected $label;
/**
* @param \DOMElement $el
* @param null $label
*/
public function __construct( \DOMElement $el, $label = null ) {
$this->el = $el;
if(null !== $label) {
$this->label = strip_tags($label);
}
}
/**
* @param $ruleName
*/
public function addValidationRuleByName($ruleName ) {
if(!Validator::isValidDefaultInlineRuleName($ruleName)) {
throw new \InvalidArgumentException("'$ruleName' is not valid name of a validation-rule");
}
$this->validationRuleNames[$ruleName] = $ruleName;
}
/**
* @return \DOMElement
*/
public function getEl() {
return $this->el;
}
/**
* @param $val
*/
public function setValue($val ) {
$this->el->setAttribute('value',strip_tags($val));
}
}

View File

@@ -0,0 +1,263 @@
<?php
namespace DynCom\mysyde\common\classes;
use Monolog\Formatter\HtmlFormatter;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\SwiftMailerHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 06.05.2016
* Time: 10:42
*/
class GeneralErrorExceptionHandling
{
const DEFAULT_ERROR_LOG_PATH = '/logs/unhandled_errors.log';
const DEFAULT_ERROR_LOGGER_NAME = 'UnhandledErrorLogging';
const DEFAULT_EXCEPTION_LOG_PATH = '/logs/unhandled_exceptions.log';
const DEFAULT_EXCEPTION_LOGGER_NAME = 'UnhandledExceptionLogging';
const DEFAULT_ERROR_MAIL_SENDER_ADDR = 'error@projectname.dc-solution';
const DEFAULT_ERROR_MAIL_SUBJECT = 'Unhandled Error in project projectname';
const DEFAULT_EXCEPTION_MAIL_SENDER_ADDR = 'exception@projectname.dc-solution';
const DEFAULT_EXCEPTION_MAIL_SUBJECT = 'Unhandled Exception in project projectname';
const DEFAULT_ERROR_EXCEPTION_MAIL_RECIPIENT_ADDRESS = '';
const DEFAULT_ERROR_EXCEPTION_MAIL_RECIPIENT_NAME = '';
private static $isSetAsErrorHandler;
private static $isSetAsExceptionHandler;
private static $redirectErrorPath;
private static $redirectErrorMsg;
private static $redirectExceptionPath;
private static $redirectExceptionMsg;
/**
* @var \Psr\Log\LoggerInterface
*/
private static $defaultErrorLogger;
/**
* @var \Psr\Log\LoggerInterface
*/
private static $defaultExceptionLogger;
/**
* @return LoggerInterface
*/
public static function getDefaultErrorLogger()
{
if (self::$defaultErrorLogger === null) {
$baseDir = dirname(dirname(dirname(__DIR__)));
$loggerPath = rtrim($baseDir,'/') . self::DEFAULT_ERROR_LOG_PATH;
if (empty($_SERVER['DOCUMENT_ROOT'])) { //Output only on CLI
//echo "Class " . __CLASS__ . " logging errors to path [$loggerPath]" . PHP_EOL;
}
self::$defaultErrorLogger = self::createDefaultLogger($loggerPath, self::DEFAULT_ERROR_LOGGER_NAME,self::DEFAULT_ERROR_MAIL_SUBJECT,self::DEFAULT_ERROR_MAIL_SENDER_ADDR);
}
return self::$defaultErrorLogger;
}
/**
* @return Logger|LoggerInterface
*/
public static function getDefaultExceptionLogger()
{
if (self::$defaultExceptionLogger === null) {
$baseDir = dirname(dirname(dirname(__DIR__)));
$loggerPath = rtrim($baseDir,'/') . self::DEFAULT_EXCEPTION_LOG_PATH;
if (empty($_SERVER['DOCUMENT_ROOT'])) { //Output only on CLI
//echo "Class " . __CLASS__ . " logging exceptions to path [$loggerPath]" . PHP_EOL;
}
self::$defaultExceptionLogger = self::createDefaultLogger($loggerPath, self::DEFAULT_EXCEPTION_LOGGER_NAME,self::DEFAULT_EXCEPTION_MAIL_SUBJECT,self::DEFAULT_EXCEPTION_MAIL_SENDER_ADDR);
}
return self::$defaultExceptionLogger;
}
/**
* @param $logFilePath
* @param $loggerName
* @param $mailSubject
* @param $mailFromAddr
* @return \Monolog\Logger
*/
private static function createDefaultLogger($logFilePath,$loggerName,$mailSubject,$mailFromAddr)
{
$handlers = [];
$rotatingFileHandler = new RotatingFileHandler($logFilePath, 10);
$formatter = new LineFormatter(null, null, false, true);
$rotatingFileHandler->setFormatter($formatter);
$handlers[] = $rotatingFileHandler;
$mailRecipientAddr = self::DEFAULT_ERROR_EXCEPTION_MAIL_RECIPIENT_ADDRESS;
if ($mailRecipientAddr !== '' && filter_var($mailRecipientAddr,FILTER_VALIDATE_EMAIL)) {
$handlers[] = self::getDefaultMailHandler($mailSubject,$mailFromAddr,self::DEFAULT_ERROR_EXCEPTION_MAIL_RECIPIENT_ADDRESS,self::DEFAULT_ERROR_EXCEPTION_MAIL_RECIPIENT_NAME);
}
$logger = new Logger($loggerName,$handlers);
return $logger;
}
/**
* @param $subject
* @param $fromAddr
* @param $toAddr
* @param $toName
* @return SwiftMailerHandler
*/
private static function getDefaultMailHandler($subject, $fromAddr, $toAddr, $toName)
{
$smtpTransporter = \Swift_SmtpTransport::newInstance();
$mailer = \Swift_Mailer::newInstance($smtpTransporter);
$msg = \Swift_Message::newInstance($subject);
$msg->addFrom($fromAddr);
$msg->addTo($toAddr, $toName);
$mailFormatter = new HtmlFormatter();
$mailHandler = new SwiftMailerHandler($mailer, $msg);
$mailHandler->setFormatter($mailFormatter);
return $mailHandler;
}
/**
* @param $exception
*/
public static function handleException($exception)
{
$logger = self::getDefaultExceptionLogger();
$msg = 'An unhandled exception occurred! ' . PHP_EOL .
" Errno: {$exception->getCode()}" . PHP_EOL .
" Msg: {$exception->getMessage()}" . PHP_EOL;
$fileName = $exception->getFile();
if ($fileName !== '') {
$msg .= " File: $fileName " . PHP_EOL;
}
$lineNo = $exception->getLine();
if ($lineNo !== 0) {
$msg .= " Line: $lineNo" . PHP_EOL;
}
$traceString = str_replace("\n",PHP_EOL,$exception->getTraceAsString());
if ($traceString !== '') {
$msg .= " Trace: $traceString" . PHP_EOL;
}
$msg .= PHP_EOL;
$logger->addError($msg);
self::doConditionalRedirect(self::$redirectExceptionPath,self::$redirectExceptionMsg);
}
/**
* @param $errno
* @param $errstr
* @param string $errfileName
* @param null $errLine
* @param array|null $errContext
*/
public static function handleError($errno, $errstr, $errfileName = '', $errLine = null, array $errContext = null)
{
$logger = self::getDefaultErrorLogger();
$msg = 'An error occurred!' . PHP_EOL .
" Errno: $errno" . PHP_EOL .
" Msg: $errstr" . PHP_EOL;
if ($errfileName !== '') {
$msg .= " File: $errfileName" . PHP_EOL;
}
if ($errLine !== null) {
$msg .= " Line: $errLine" . PHP_EOL;
}
if ($errContext !== null && count($errContext) > 0) {
$msg .= ' Context Variables: ' . print_r($errContext,1) . PHP_EOL;
}
$msg .= PHP_EOL;
$logger->addError($msg);
self::doConditionalRedirect(self::$redirectErrorPath,self::$redirectErrorMsg);
}
/**
* @param string $redirectToPagePath
* @param string $redirectWithMessage
*/
public static function setExceptionHandler($redirectToPagePath = '', $redirectWithMessage = '')
{
if (!self::$isSetAsExceptionHandler) {
self::$redirectExceptionPath = $redirectToPagePath;
self::$redirectExceptionMsg = $redirectWithMessage;
$callable = array(__CLASS__,'handleException');
set_exception_handler($callable);
}
}
/**
* @param string $redirectToPagePath
* @param string $redirectWithMessage
*/
public static function setErrorHandler($redirectToPagePath = '', $redirectWithMessage = '')
{
if (!self::$isSetAsErrorHandler) {
self::$redirectErrorPath = $redirectToPagePath;
self::$redirectErrorMsg = $redirectWithMessage;
$callable = array(__CLASS__,'handleError');
set_error_handler($callable,self::getErrorHandlingLevel());
}
}
/**
* @return int
*/
private static function getErrorHandlingLevel()
{
return E_ALL^E_NOTICE^E_STRICT^E_WARNING;
}
/**
* @param string $path
* @param string $msg
*/
private static function doConditionalRedirect($path = '', $msg = '')
{
if ($path !== '' && !self::isPathCurrentUrl($path)) {
self::saveErrorFlashMessageToSession($msg);
universal_redirect($path);
}
}
/**
* @param string $msg
*/
private static function saveErrorFlashMessageToSession($msg = '')
{
static $i = null;
if ($msg !== '') {
$errorMsgs = isset($_SESSION['msgBag']['errors']) ? $_SESSION['msgBag']['errors'] : [];
if (!in_array($msg,$errorMsgs,true)) {
$errorMsgs[] = $msg;
}
$_SESSION['msgBag']['errors'] = $errorMsgs;
}
}
/**
* @param string $path
* @return bool
*/
private static function isPathCurrentUrl($path = '')
{
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$domainName = $_SERVER['HTTP_HOST'];
$request = $_SERVER['REQUEST_URI'];
$currPath = $protocol.$domainName.$request;
return $path === $currPath;
}
}

View File

@@ -0,0 +1,238 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\CRUDObjectStorage;
use DynCom\mysyde\common\interfaces\Entity;
use DynCom\mysyde\common\interfaces\Observer;
use DynCom\mysyde\common\interfaces\UnitOfWorkInterface;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 08.07.2015
* Time: 13:59
*/
class GenericCRUDObjectStorageUnitOfWork implements UnitOfWorkInterface,Observer
{
const ENTITY_STATE_NEW = 'ENTITY_STATE_NEW';
const ENTITY_STATE_CLEAN = 'ENTITY_STATE_CLEAN';
const ENTITY_STATE_DIRTY = 'ENTITY_STATE_DIRTY';
const ENTITY_STATE_REMOVED = 'ENTITY_STATE_REMOVED';
const EVENT_SUBSTR_MODEL_CHANGED = '.changed';
protected $storage;
protected $newEntities;
protected $cleanEntities;
protected $cleanEntitiesInit;
protected $dirtyEntities;
protected $removedEntities;
/**
* GenericCRUDObjectStorageUnitOfWork constructor.
* @param CRUDObjectStorage $storage
*/
public function __construct(CRUDObjectStorage $storage) {
$this->storage = $storage;
}
/**
* @param $eventName
* @param $data
*/
public function notify($eventName, $data) {
$className = get_class($data);
if(!$className || !($data instanceof Entity)) return;
$id = $data->getID();
$this->checkEventForChangedClean($eventName,$className,$id);
}
/**
* @param $eventName
* @param $className
* @param $id
*/
protected function checkEventForChangedClean($eventName, $className, $id) {
if(array_key_exists($className,$this->cleanEntities) && array_key_exists($id,$this->cleanEntities[$className]) && false !== stripos($eventName,self::EVENT_SUBSTR_MODEL_CHANGED)) {
if(isset($this->cleanEntities[$className][$id])) {
$entity = $this->cleanEntities[$className][$id];
$this->dirtyEntities[$className][$id] = $entity;
unset($this->cleanEntities[$className][$id]);
}
}
}
/**
* @param Entity $entity
*/
public function registerNew(Entity $entity) {
$className = get_class($entity);
$id = $entity->getID();
if((int)$id > 0) {
throw new \BadMethodCallException(
"Entity must not have an ID > 0 to be registered as new."
);
}
$objHash = spl_object_hash($entity);
$this->newEntities[$className][$objHash] = &$entity;
}
/**
* @param Entity $entity
*/
public function registerClean(Entity $entity) {
$className = get_class($entity);
$id = $entity->getID();
if(!(int)$id > 0) {
throw new \BadMethodCallException(
"Entity needs a not-null id to be registered as clean."
);
}
if(
(array_key_exists($className,$this->dirtyEntities) && array_key_exists($id,$this->dirtyEntities[$className]))
|| (array_key_exists($className,$this->removedEntities) && array_key_exists($id,$this->removedEntities[$className]))) {
throw new \BadMethodCallException(
"Entity must not already be registered as dirty or removed to be registered as Clean"
);
}
$this->cleanEntitiesInit[$className][$id] = clone $entity;
$this->cleanEntities[$className][$id] = &$entity;
}
/**
* @param Entity $entity
*/
public function registerDirty(Entity $entity) {
$className = get_class($entity);
$id = $entity->getID();
if(!(int)$id > 0) {
throw new \BadMethodCallException(
"Entity needs a not-null id to be registered as dirty."
);
}
unset($this->cleanEntities[$className][$id],$this->removedEntities[$className][$id]);
$this->dirtyEntities[$className][$id] = &$entity;
}
/**
* @param Entity $entity
*/
public function registerRemoved(Entity $entity) {
$className = get_class($entity);
$id = $entity->getID();
if(!(int)$id > 0) {
throw new \BadMethodCallException(
"Entity needs a not-null id to be registered as removed."
);
}
unset($this->cleanEntities[$className][$id],$this->dirtyEntities[$className][$id]);
$this->removedEntities[$className][$id] = &$entity;
}
/**
* @param Entity $entity
* @param $state
*/
public function registerEntity(Entity $entity, $state) {
switch($state) {
case self::ENTITY_STATE_NEW:
$this->registerNew($entity);
return;
case self::ENTITY_STATE_CLEAN:
$this->registerClean($entity);
return;
case self::ENTITY_STATE_DIRTY:
$this->registerDirty($entity);
return;
case self::ENTITY_STATE_REMOVED:
$this->registerRemoved($entity);
return;
default: break;
}
throw new \InvalidArgumentException(
"State must be one of ENTITY_STATE_NEW, ENTITY_STATE_CLEAN, ENTITY_STATE_DIRTY, ENTITY_STATE_REMOVED."
);
}
/**
* @param Entity $entity
*/
public function unregisterEntity(Entity $entity) {
$className = get_class($entity);
$id = $entity->getID();
$objHash = spl_object_hash($entity);
unset(
$this->newEntities[$className][$objHash],
$this->cleanEntities[$className][$id],
$this->dirtyEntities[$className][$id],
$this->removedEntities[$className][$id]
);
}
public function rollback() {
//Look for entities in dirty / removed that had initially
//been registered as clean and then moved to dirty / removed through changes.
//Reset such entities to their initial state cloned on registration
foreach($this->dirtyEntities as $className => &$entityArr) {
foreach($entityArr as $id => $obj) {
if(array_key_exists($id,$this->cleanEntitiesInit[$className])) {
$oldState = $this->cleanEntitiesInit[$className][$id];
//Initially stored by reference,
//So this resets the referenced entity to init state
//And then deletes the reference in the array
$obj = $entityArr[$id];
$obj = $oldState;
unset($entityArr[$id]);
$this->cleanEntities[$className][$id] = $obj;
}
}
}
unset($entityArr);
foreach($this->removedEntities as $className => &$entityArr2) {
foreach($entityArr2 as $id => $obj) {
if(array_key_exists($id,$this->cleanEntitiesInit[$className])) {
$oldState = $this->cleanEntitiesInit[$className][$id];
//Initially stored by reference,
//So this resets the referenced entity to init state
//And then deletes the reference in the array
$obj = $entityArr2[$id];
$obj = $oldState;
unset($entityArr2[$id]);
$this->cleanEntities[$className][$id] = $obj;
}
}
}
unset($entityArr2);
}
public function clear() {
$this->newEntities = [];
$this->cleanEntitiesInit = [];
$this->cleanEntities = [];
$this->dirtyEntities = [];
$this->removedEntities = [];
}
public function commit() {
foreach($this->newEntities as $className => $objArr) {
foreach($objArr as $entity) {
$this->storage->create($entity);
}
}
foreach($this->dirtyEntities as $className => $objArr) {
foreach($objArr as $id => $entity) {
$this->storage->update($entity);
}
}
foreach($this->removedEntities as $className => $objArr) {
foreach($objArr as $id => $entity) {
$this->storage->delete($entity);
}
}
}
}

View File

@@ -0,0 +1,122 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\DOMRepositoryListView;
use DynCom\mysyde\common\interfaces\DOMTemplate;
use DynCom\mysyde\common\interfaces\Repository;
use DynCom\mysyde\common\traits\genericRepositoryListViewTrait;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 25.07.2015
* Time: 11:15
*/
class GenericDOMRepositoryListView implements DOMRepositoryListView
{
use genericRepositoryListViewTrait;
protected $DOMTemplate;
protected $DOMDocument;
protected $repository;
protected $transformer;
protected $prefix;
protected $renderedContent = false;
/**
* GenericDOMRepositoryListView constructor.
* @param DOMTemplate $listElementTemplate
* @param Repository $repository
* @param RenderableStringTransformer $transformer
*/
public function __construct(DOMTemplate $listElementTemplate, Repository $repository, RenderableStringTransformer $transformer) {
$domImpl = new \DOMImplementation();
$this->DOMDocument = $domImpl->createDocument(null, 'html',
$domImpl->createDocumentType("html",
"-//W3C//DTD XHTML 1.0 Transitional//EN",
"/mysyde/common/xhtml11.dtd"));
$this->DOMDocument->formatOutput = true;
$this->DOMTemplate = $this->DOMDocument->importNode($listElementTemplate->getDOMDocument()->documentElement, true);
$this->repository = $repository;
$this->transformer = $transformer;
$this->prefix = $listElementTemplate->getInserterTokenPrefix();
$this->lowestWritableDir = '/htdocs';
$this->enforceLowestWriteLevelLimit = true;
$this->classOrSelfReferencePath = 'self';
$this->canSidestep = false;
}
/**
* @param array $criteria
* @param int $offset
* @param int $limit
* @return bool|string
*/
public function render(array $criteria, $offset = 0, $limit = 0) {
if($this->renderedContent) {
return $this->renderedContent;
}
$doc = $this->DOMDocument;
$XPath = new \DOMXPath($doc);
$query = "//@*[starts-with(name(),'{$this->prefix}')]";
$nodeList = $XPath->query($query);
$nodeArr = [];
$len = $nodeList->length;
for($i = 0;$i < $len;++$i) {
$node = $nodeList->item($i);
$attrName = $node->nodeName;
$fieldName = str_replace($this->prefix,'',$attrName);
$owner = &$node->ownerElement;
$owner->removeAttribute($attrName);
$nodeArr[$fieldName] = &$owner;
}
$collection = $this->repository->findByCriteria($criteria,$offset,$limit);
$renderedString = '';
foreach($collection as $listElement) {
$tmpTemplate = clone $this->DOMTemplate;
$tmpDoc = $tmpTemplate->ownerDocument;
$XPath = new \DOMXPath($tmpDoc);
$nodeList = $XPath->query($query);
$nodeArr = [];
$len = $nodeList->length;
for($i = 0;$i < $len;++$i) {
$node = $nodeList->item($i);
$attrName = $node->nodeName;
$fieldName = str_replace($this->prefix,'',$attrName);
$owner = &$node->ownerElement;
$owner->removeAttribute($attrName);
$nodeArr[$fieldName] = &$owner;
}
$fieldNames = array_keys($nodeArr);
foreach($fieldNames as $fieldName) {
if(property_exists($listElement,$fieldName)) {
$node = $nodeArr[$fieldName];
$stringVal = $this->transformer->toString($listElement->$fieldName);
$isXML = (strip_tags($stringVal) !== $stringVal);
if($isXML) {
$tmpDoc = clone $doc;
//LoadHTML is needed to correctly format HTML on loading
@$tmpDoc->loadHTML($stringVal);
//loadHTML creates html and body tags around stringVal, so content is first child of first child
$el = $doc->importNode($tmpDoc->documentElement->firstChild->firstChild,true);
} else {
$el = $doc->createTextNode($stringVal);
}
$node->appendChild($el);
}
}
$renderedString .= $tmpDoc->saveHTML();
}
$this->renderedContent = $renderedString;
return $this->renderedContent;
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\DOMTemplate;
use DynCom\mysyde\common\interfaces\DOMView;
use DynCom\mysyde\common\interfaces\ViewModel;
use DynCom\mysyde\common\traits\genericViewTrait;
/**
* Created by PhpStorm.
* User: Michael Bauer
* Date: 7/14/2015
* Time: 12:11 AM
*/
class GenericDOMView implements DOMView
{
use genericViewTrait;
protected $DOMTemplate;
protected $DOMDocument;
protected $viewModelData;
protected $transformer;
protected $prefix;
protected $renderedContent = false;
/**
* GenericDOMView constructor.
* @param DOMTemplate $template
* @param ViewModel $viewModel
* @param RenderableStringTransformer $transformer
*/
public function __construct(DOMTemplate $template, ViewModel $viewModel, RenderableStringTransformer $transformer) {
$this->DOMTemplate = $template;
$this->DOMDocument = $template->getDOMDocument();
$this->viewModelData = $viewModel->getData();
$this->transformer = $transformer;
$this->prefix = $template->getInserterTokenPrefix();
$this->lowestWritableDir = '/htdocs';
$this->enforceLowestWriteLevelLimit = true;
$this->classOrSelfReferencePath = 'self';
$this->canSidestep = false;
}
/**
* @return bool|string
*/
public function render() {
if($this->renderedContent) {
return $this->renderedContent;
}
$doc = $this->DOMDocument;
$XPath = new \DOMXPath($doc);
$query = "//@*[starts-with(name(),'{$this->prefix}')]";
$nodeList = $XPath->query($query);
$nodeArr = [];
$len = $nodeList->length;
for($i = 0;$i < $len;++$i) {
$node = $nodeList->item($i);
$attrName = $node->nodeName;
$fieldName = str_replace($this->prefix,'',$attrName);
$owner = &$node->ownerElement;
$owner->removeAttribute($attrName);
$nodeArr[$fieldName] = &$owner;
}
foreach($this->viewModelData as $key => &$value) {
if(array_key_exists($key,$nodeArr) && ($node = $nodeArr[$key]) && ($node instanceof \DOMNode)) {
$stringVal = $this->transformer->toString($value);
$isXML = (strip_tags($stringVal) !== $stringVal);
if($isXML) {
$tmpDoc = clone $doc;
//LoadHTML is needed to correctly format HTML on loading
@$tmpDoc->loadHTML($stringVal);
//loadHTML creates html and body tags around stringVal, so content is first child of first child
$el = $doc->importNode($tmpDoc->documentElement,true);
} else {
$el = $doc->createTextNode($stringVal);
}
$node->appendChild($el);
}
}
$this->renderedContent = $doc->saveXML($doc->documentElement);
return $this->renderedContent;
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\GenericObjectStorageInterface;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/2/2015
* Time: 10:21 AM
*/
class GenericObjectStorage extends \SplObjectStorage implements GenericObjectStorageInterface {
public function clear() {
$tempStorage = clone $this;
$this->addAll($tempStorage);
$this->removeAll($tempStorage);
$tempStorage = null;
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\PHTMLTemplate;
use DynCom\mysyde\common\interfaces\Repository;
use DynCom\mysyde\common\interfaces\RepositoryListView;
use DynCom\mysyde\common\traits\genericRepositoryListViewTrait;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 25.07.2015
* Time: 15:21
*/
class GenericPHTMLRepositoryListView implements RepositoryListView
{
use genericRepositoryListViewTrait;
protected $template;
protected $model;
protected $renderedContent = false;
protected $repository;
/**
* GenericPHTMLRepositoryListView constructor.
* @param PHTMLTemplate $listElementTemplate
* @param Repository $repository
*/
public function __construct(PHTMLTemplate $listElementTemplate, Repository $repository) {
$this->template = $listElementTemplate;
$this->repository = $repository;
}
/**
* @param array $criteria
* @param int $offset
* @param int $limit
* @return bool|string
*/
public function render(array $criteria, $offset = 0, $limit = 0) {
if($this->renderedContent) return $this->renderedContent;
$renderedString = '';
$collection = $this->repository->findByCriteria($criteria,$offset,$limit);
foreach($collection as $listElement) {
$this->model = $listElement;
ob_start();
include_once($this->template->getPHTMLPath());
$renderedString .= ob_get_clean();
}
$this->renderedContent = $renderedString;
return $this->renderedContent;
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\PHTMLTemplate;
use DynCom\mysyde\common\interfaces\PHTMLView;
use DynCom\mysyde\common\interfaces\ViewModel;
use DynCom\mysyde\common\traits\genericViewTrait;
/**
* Created by PhpStorm.
* User: Michael Bauer
* Date: 7/14/2015
* Time: 2:19 AM
*/
class GenericPHTMLView implements PHTMLView
{
use genericViewTrait;
protected $template;
protected $model;
protected $renderedContent = false;
/**
* GenericPHTMLView constructor.
* @param PHTMLTemplate $template
* @param ViewModel $viewModel
*/
public function __construct(PHTMLTemplate $template, ViewModel $viewModel) {
$this->template = $template;
$this->model = (object)$viewModel->getData();
}
/**
* @return bool|string
*/
public function render() {
if($this->renderedContent) return $this->renderedContent;
ob_start();
include_once($this->template->getPHTMLPath());
$this->renderedContent = ob_get_clean();
return $this->renderedContent;
}
}

View File

@@ -0,0 +1,73 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\PlainRepositoryListView;
use DynCom\mysyde\common\interfaces\PlainTemplate;
use DynCom\mysyde\common\interfaces\Repository;
use DynCom\mysyde\common\traits\genericRepositoryListViewTrait;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 25.07.2015
* Time: 12:14
*/
class GenericPlainRepositoryListView implements PlainRepositoryListView
{
use genericRepositoryListViewTrait;
protected $templateFieldNames;
protected $templateContentRaw;
protected $templateFieldDelimiter;
protected $repository;
protected $transformer;
protected $renderedContent = false;
/**
* GenericPlainRepositoryListView constructor.
* @param PlainTemplate $listElementTemplate
* @param Repository $repository
* @param RenderableStringTransformer $transformer
*/
public function __construct(PlainTemplate $listElementTemplate, Repository $repository, RenderableStringTransformer $transformer) {
$this->templateContentRaw = $listElementTemplate->getRawContent();
$this->templateFieldNames = $listElementTemplate->getFields();
$this->templateFieldDelimiter = $listElementTemplate->getDelimiter();
$this->repository = $repository;
$this->transformer = $transformer;
}
/**
* @param array $criteria
* @param int $offset
* @param int $limit
* @param bool $cleanup
* @return bool|string
*/
public function render(array $criteria, $offset = 0, $limit = 0, $cleanup = true) {
if($this->renderedContent) {return $this->renderedContent;}
$collection = $this->repository->findByCriteria($criteria,$offset,$limit);
$renderedString = '';
$content = '';
foreach($collection as $listElement) {
$content = $this->templateContentRaw;
foreach($this->templateFieldNames as $fieldName) {
if(property_exists($listElement,$fieldName)) {
$valueStr = $this->transformer->toString($listElement->$fieldName);
$token = '{' . $this->templateFieldDelimiter . $fieldName . $this->templateFieldDelimiter . '}';
$content = str_replace($token,$valueStr,$content);
}
}
}
if($cleanup) {
foreach($this->templateFieldNames as $fieldName) {
$token = '{' . $this->templateFieldDelimiter . $fieldName . $this->templateFieldDelimiter . '}';
$content = str_replace($token,'',$content);
}
}
$renderedString .= $content;
$this->renderedContent = $renderedString;
return $this->renderedContent;
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\PlainTemplate;
use DynCom\mysyde\common\interfaces\PlainView;
use DynCom\mysyde\common\interfaces\ViewModel;
use DynCom\mysyde\common\traits\genericViewTrait;
/**
* Created by PhpStorm.
* User: Michael Bauer
* Date: 7/14/2015
* Time: 2:26 AM
*/
class GenericPlainView implements PlainView
{
use genericViewTrait;
protected $templateFieldNames;
protected $templateContentRaw;
protected $templateFieldDelimiter;
protected $viewModelData;
protected $transformer;
protected $renderedContent = false;
/**
* GenericPlainView constructor.
* @param PlainTemplate $template
* @param ViewModel $viewModel
* @param RenderableStringTransformer $transformer
*/
public function __construct(PlainTemplate $template, ViewModel $viewModel, RenderableStringTransformer $transformer) {
$this->templateContentRaw = $template->getRawContent();
$this->templateFieldNames = $template->getFields();
$this->templateFieldDelimiter = $template->getDelimiter();
$this->viewModelData = $viewModel->getData();
$this->transformer = $transformer;
}
/**
* @param bool $cleanup
* @return bool|mixed|string
*/
public function render($cleanup = true) {
if($this->renderedContent) {return $this->renderedContent;}
$content = $this->templateContentRaw;
foreach($this->viewModelData as $key => &$value) {
if(in_array($key,$this->templateFieldNames,false)) {
$valueStr = $this->transformer->toString($value);
$token = '{' . $this->templateFieldDelimiter . $key . $this->templateFieldDelimiter . '}';
$content = str_replace($token,$valueStr,$content);
}
}
unset($value);
if($cleanup) {
foreach($this->templateFieldNames as $fieldName) {
$token = '{' . $this->templateFieldDelimiter . $fieldName . $this->templateFieldDelimiter . '}';
$content = str_replace($token,'',$content);
}
}
return $content;
}
}

View File

@@ -0,0 +1,227 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\ServicePayload;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 17.08.2015
* Time: 09:42
*/
class GenericServicePayload implements ServicePayload
{
/**
* @var ServiceRequestID
*/
protected $requestID;
/**
* @var string
*/
protected $serviceName;
/**
* @var int
*/
protected $statusCode;
/**
* @var string
*/
protected $statusMessage;
/**
* @var array
*/
protected $payloadData;
/**
* @var array
*/
protected $devErrors;
/**
* @var array
*/
protected $devWarnings;
/**
* @var array
*/
protected $devNotifications;
/**
* @var array
*/
protected $userSuccessMsgs;
/**
* @var array
*/
protected $userErrors;
/**
* @var array
*/
protected $userWarnings;
/**
* @var array
*/
protected $userNotifications;
/**
* GenericServicePayload constructor.
* @param ServiceRequestID $requestID
* @param $serviceName
* @param $statusCode
* @param $statusMessage
* @param array $payloadData
* @param array $devErrors
* @param array $devWarnings
* @param array $devNotifications
* @param array $userSuccessMsgs
* @param array $userErrors
* @param array $userWarnings
* @param array $userNotifications
*/
public function __construct(
ServiceRequestID $requestID,
$serviceName,
$statusCode,
$statusMessage,
array $payloadData,
array $devErrors,
array $devWarnings,
array $devNotifications,
array $userSuccessMsgs,
array $userErrors,
array $userWarnings,
array $userNotifications)
{
$this->requestID = clone $requestID;
$this->serviceName = (string)$serviceName;
$this->statusCode = (int)$statusCode;
$this->statusMessage = (string)$statusMessage;
$this->payloadData = $payloadData;
$this->devErrors = $devErrors;
$this->devWarnings = $devWarnings;
$this->devNotifications = $devNotifications;
$this->userSuccessMsgs = $userSuccessMsgs;
$this->userErrors = $userErrors;
$this->userWarnings = $userWarnings;
$this->userNotifications = $userNotifications;
}
/**
* @return ServiceRequestID
*/
public function getRequestID()
{
return $this->requestID;
}
/**
* @return string
*/
public function getServiceName()
{
return $this->serviceName;
}
/**
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* @return string
*/
public function getStatusMessage()
{
return $this->statusMessage;
}
/**
* @return array
*/
public function getPayloadData()
{
return $this->payloadData;
}
/**
* @return array
*/
public function getDevErrors()
{
return $this->devErrors;
}
/**
* @return array
*/
public function getDevWarnings()
{
return $this->devWarnings;
}
/**
* @return array
*/
public function getDevNotifications()
{
return $this->devNotifications;
}
/**
* @return array
*/
public function getUserSuccessMsgs()
{
return $this->userSuccessMsgs;
}
/**
* @return array
*/
public function getUserErrors()
{
return $this->userErrors;
}
/**
* @return array
*/
public function getUserWarnings()
{
return $this->userWarnings;
}
/**
* @return array
*/
public function getUserNotifications()
{
return $this->userNotifications;
}
}

View File

@@ -0,0 +1,428 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 17.08.2015
* Time: 15:49
*/
class GenericServicePayloadBuilder
{
/**
* @var ServiceRequestID
*/
protected $requestID;
/**
* @var string
*/
protected $serviceName = '';
/**
* @var int
*/
protected $statusCode = 400;
/**
* @var string
*/
protected $statusMessage = '';
/**
* @var array
*/
protected $payloadData = [];
/**
* @var array
*/
protected $devErrors = [];
/**
* @var array
*/
protected $devWarnings = [];
/**
* @var array
*/
protected $devNotifications = [];
/**
* @var array
*/
protected $userSuccessMsgs = [];
/**
* @var array
*/
protected $userErrors = [];
/**
* @var array
*/
protected $userWarnings = [];
/**
* @var array
*/
protected $userNotifications = [];
/**
* @return ServiceRequestID
*/
public function getRequestID()
{
return $this->requestID;
}
/**
* @param ServiceRequestID $requestID
*/
public function setRequestID($requestID)
{
$this->requestID = $requestID;
}
/**
* @return string
*/
public function getServiceName()
{
return $this->serviceName;
}
/**
* @param string $serviceName
*/
public function setServiceName($serviceName)
{
$this->serviceName = $serviceName;
}
/**
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* @param int $statusCode
*/
public function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;
}
/**
* @return string
*/
public function getStatusMessage()
{
return $this->statusMessage;
}
/**
* @param string $statusMessage
*/
public function setStatusMessage($statusMessage)
{
$this->statusMessage = $statusMessage;
}
/**
* @return array
*/
public function getPayloadData()
{
return $this->payloadData;
}
/**
* @param array $payloadData
*/
public function setPayloadData($payloadData)
{
$this->payloadData = $payloadData;
}
/**
* @return array
*/
public function getDevErrors()
{
return $this->devErrors;
}
/**
* @param array $devErrors
*/
public function setDevErrors($devErrors)
{
$this->devErrors = $devErrors;
}
/**
* @return array
*/
public function getDevWarnings()
{
return $this->devWarnings;
}
/**
* @param array $devWarnings
*/
public function setDevWarnings($devWarnings)
{
$this->devWarnings = $devWarnings;
}
/**
* @return array
*/
public function getDevNotifications()
{
return $this->devNotifications;
}
/**
* @param array $devNotifications
*/
public function setDevNotifications($devNotifications)
{
$this->devNotifications = $devNotifications;
}
/**
* @return array
*/
public function getUserSuccessMsgs()
{
return $this->userSuccessMsgs;
}
/**
* @param array $userSuccessMsgs
*/
public function setUserSuccessMsgs($userSuccessMsgs)
{
$this->userSuccessMsgs = $userSuccessMsgs;
}
/**
* @return array
*/
public function getUserErrors()
{
return $this->userErrors;
}
/**
* @param array $userErrors
*/
public function setUserErrors($userErrors)
{
$this->userErrors = $userErrors;
}
/**
* @return array
*/
public function getUserWarnings()
{
return $this->userWarnings;
}
/**
* @param array $userWarnings
*/
public function setUserWarnings($userWarnings)
{
$this->userWarnings = $userWarnings;
}
/**
* @return array
*/
public function getUserNotifications()
{
return $this->userNotifications;
}
/**
* @param array $userNotifications
*/
public function setUserNotifications($userNotifications)
{
$this->userNotifications = $userNotifications;
}
public function reset()
{
unset($this->requestID);
$this->serviceName = '';
$this->statusCode = 400;
$this->statusMessage = '';
$this->devErrors = [];
$this->devWarnings = [];
$this->devNotifications = [];
$this->userSuccessMsgs = [];
$this->userErrors = [];
$this->userNotifications = [];
}
/**
* @return GenericServicePayload
*/
public function makeGenericServicePayload()
{
return new GenericServicePayload($this->requestID, $this->serviceName, $this->statusCode, $this->statusMessage, $this->payloadData, $this->devErrors, $this->devWarnings, $this->devNotifications, $this->userSuccessMsgs, $this->userErrors, $this->userWarnings, $this->userNotifications);
}
/**
* @param $serviceName
* @param ServiceRequestID|null $requestID
* @param array $messageData
* @return GenericServicePayload
*/
public function make400GenericServicePayload($serviceName, ServiceRequestID $requestID = null, array $messageData = []) {
$this->reset();
$this->serviceName = $serviceName;
if(null !== $requestID) {
$this->requestID = $requestID;
}
if(null === $this->requestID) {
$this->requestID = new ServiceRequestID($this->serviceName);
}
$this->statusCode = 400;
$this->statusMessage = 'Bad Request';
$requestIDString = $this->requestID->getID();
$this->devErrors = [
$requestIDString => [
'code' => 400,
'message' => 'bad_request',
'message_data' => $messageData
]
];
$this->userErrors = [
$requestIDString => [
'code' => 400,
'message' => 'bad_request',
'message_data' => $messageData
]
];
return $this->makeGenericServicePayload();
}
/**
* @param $serviceName
* @param ServiceRequestID|null $requestID
* @param array $messageData
* @return GenericServicePayload
*/
public function make403GenericServicePayload($serviceName, ServiceRequestID $requestID = null, array $messageData = []) {
$this->reset();
$this->serviceName = $serviceName;
if(null !== $requestID) {
$this->requestID = $requestID;
}
if(null === $this->requestID) {
$this->requestID = new ServiceRequestID($this->serviceName);
}
$this->statusCode = 403;
$this->statusMessage = 'Forbidden.';
$requestIDString = $this->requestID->getID();
$this->devErrors = [
$requestIDString => [
'code' => 403,
'message' => 'Forbidden.',
'message_data' => $messageData
]
];
$this->userErrors = [
$requestIDString => [
'code' => 403,
'message' => 'not_found',
'message_data' => $messageData
]
];
return $this->makeGenericServicePayload();
}
/**
* @param $serviceName
* @param ServiceRequestID|null $requestID
* @param array $messageData
* @return GenericServicePayload
*/
public function make404GenericServicePayload($serviceName, ServiceRequestID $requestID = null, array $messageData = []) {
$this->reset();
$this->serviceName = $serviceName;
if(null !== $requestID) {
$this->requestID = $requestID;
}
if(null === $this->requestID) {
$this->requestID = new ServiceRequestID($this->serviceName);
}
$this->statusCode = 404;
$this->statusMessage = 'Not Found.';
$this->devErrors = [
$this->requestID->getID() => [
'code' => 404,
'message' => 'Not Found.',
'message_data' => $messageData
]
];
$this->userErrors = [
$this->requestID->getID() => [
'code' => 404,
'message' => 'not_found',
'message_data' => $messageData
]
];
return $this->makeGenericServicePayload();
}
/**
* @param $serviceName
* @param ServiceRequestID|null $requestID
* @param array $messageData
* @return GenericServicePayload
*/
public function make405GenericServicePayload($serviceName, ServiceRequestID $requestID = null, array $messageData = []) {
$this->reset();
$this->serviceName = $serviceName;
if(null !== $requestID) {
$this->requestID = $requestID;
}
if(null === $this->requestID) {
$this->requestID = new ServiceRequestID($this->serviceName);
}
$this->statusCode = 405;
$this->statusMessage = 'Method not allowed.';
$requestIDString = $this->requestID->getID();
$this->devErrors = [
$requestIDString => [
'code' => 405,
'message' => 'Method not allowed.',
'message_data' => $messageData
]
];
$this->userErrors = [
$requestIDString => [
'code' => 405,
'message' => 'method_not_allowed',
'message_data' => $messageData
]
];
return $this->makeGenericServicePayload();
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\GenericViewInterface;
use DynCom\mysyde\common\interfaces\Template;
use DynCom\mysyde\common\interfaces\ViewModel;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 22.01.2015
* Time: 14:22
*/
class GenericView implements GenericViewInterface {
/**
* @var ViewModel
*/
protected $model;
/**
* @var Template
*/
protected $template;
/**
* @var string
*/
protected $renderedContent;
/**
* @var bool
*/
protected $isRendered = false;
/**
* @param Template $template
* @param ViewModel $model
*/
public function __construct(Template $template, ViewModel $model) {
$this->template = $template;
$this->model = $model;
}
/**
* @param TemplateInserterFactory $inserterFactory
*/
public function render(TemplateInserterFactory $inserterFactory) {
$viewModelData = $this->model->getData();
$inserter = $inserterFactory->getInserter($this->template,$viewModelData);
if(!isset($inserter)) {throw new \InvalidArgumentException('Template is not of allowed type. Allowed types are default, string, or DOM.');}
$inserter->insertData();
$this->renderedContent = $this->template->getRenderedContent();
$this->isRendered = true;
}
/**
* @return string
*/
public function getContent() {
return $this->renderedContent;
}
public function echoContent() {
echo $this->renderedContent;
}
/**
* @return bool
*/
public function isRendered() {
return $this->isRendered;
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* Created by PhpStorm.
* User: bauer
* Date: 28.06.2017
* Time: 14:08
*/
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\AddressValidator;
use GuzzleHttp\Client;
class GoogleAddressValidator implements AddressValidator
{
protected const GOOGLE_GEOCODE_JSON_ENDPOINT_URL = 'https://maps.googleapis.com/maps/api/geocode/json';
/**
* @var bool
*/
protected $isInitialized = false;
/**
* @var Client
*/
protected $client;
/**
* @var string
*/
protected $apiKey;
protected function initialize()
{
$this->apiKey = getenv('GOOGLE_MAPS_API_KEY') ?? '';
$client = new Client(
['headers' => [
'Authorization' => 'Bearer ' . $this->apiKey,
]]
);
$this->client = $client;
$this->isInitialized = true;
}
public function isAddressValid(string $address): bool
{
if (!$this->isInitialized) {
$this->initialize();
}
$endpoint = self::GOOGLE_GEOCODE_JSON_ENDPOINT_URL . '?address=' . urlencode($address);
$response = $this->client->get($endpoint);
if ($response->getStatusCode() != '200') {
return false;
}
$responseBodyContent = $response->getBody()->getContents();
try {
$decodedBody = \GuzzleHttp\json_decode($responseBodyContent, true);
if (array_key_exists('status',$decodedBody) && $decodedBody['status'] === 'OK') {
return true;
}
} catch (\Throwable $t) {
return false;
}
return false;
}
}

View File

@@ -0,0 +1,224 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\dcShop\interfaces\TextProviderInterface;
/**
* Class HTMLSnippetProvider
*/
class HTMLSnippetProvider implements TextProviderInterface {
const GENERICDIV = '
<div class="{CLASSNAME}" id="{ID}" {VARATTRIBUTES}>{INNERHTML}</div>';
const GENERICSPAN = '<span class="{CLASSNAME}" id="{ID}" {VARATTRIBUTES}>{INNERHTML}</span>';
const GENERICANCHOR = '<a href="{HREF}" id="{ID} class="{CLASSNAME}" alt="{ALTTEXT}" {VARATTRIBUTES}>{INNERHTML}</a>';
const GENERICFORM = '
<form class="{CLASSNAME}" id="{ID}" method="{METHOD}" action="{ACTION}" {VARATTRIBUTES}>{INNERHTML}</form>';
const GENERICTABLE = '
<table class="{CLASSNAME}" id="{ID}" width="{WIDTH}" height="{HEIGHT}" cellpadding="{CELLPADDING}" cellspacing="{CELLSPACING}" align="{ALIGN}" valign="{VALIGN}" {VARATTRIBUTES}>{INNERHTML}</table>';
const GENERICTHEAD = '
<thead>{INNERHTML}</thead>';
const GENERICTBODY = '
<tbody>{INNERHTML}</tbody>';
const GENERICTFOOT = '
<tfoot>{INNERHTML}</tfoot>';
const GENERICTABLEROW = '
<tr class="{CLASSNAME}" id="{ID}" width="{WIDTH}" height="{HEIGHT}" {VARATTRIBUTES}>{INNERHTML}</tr>';
const GENERICTH = '<th class="{CLASSNAME}" id="{ID}" colspan="{COLSPAN}" rowspan="{ROWSPAN}" align="{ALIGN}" valign="{VALIGN}" width="{WIDTH}" height="{HEIGHT}" {VARATTRIBUTES}>{INNERHTML}</th>';
const GENERICTD = '<td class="{CLASSNAME}" id="{ID}" colspan="{COLSPAN}" rowspan="{ROWSPAN}" align="{ALIGN}" valign="{VALIGN}" width="{WIDTH}" height="{HEIGHT}" {VARATTRIBUTES}>{INNERHTML}</td>';
const GENERICINPUT = '<input name="{INPUTNAME}" type="{TYPE}" value="{VALUE}" placeholder="{PLACEHOLDER}" class="{CLASSNAME}" id="{ID}" {CHECKED} {DISABLED} {VARATTRIBUTES} />';
const GENERICSELECT = '
<select name="{INPUTNAME}" class="{CLASSNAME}" id="{ID}" {MULTIPLE} {DISABLED} {VARATTRIBUTES}>{INNERHTML}</select>';
const GENERICOPTGROUP = '
<optgroup label="{LABEL}">{INNERHTML}</optgroup>';
const GENERICOPTION = '<option value="{VALUE}" {DISABLED} {SELECTED} {VARATTRIBUTES}>{NAME}</option>';
const GENERICTEXTAREA = '
<textarea rows="{ROWS}" cols="{COLS}" width="{WIDTH}" height="{HEIGHT}" {DISABLED} {VARATTRIBUTES}>{TEXT}</textarea>';
const LABELEDINPUT = '
<div class="label">
<label for="{INPUTNAME}">{NAME}</label>
</div>
<div class="input">
<input name="{INPUTNAME}" type="{TYPE}" value="{VALUE}" class="{CLASSNAME}" id="{ID}" {VARATTRIBUTES} />
</div>';
const LABELEDSELECT = '
<div class="label">
<label for="{INPUTNAME}">{NAME}</label>
</div>
<div class="input">
<select name="{INPUTNAME}" class="{CLASSNAME}" id="{ID}" {MULTIPLE} {DISABLED} {VARATTRIBUTES}>{INNERHTML}</select>
</div>';
const LABALEDTEXTAREA = '
<div class="label">
<label for="{INPUTNAME}">{NAME}</label>
</div>
<div class="input">
<textarea rows="{ROWS}" cols="{COLS}" width="{WIDTH}" height="{HEIGHT}" {DISABLED} {VARATTRIBUTES}>{VALUE}</textarea>
</div>';
const ERRORBOX = '
<div class="errorbox {ADDEDCLASSNAMES}" id="{ID}">{INNERHTML}</div>';
const SUCCESSBOX = '
<div class="successbox {ADDEDCLASSNAMES}" id="{ID}">{INNERHTML}</div>';
const NOTICEBOX = '
<div class="noticebox {ADDEDCLASSNAMES}" id="{ID}">{INNERHTML}</div>';
const ERRORTEXT = '
<div class="errortext {ADDEDCLASSNAMES}" id="{ID}">{INNERHTML}</div>';
const SUCCESSTEXT = '
<div class="successtext {ADDEDCLASSNAMES}" id="{ID}">{INNERHTML}</div>';
const NOTICETEXT = '
<div class="noticetext {ADDEDCLASSNAMES}" id="{ID}">{INNERHTML}</div>';
/**
* @param $name
*
* @return mixed|null
*/
public function getConstant( $name ) {
return $this->_getConstant($name);
}
/**
* @param $name
*
* @return mixed|null
*/
protected function _getConstant( $name ) {
if (defined('self::' . $name)) {
return constant('self::' . $name);
}
return NULL;
}
/**
* @param $name
*/
public function printConstant( $name ) {
$this->_printConstant($name);
}
/**
* @param $name
*/
protected function _printConstant( $name ) {
if (defined('self::' . $name)) {
echo constant($name);
}
}
/**
* @param $name
*
* @return mixed|null
*/
public function getText( $name ) {
return $this->_getConstant($name);
}
/**
* @param $name
*
* @return mixed|void
*/
public function printText( $name ) {
$this->_printConstant($name);
}
/**
* @param $inner
* @param string $id
* @param string $className
*
* @return string
*/
public function wrapInDiv( $inner, $id = '', $className = '' ) {
$output = "<div";
if(preg_match("/[a-zA-Z0-9_\-]+/",$id)) {
$output .= " id=\"" . $id . "\" ";
}
if(preg_match("/[a-zA-Z0-9_\-]+/",$className)) {
$output .= " class=\"" . $className . "\" ";
}
$output .= ">" . $inner . "</div>";
return $output;
}
/**
* @param $inner
* @param string $id
* @param string $className
*
* @return string
*/
public function wrapInSpan( $inner, $id = '', $className = '' ) {
$output = "<span";
if(preg_match("/[a-zA-Z0-9_\-]+/",$id)) {
$output .= " id=\"" . $id . "\" ";
}
if(preg_match("/[a-zA-Z0-9_\-]+/",$className)) {
$output .= " class=\"" . $className . "\" ";
}
$output .= ">" . $inner . "</span>";
return $output;
}
/**
* @param $inner
* @param string $id
* @param string $className
*
* @return string
*/
public function wrapInUL( $inner, $id = '', $className = '' ) {
$output = "<ul";
if(preg_match("/[a-zA-Z0-9_\-]+/",$id)) {
$output .= " id=\"" . $id . "\" ";
}
if(preg_match("/[a-zA-Z0-9_\-]+/",$className)) {
$output .= " class=\"" . $className . "\" ";
}
$output .= ">" . $inner . "</ul>";
return $output;
}
/**
* @param $inner
* @param string $id
* @param string $className
*
* @return string
*/
public function wrapInLI( $inner, $id = '', $className = '' ) {
$output = "<li";
if(preg_match("/[a-zA-Z0-9_\-]+/",$id)) {
$output .= " id=\"" . $id . "\" ";
}
if(preg_match("/[a-zA-Z0-9_\-]+/",$className)) {
$output .= " class=\"" . $className . "\" ";
}
$output .= ">" . $inner . "</li>";
return $output;
}
/**
* @param $href
* @param $inner
* @param string $id
* @param string $className
*
* @return string
*/
public function wrapInAnchor( $href, $inner, $id = '', $className = '' ) {
if(!filter_var($href,FILTER_VALIDATE_URL)) {
return '';
}
$output = "<a href=\"" . $href . "\"";
if(preg_match("/[a-zA-Z0-9_\-]+/",$id)) {
$output .= " id=\"" . $id . "\" ";
}
if(preg_match("/[a-zA-Z0-9_\-]+/",$className)) {
$output .= " class=\"" . $className . "\" ";
}
$output .= ">" . $inner . "</a>";
return $output;
}
}

View File

@@ -0,0 +1,174 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\Entity;
use DynCom\mysyde\common\interfaces\Observer;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 08.07.2015
* Time: 13:29
*/
class Hook
{
/**
* @var $logger \Psr\Log\LoggerInterface
*/
protected static $logger;
protected static $listenedEventNames = [];
/**
* @param Observer $listener
* @param $eventName
* @param string $namespace
* @param string $callbackName
*/
public static function registerEventListener(Observer $listener, $eventName, $namespace = 'global', $callbackName = null)
{
self::ensureLoggerSet();
$listenerID = spl_object_hash($listener);
static::$listenedEventNames[$namespace][$eventName]['listeners'][$listenerID]['obj'] = &$listener;
static::$listenedEventNames[$namespace][$eventName]['listeners'][$listenerID]['callback'] = self::getCallbackCallable($listener,$callbackName);
static::$listenedEventNames[$namespace][$eventName]['listeners'][$listenerID]['IDs'] = [];
self::$logger->debug('EventListener of class [' . get_class($listener) . '] registered for eventName [' . $eventName . '] in namespace [' . $namespace . '] with callback name [' . $callbackName . ']');
}
/**
* @param Observer $listener
* @param $callback
* @return null|\Closure
*/
protected static function getCallbackCallable(Observer $listener, $callback)
{
if (null === $callback || is_callable($callback)) {
return $callback;
}
if (method_exists($listener,$callback)) {
return function($eventName, $data) use ($listener,$callback) {
return $listener->$callback($eventName,$data);
};
}
}
/**
* @param Observer $listener
* @param $eventName
* @param $id
* @param string $namespace
*/
public static function addSourceIDForEventListener(Observer $listener, $eventName, $id, $namespace = 'global')
{
self::ensureLoggerSet();
$listenerID = spl_object_hash($listener);
if (!isset(static::$listenedEventNames[$namespace][$eventName]['listeners'][$listenerID])) {
throw new \InvalidArgumentException(
'Observer ' . get_class($listener) . ' is not registered for Event ' . strip_tags($eventName) . ' in Namespace ' . strip_tags($namespace)
);
}
static::$listenedEventNames[$namespace][$eventName]['listeners'][$listenerID]['IDs'][] = $id;
self::$logger->debug('added SourceID [' . $id . '] for EventListener of class [' . get_class($listener) . '] registered for eventName [' . $eventName . '] in namespace [' . $namespace . ']');
}
/**
* @param Observer $listener
* @param $eventName
* @param string $namespace
*/
public static function unregisterEventListener(Observer $listener, $eventName, $namespace = 'global')
{
self::ensureLoggerSet();
$listenerID = spl_object_hash($listener);
unset(static::$listenedEventNames[$namespace][$eventName]['listeners'][$listenerID]);
self::$logger->debug('Unregistered EventListener of class [' . get_class($listener) . '] for eventName [' . $eventName . '] in namespace [' . $namespace . ']');
}
/**
* @param $eventName
* @param $data
* @param string $namespace
*/
public static function update($eventName, $data, $namespace = 'global')
{
self::ensureLoggerSet();
self::$logger->debug('Event of name [' . $eventName . '] occurred');
if (!is_array(static::$listenedEventNames) || !array_key_exists($namespace, static::$listenedEventNames) || !is_array(static::$listenedEventNames[$namespace]) || !array_key_exists($eventName, static::$listenedEventNames[$namespace])) {
//No listener for event
return;
}
foreach (static::$listenedEventNames[$namespace][$eventName]['listeners'] as $listenerRegistryEntry) {
self::notifyEventListener($eventName, $data, $listenerRegistryEntry);
}
}
protected static function ensureLoggerSet()
{
if (!self::isLoggerSet()) {
self::$logger = self::getLogger();
}
}
/**
* @return bool
*/
protected static function isLoggerSet()
{
return self::$logger instanceof LoggerInterface;
}
/**
* @return Logger
*/
protected static function getLogger()
{
$envGlobalsLoglevel = getenv('LOGLEVEL_GLOBAL');
$globalLogLevel = $envGlobalsLoglevel ? $envGlobalsLoglevel : 'CRITICAL';
$envLogLevelHook = getenv('LOGLEVEL_HOOK');
$hookLogLevel = $envLogLevelHook ? $envLogLevelHook : $globalLogLevel;
$baseDir = dirname(dirname(dirname(__DIR__)));
$logDir = rtrim($baseDir, '/') . '/logs/';
$logFilePath = $logDir . 'hook_log.log';
$handlers = [];
$rotatingFileHandler = new RotatingFileHandler($logFilePath, 10);
$rotatingFileHandler->setLevel($hookLogLevel);
$formatter = new LineFormatter(null, null, false, true);
$rotatingFileHandler->setFormatter($formatter);
$handlers[] = $rotatingFileHandler;
$logger = new Logger('hook_log', $handlers);
return $logger;
}
/**
* @param $eventName
* @param $data
* @param array $listenerRegistryEntry
*/
protected static function notifyEventListener($eventName, $data, array $listenerRegistryEntry)
{
$listener = array_key_exists('obj',$listenerRegistryEntry) && ($listenerRegistryEntry['obj'] instanceof Observer) ? $listenerRegistryEntry['obj'] : null;
if ($listener) {
$idCount = count($listenerRegistryEntry['IDs']);
if ($idCount === 0 || (($data instanceof Entity) && in_array($data->getID(), $listenerRegistryEntry['IDs'], true))) {
$listener->notify($eventName, $data);
self::$logger->debug('Listener of class [' . get_class($listener) . '] found for eventName [' . $eventName . '] notified.');
if (null !== $listenerRegistryEntry['callback']) {
$listenerRegistryEntry['callback']($eventName, $data);
}
}
}
}
}

View File

@@ -0,0 +1,78 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\Entity;
use DynCom\mysyde\common\interfaces\GenericDBModelInterface;
use DynCom\mysyde\common\traits\genericDBModelTrait;
use DynCom\mysyde\common\traits\universallyGettableTrait;
/**
* Created by PhpStorm.
* User: Micha
* Date: 19.01.2015
* Time: 00:01
*/
class Language implements GenericDBModelInterface, Entity {
use genericDBModelTrait, universallyGettableTrait;
protected $id;
protected $main_site_id;
protected $code;
protected $language_code;
protected $name;
protected $site_name;
protected $site_title_name;
protected $main_layout_id;
protected $meta_description;
protected $meta_keywords;
protected $std_main_navigation_id;
protected $company;
protected $shop_code;
protected $shop_language_code;
protected $logout_site_id;
protected $logout_language_id;
protected $logout_navigation_id;
/**
* @param LanguageConfig $config
*/
public function __construct( LanguageConfig $config ) {
$this->config = $config;
}
/**
* @return Language
*/
public function getNullObject() {
return new self($this->config);
}
/**
* @return array
*/
public function getLinkedShopPrimary()
{
$primary = [];
if ($this->company && $this->shop_code) {
$primary['company'] = $this->company;
$primary['code'] = $this->shop_code;
}
return $primary;
}
/**
* @return array
*/
public function getLinkedShopLanguagePrimary()
{
$primary = [];
if ($this->company && $this->shop_code && $this->shop_language_code) {
$primary['company'] = $this->company;
$primary['shop_code'] = $this->shop_code;
$primary['code'] = $this->shop_language_code;
}
return $primary;
}
}

View File

@@ -0,0 +1,77 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\CriteriaHelperInterface;
use DynCom\mysyde\common\interfaces\GenericCollectionInterface;
use DynCom\mysyde\common\traits\genericCollectionTrait;
/**
* Created by PhpStorm.
* User: Micha
* Date: 19.01.2015
* Time: 00:01
*/
class LanguageCollection implements GenericCollectionInterface {
use genericCollectionTrait;
/**
* @param LanguageConfig $config
* @param CriteriaHelperInterface $criteriaValidationService
*/
public function __construct( LanguageConfig $config, CriteriaHelperInterface $criteriaValidationService ) {
$this->elements = new \SplObjectStorage();
$this->config = $config;
$this->criteriaValidationService = $criteriaValidationService;
$this->entryClassName = $config->getModelClassName();
}
/**
* @return LanguageCollection
*/
public function getEmptyCollection() {
return new self($this->config,$this->criteriaValidationService);
}
/**
* @param mixed $instance
* @param bool $idCheck
*
* @return bool
*/
public function add( $instance, $idCheck = FALSE ) {
return $this->_addLanguage($instance, $idCheck);
}
/**
* @param Language $language
* @param bool $idCheck
*
* @return bool
*/
protected function _addLanguage( Language $language, $idCheck = FALSE ) {
return $this->_add($language, $idCheck);
}
/**
* @param mixed $instance
* @param bool $idCheck
*
* @return bool
*/
public function remove( $instance, $idCheck = FALSE ) {
return $this->_removeLanguage($instance,$idCheck);
}
/**
* @param Language $language
* @param bool $idCheck
*
* @return bool
*/
protected function _removeLanguage( Language $language, $idCheck = FALSE ) {
return $this->_remove($language,$idCheck);
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\ModelDBConfigInterface;
use DynCom\mysyde\common\traits\genericConfigTrait;
/**
* Created by PhpStorm.
* User: Micha
* Date: 19.01.2015
* Time: 00:01
*/
class LanguageConfig implements ModelDBConfigInterface {
use genericConfigTrait;
protected $modelClassName = 'DynCom\mysyde\common\classes\Language';
protected $tableName = 'main_language';
protected $baseTableName = 'main_language';
protected $altPrimary = array('main_site_id','code');
protected $mappedFields = array(
array('name'=>'id','type'=>'INT'),
array('name'=>'main_site_id','type'=>'INT'),
array('name'=>'code','type'=>'VARCHAR'),
array('name' => 'locale_code', 'type' => 'VARCHAR'),
array('name'=>'name','type'=>'VARCHAR'),
array('name'=>'site_name','type'=>'VARCHAR'),
array('name'=>'site_title_name','type'=>'VARCHAR'),
array('name'=>'main_layout_id','type'=>'INT'),
array('name'=>'meta_description','type'=>'LONGTEXT'),
array('name'=>'meta_keywords','type'=>'LONGTEXT'),
array('name'=>'std_main_navigation_id','type'=>'INT'),
array('name'=>'company','type'=>'VARCHAR'),
array('name'=>'shop_code','type'=>'VARCHAR'),
array('name'=>'shop_language_code','type'=>'VARCHAR'),
array('name'=>'logout_site_id','type'=>'INT'),
array('name'=>'logout_language_id','type'=>'INT'),
array('name'=>'logout_navigation_id','type'=>'INT')
);
}

View File

@@ -0,0 +1,87 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\CriteriaHelperInterface;
use DynCom\mysyde\common\interfaces\GenericDBQueryWrapperInterface;
use DynCom\mysyde\common\interfaces\Repository;
use DynCom\mysyde\common\traits\genericRepositoryTrait;
use DynCom\mysyde\dcShop\classes\ShopLanguageRepository;
use DynCom\mysyde\dcShop\classes\ShopRepository;
/**
* Created by PhpStorm.
* User: Micha
* Date: 19.01.2015
* Time: 00:01
*/
class LanguageRepository implements Repository {
use genericRepositoryTrait;
/**
* @param GenericDBQueryWrapperInterface $db
* @param LanguageConfig $config
* @param CriteriaHelperInterface $criteriaValidationService
* @param LanguageCollection $collection
* @param $cacheAll
*/
public function __construct( GenericDBQueryWrapperInterface $db, LanguageConfig $config, CriteriaHelperInterface $criteriaValidationService, LanguageCollection $collection, $cacheAll=false) {
$this->db = $db;
$this->config = $config;
$this->criteriaValidationService = $criteriaValidationService;
$this->collection = $collection;
$this->collectionEntryClassName = $this->collection->getEntryClassName();
}
/**
* @param SiteRepository $siteRepository
* @return mixed
*/
public function getFromRequest(SiteRepository $siteRepository) {
$site = $siteRepository->getFromRequest();
$main_site_id = $site->getID();
$std_main_language_id = $site->std_main_language_id;
if(isset($_GET['language'])) {
$found = $this->findByAltPrimary(array('main_site_id' => $main_site_id,'code' => filter_var($_GET['language'],FILTER_SANITIZE_SPECIAL_CHARS)));
} else {
$found = $this->findByID($std_main_language_id);
}
return $found;
}
/**
* @param ShopRepository $shopRepository
* @param SiteRepository $siteRepository
* @return \DynCom\mysyde\dcShop\classes\Shop|mixed
*/
public function getCurrShopFromRequest(ShopRepository $shopRepository, SiteRepository $siteRepository) {
$currLanguage = $this->getFromRequest($siteRepository);
$nullObj = $shopRepository->getNullObject();
if(!isset($currLanguage->company) || !isset($currLanguage->shop_code)) {
return $nullObj;
}
$altPrimaryArr = [
'company' => $currLanguage->company,
'code' => $currLanguage->shop_code
];
$found = $shopRepository->findByAltPrimary($altPrimaryArr);
return $found;
}
/**
* @param ShopLanguageRepository $shopLanguageRepository
* @param SiteRepository $siteRepository
* @return mixed
*/
public function getCurrShopLanguageFromRequest(ShopLanguageRepository $shopLanguageRepository, SiteRepository $siteRepository) {
$currLanguage = $this->getFromRequest($siteRepository);
$nullObj = $shopLanguageRepository->getNullObject();
if(!isset($currLanguage->company) || !isset($currLanguage->shop_code) || !isset($currLanguage->shop_language_code)) {
return $nullObj;
}
return $shopLanguageRepository->findByAltPrimary(array('company' => $currLanguage->company,'shop_code' => $currLanguage->shop_code, 'code' => $currLanguage->shop_language_code));
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\TemplateEngine;
use Mustache_Engine;
/**
* Created by PhpStorm.
* User: bauer
* Date: 04.11.2015
* Time: 10:03
*/
class MustacheTemplateEngine extends Mustache_Engine implements TemplateEngine
{
//Empty wrapper to satisfy interface
}

View File

@@ -0,0 +1,392 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\GenericDBQueryWrapperInterface;
use mysqli_result;
/**
* Created by PhpStorm.
* User: Micha
* Date: 16.01.2015
* Time: 23:39
*/
class MySQLiQueryWrapper implements GenericDBQueryWrapperInterface {
protected $hostName;
protected $portNumber;
protected $dbName;
protected $userName;
protected $password;
protected $optionsArray;
protected $connectionObject;
protected $query = '';
protected $stmt;
protected $result;
protected $errorState = FALSE;
protected $errorMessage = '';
/**
* @param string $hostName
* @param int $portNumber
* @param string $dbName
* @param string $userName
* @param string $password
* @param array $optionsArray
*/
public function __construct( $hostName, $portNumber, $dbName, $userName, $password, $optionsArray = array() ) {
$this->hostName = ($hostName ?: 'localhost');
$this->portNumber = ($portNumber ? (int)$portNumber : 3306);
$this->dbName = ($dbName ?:'dcshop');
$this->userName = ($userName ?: 'root');
$this->password = $password;
$this->optionsArray = (is_array($optionsArray) ? $optionsArray : array());
$this->connectionObject = mysqli_init();
if(count($this->optionsArray) > 0) {
foreach($this->optionsArray as $optionPair) {
if(!is_array($optionPair) || count($optionPair) !== 2) {
$this->errorState = TRUE;
$this->errorMessage .= 'At least one entry in the options array is not an array with two entries.';
} else {
if(!$this->connectionObject->options($optionPair[0],$optionPair[1])) {
$this->errorState = TRUE;
$this->errorMessage .= $this->connectionObject->error . ' || ';
}
}
}
}
if(!($this->connectionObject->real_connect($this->hostName,$this->userName,$this->password,$this->dbName,$this->portNumber))) {
$this->errorState = TRUE;
$this->errorMessage .= $this->connectionObject->error . ' || ';
}
if (!($this->connectionObject->ping())) {
$this->errorState = TRUE;
$this->errorMessage .= $this->connectionObject->connect_error;
}
$this->connectionObject->set_charset('utf8');
}
/**
* @param string $hostName
*/
public function setHostName( $hostName ) {
$this->hostName = $hostName;
}
/**
* @param int $portNumber
*/
public function setPortNumber( $portNumber ) {
$this->portNumber = $portNumber;
}
/**
* @param string $dbName
*/
public function setDbName( $dbName ) {
$this->dbName = $dbName;
}
/**
* @param string $userName
*/
public function setUserName( $userName ) {
$this->userName = $userName;
}
/**
* @param string $password
*/
public function setPassword( $password ) {
$this->password = $password;
}
/**
* @param array $optionsArray
*/
public function setOptionsArray( array $optionsArray ) {
$this->optionsArray = $optionsArray;
}
/**
* @param string $query
*/
public function setQuery( $query ) {
$this->query = $query;
}
/**
* @return string
*/
public function getHostName() {
return $this->hostName;
}
/**
* @return int
*/
public function getPortNumber() {
return $this->portNumber;
}
/**
* @return string
*/
public function getDbName() {
return $this->dbName;
}
/**
* @return string
*/
public function getUserName() {
return $this->userName;
}
/**
* @return array
*/
public function getOptionsArray() {
return $this->optionsArray;
}
/**
* @return mixed
*/
public function getQuery() {
return $this->query;
}
/**
* @return boolean
*/
public function isErrorState() {
return $this->errorState;
}
/**
* @return string
*/
public function getErrorMessage() {
return $this->errorMessage;
}
/**
* @return bool
*/
public function reconnect() {
if(count($this->optionsArray) > 0) {
foreach($this->optionsArray as $optionPair) {
if(!is_array($optionPair) || count($optionPair) !== 2) {
$this->errorState = TRUE;
$this->errorMessage .= 'At least one entry in the options array is not an array with two entries. || ';
} else {
if(!$this->connectionObject->options($optionPair[0],$optionPair[1])) {
$this->errorState = TRUE;
$this->errorMessage .= $this->connectionObject->error . ' || ';
}
}
}
}
if(!($this->connectionObject->real_connect($this->hostName,$this->userName,$this->password,$this->dbName,$this->portNumber))) {
$this->errorState = TRUE;
$this->errorMessage .= $this->connectionObject->error . ' || ';
}
if (!($this->connectionObject->ping())) {
$this->errorState = TRUE;
$this->errorMessage .= $this->connectionObject->connect_error;
}
if($this->errorState) {
$this->query = '';
$this->stmt = NULL;
$this->result = NULL;
return FALSE;
}
$this->connectionObject->set_charset('utf8');
$this->query = '';
$this->stmt = NULL;
$this->result = NULL;
$this->errorState = FALSE;
$this->errorMessage = '';
return TRUE;
}
/**
* @return bool
*/
public function doQuery() {
if(!$this->connectionObject->ping()) {
throw new \Exception($this->connectionObject->connect_error);
return FALSE;
}
if(empty($this->query)) {
throw new \Exception('Query is not set');
return FALSE;
}
$result = $this->connectionObject->query($this->query);
if($result === TRUE) {
return TRUE;
}
if(!($result instanceof mysqli_result)) {
$this->stmt = NULL;
$this->result = NULL;
$this->errorState = TRUE;
$this->errorMessage .= $this->connectionObject->error . ' || ';
return FALSE;
}
$this->result = $result;
return TRUE;
}
/**
* @return bool
*/
public function prepareQuery() {
if(empty($this->query)) {
throw new \Exception('Query is not set.');
return FALSE;
}
if(!($stmt = $this->connectionObject->prepare($this->query))) {
$this->stmt = NULL;
$this->result = NULL;
return FALSE;
}
$this->stmt = $stmt;
return TRUE;
}
/**
* @param array $array
*
* @return bool
*/
public function bindParameters( array $array ) {
// TODO: Implement bindParameters() method.
}
/**
* @return bool
*/
public function executePreparedStatement() {
// TODO: Implement executePreparedStatement() method.
}
/**
* @param array $params
*
* @return bool
*/
public function bindResult( array $params ) {
// TODO: Implement bindReturnValues() method.
}
/**
* @return bool
*/
public function startTransaction() {
// TODO: Implement startTransaction() method.
}
/**
* @return bool
*/
public function commitTransaction() {
// TODO: Implement commitTransaction() method.
}
/**
* @return bool
*/
public function cancelTransaction() {
// TODO: Implement cancelTransaction() method.
}
/**
* @return int
*/
public function getLastInsertId() {
// TODO: Implement getLastInsertID() method.
}
/**
* @return int
*/
public function getNoOfAffectedRows() {
// TODO: Implement getNoOfAffectedRows() method.
}
/**
* @return int
*/
public function getNoOfReturnedRows() {
// TODO: Implement getNoOfReturnedRows() method.
}
/**
* @return Resource
*/
public function getResultResource() {
// TODO: Implement getResultResource() method.
}
/**
* @return array
*/
public function getResultArray() {
// TODO: Implement getResultArray() method.
}
/**
* @return array
*/
public function getNextRow() {
// TODO: Implement getNextRow() method.
}
public function rollbackTransaction()
{
// TODO: Implement rollbackTransaction() method.
}
/**
* @param $string
*/
public function escapeString($string)
{
// TODO: Implement escapeString() method.
}
public function closeStatement()
{
// TODO: Implement closeStatement() method.
}
public function inTransaction()
{
// TODO: Implement inTransaction() method.
}
}

View File

@@ -0,0 +1,745 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/8/2015
* Time: 1:48 PM
*/
class NAVDateFormulaManagement
{
const REGEX_PATTERN_EXPRESSION = '/^[\+\-]{0,1}(?:(?:[0-9]+(?:D|T|WD|WT|W|M|Q|Y|J))|(?:(?:D|T|WD|WT|W|M|Q|Y|J)[0-9]+)|(?:[CL]{1}(?:D|T|WD|WT|W|M|Q|Y|J)))(?:[\+\-]{1}(?:(?:[0-9]+(?:D|T|WD|WT|W|M|Q|Y|J))|(?:(?:D|T|WD|WT|W|M|Q|Y|J)[0-9]+)|(?:[CL]{1}(?:D|T|WD|WT|W|M|Q|Y|J))))*$/';
const REGEX_PATTERN_SUBEXPRESSION = '/([\+\-]{0,1}(?:(?:[0-9]+(?:D|T|WD|WT|W|M|Q|Y|J))|(?:(?:D|T|WD|WT|W|M|Q|Y|J)[0-9]+)|(?:[CL]{1}(?:D|T|WD|WT|W|M|Q|Y|J))))/';
const REGEX_PATTERN_SIGN = '/^([\+\-]{1})/';
const REGEX_PATTERN_NO_OF_INTERVALS = '/^(?:[\+\-]{0,1})([0-9]+)/';
const REGEX_PATTERN_PREFIX = '/^(?:[\+\-]{0,1})(?:[0-9]{0,})([CL]{1})/';
const REGEX_PATTERN_INTERVAL_TERM = '/(D|T|WD|WT|W|M|Q|Y|J)/';
const REGEX_PATTERN_INTERVAL_ORDINAL = '/(?:D|T|WD|WT|W|M|Q|Y|J)([0-9]+)$/';
/**
* @param $dateExpr
* @return int
*/
public function isValidDateExpression($dateExpr)
{
return preg_match(self::REGEX_PATTERN_EXPRESSION, $dateExpr);
}
/**
* @param $subExp
* @return int
*/
public function isValidDateSubExpression($subExp)
{
return preg_match(self::REGEX_PATTERN_SUBEXPRESSION, $subExp);
}
/**
* @param $dateExpr
* @return array
* @throws \InvalidArgumentException
*/
public function getAllSubExpressions($dateExpr)
{
if (!$this->isValidDateExpression($dateExpr)) {
$sanitized = str_replace(array('<', '>'), '', $dateExpr);
throw new \InvalidArgumentException("DateFormula $sanitized is invalid.");
}
$matches = array();
$returnMatches = array();
if (preg_match_all(self::REGEX_PATTERN_SUBEXPRESSION, $dateExpr, $matches)) {
$returnMatches = $matches[0];
}
return $returnMatches;
}
/**
* @param $subExp
* @return string
* @throws \InvalidArgumentException
*/
public function getSubExpressionSign($subExp)
{
if (!$this->isValidDateSubExpression($subExp)) {
$sanitized = str_replace(array('<', '>'), '', $subExp);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$matches = array();
preg_match(self::REGEX_PATTERN_SIGN, $subExp, $matches);
if (isset($matches[0]) && $matches[0] === '-') {
return '-';
} else {
return '+';
}
}
/**
* @param $subExp
* @return int
* @throws \InvalidArgumentException
*/
public function getSubExpressionNoOfIntervals($subExp)
{
if (!$this->isValidDateSubExpression($subExp)) {
$sanitized = str_replace(array('<', '>'), '', $subExp);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$matches = array();
preg_match(self::REGEX_PATTERN_NO_OF_INTERVALS, $subExp, $matches);
if (isset($matches[1]) && (int)$matches[1] > 0) {
return (int)$matches[1];
} else {
return 0;
}
}
/**
* @param $subExp
* @return string
* @throws \InvalidArgumentException
*/
public function getSubExpressionPrefix($subExp)
{
if (!$this->isValidDateSubExpression($subExp)) {
$sanitized = str_replace(array('<', '>'), '', $subExp);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$matches = array();
preg_match(self::REGEX_PATTERN_PREFIX, $subExp, $matches);
if (isset($matches[1])) {
return 'C';
} else {
return '';
}
}
/**
* @param $subExp
* @return string
* @throws \InvalidArgumentException
*/
public function getSubExpressionIntervalTerm($subExp)
{
if (!$this->isValidDateSubExpression($subExp)) {
$sanitized = str_replace(array('<', '>'), '', $subExp);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$matches = array();
preg_match(self::REGEX_PATTERN_INTERVAL_TERM, $subExp, $matches);
if (isset($matches[1])) {
return $matches[1];
} else {
return 'CD';
}
}
/**
* @param $subExp
* @return int
* @throws \InvalidArgumentException
*/
public function getSubExpressionIntervalOrdinal($subExp)
{
if (!$this->isValidDateSubExpression($subExp)) {
$sanitized = str_replace(array('<', '>'), '', $subExp);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$matches = array();
preg_match(self::REGEX_PATTERN_INTERVAL_ORDINAL, $subExp, $matches);
if (isset($matches[1]) && (int)$matches[1] > 0) {
return (int)$matches[1];
} else {
return 0;
}
}
/**
* @param $formula
* @param \DateTime $dateTime
* @throws \InvalidArgumentException
*/
public function evaluateDateFormula($formula, \DateTime $dateTime)
{
$formula = str_replace(array('<', '>'), '', $formula);
if (!$this->isValidDateExpression($formula)) {
throw new \InvalidArgumentException('Argument ' . $formula . ' is not a valid DateFormula');
}
$subExpressions = $this->getSubExpressionArray($formula);
foreach ($subExpressions as $subExpression) {
$this->_evaluateSubExpression($subExpression, $dateTime);
}
}
/**
* @param \DateTime $referenceDateTime
* @return int
*/
public function getMinusCW(\DateTime $referenceDateTime)
{
return strtotime('last monday', strtotime('tomorrow', $referenceDateTime->getTimestamp()));
}
/**
* @param \DateTime $referenceDateTime
* @return int
*/
public function getPlusCW(\DateTime $referenceDateTime)
{
return strtotime('next sunday + 1 day', strtotime('yesterday', $referenceDateTime->getTimestamp()));
}
/**
* @param \DateTime $referenceDateTime
* @return int
*/
public function getMinusCM(\DateTime $referenceDateTime)
{
return strtotime('first day of this month', $referenceDateTime->getTimestamp());
}
/**
* @param \DateTime $referenceDateTime
* @return int
*/
public function getPlusCM(\DateTime $referenceDateTime)
{
return strtotime('last day of this month', $referenceDateTime->getTimestamp());
}
/**
* @param \DateTime $referenceDateTime
* @return mixed
*/
public function getMinusCQ(\DateTime $referenceDateTime)
{
return $this->getStartEndDateForCurrentQuarter($referenceDateTime)[0];
}
/**
* @param \DateTime $referenceDateTime
* @return mixed
*/
public function getPlusCQ(\DateTime $referenceDateTime)
{
return $this->getStartEndDateForCurrentQuarter($referenceDateTime)[1];
}
/**
* @param \DateTime $referenceDateTime
* @return int
*/
public function getMinusCY(\DateTime $referenceDateTime)
{
$year = date('Y', $referenceDateTime->getTimestamp());
return strtotime('01-January-' . $year);
}
/**
* @param \DateTime $referenceDateTime
* @return int
*/
public function getPlusCY(\DateTime $referenceDateTime)
{
$year = date('Y', $referenceDateTime->getTimestamp());
return strtotime('31-December-' . $year);
}
/**
* @param $subExp
* @param \DateTime $dateRef
*/
protected function _evaluateSubExpression($subExp, \DateTime $dateRef)
{
if (!$this->isValidDateSubExpression($subExp)) {
$sanitized = str_replace(array('<', '>'), '', $subExp);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$sign = $this->getSubExpressionSign($subExp);
$prefix = $this->getSubExpressionPrefix($subExp);
$noOfIntervals = $this->getSubExpressionNoOfIntervals($subExp);
$intervalTerm = $this->getSubExpressionIntervalTerm($subExp);
$intervalOrdinal = $this->getSubExpressionIntervalOrdinal($subExp);
if ($prefix === 'C' || $prefix === 'L') {
$prefix = 'C';
}
if ($intervalTerm === 'T') {
$intervalTerm = 'D';
} elseif ($intervalTerm === 'WT') {
$intervalTerm = 'WD';
} elseif ($intervalTerm === 'J') {
$intervalTerm = 'Y';
}
//NAV handles WD/WT when preceded by a number as 'D'
if ($noOfIntervals > 0 && $intervalTerm == 'WD') {
$intervalTerm = 'D';
}
if ($prefix === 'C') {
if ($intervalTerm === 'D' || $intervalTerm === 'WD') {
//Day is equal to reference date, thus no change in $dateRef
return;
}
$callableNamePrefix = 'get';
$signNamePart = 'Plus';
if ($sign === '-') {
$signNamePart = 'Minus';
}
$callableName = $callableNamePrefix . $signNamePart . $prefix . $intervalTerm;
$newTimestamp = $this->{$callableName}($dateRef);
$dateRef->setTimestamp($newTimestamp);
} elseif ($prefix === '' && $noOfIntervals > 0) {
$this->traverseDateAndMutateRef($sign, $noOfIntervals, $intervalTerm, $dateRef);
} elseif ($prefix === '' && $intervalOrdinal > 0) {
$this->mutateDateTimeForOrdinalExpression($sign, $intervalTerm, $intervalOrdinal, $dateRef);
}
}
/**
* @param $sign
* @param $intervalTerm
* @param $intervalOrdinal
* @param \DateTime $dateRef
*/
public function mutateDateTimeForOrdinalExpression($sign, $intervalTerm, $intervalOrdinal, \DateTime $dateRef)
{
$combined = $sign . $intervalTerm . $intervalOrdinal;
if (!$this->isValidDateSubExpression($combined)) {
$sanitized = str_replace(array('<', '>'), '', $combined);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
switch ($intervalTerm) {
case 'D':
$this->mutateDateTimeForDayOrdinal($sign, $intervalOrdinal, $dateRef);
break;
case 'T':
$this->mutateDateTimeForDayOrdinal($sign, $intervalOrdinal, $dateRef);
break;
case 'WD':
$this->mutateDateTimeForWeekDayOrdinal($sign, $intervalOrdinal, $dateRef);
break;
case 'WT':
$this->mutateDateTimeForWeekDayOrdinal($sign, $intervalOrdinal, $dateRef);
break;
case 'W':
$this->mutateDateTimeForWeekOrdinal($sign, $intervalOrdinal, $dateRef);
break;
case 'M':
$this->mutateDateTimeForMonthOrdinal($sign, $intervalOrdinal, $dateRef);
break;
case 'Q':
$this->mutateDateTimeForQuarterOrdinal($sign, $intervalOrdinal, $dateRef);
break;
case 'Y':
$this->mutateDateTimeForYearOrdinal($sign, $intervalOrdinal, $dateRef);
break;
case 'J':
$this->mutateDateTimeForYearOrdinal($sign, $intervalOrdinal, $dateRef);
break;
}
}
/**
* @param $sign
* @param $intervalOrdinal
* @param \DateTime $dateRef
*/
protected function mutateDateTimeForDayOrdinal($sign, $intervalOrdinal, \DateTime $dateRef)
{
$intervalTerm = 'D';
$combined = $sign . $intervalTerm . $intervalOrdinal;
if (!$this->isValidDateSubExpression($combined)) {
$sanitized = str_replace(array('<', '>'), '', $combined);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$dateRefInitTimestamp = $dateRef->getTimestamp();
$dateRefInitMidnightTimestamp = strtotime($dateRef->format('d.m.Y'));
$dateRefInitDayOfMonthNo = strftime('%d', $dateRefInitTimestamp);
$dateRefInitMonthNo = strftime('%m', $dateRefInitTimestamp);
$dateRefInitYear4digit = strftime('%Y', $dateRefInitTimestamp);
$intermediateTimestamp = strtotime(sprintf('%02d.%02d.%4d', $intervalOrdinal, $dateRefInitMonthNo, $dateRefInitYear4digit));
$finalTimestamp = $intermediateTimestamp;
if ($sign === '+' && (($intermediateTimestamp <= $dateRefInitMidnightTimestamp))) {
$calcMonthNo = (int)$dateRefInitMonthNo + 1;
$calcYearNo = $dateRefInitYear4digit;
if ($calcMonthNo === 13) {
$calcMonthNo = '01';
$calcYearNo = (int)$calcYearNo + 1;
}
$finalTimestamp = strtotime(sprintf('%02d.%02d.%4d', $intervalOrdinal, $calcMonthNo, $calcYearNo));
} elseif ($sign === '-' && ($intermediateTimestamp <= $dateRefInitMidnightTimestamp)) {
$finalTimestamp = $intermediateTimestamp;
} elseif ($sign === '-' && ($intermediateTimestamp > $dateRefInitMidnightTimestamp)) {
$calcMonthNo = (int)$dateRefInitDayOfMonthNo - 1;
$calcYearNo = $dateRefInitYear4digit;
if ($calcMonthNo === 0) {
$calcMonthNo = '12';
$calcYearNo = (int)$calcYearNo - 1;
}
$finalTimestamp = strtotime(sprintf('%02d.%02d.%4d', $intervalOrdinal, $calcMonthNo, $calcYearNo));
}
$dtStr = date("c", $finalTimestamp);
$newDateTime = new \DateTime($dtStr);
$dateRef->setTimestamp($newDateTime->getTimestamp());
}
/**
* @param $sign
* @param $intervalOrdinal
* @param \DateTime $dateRef
*/
protected function mutateDateTimeForWeekDayOrdinal($sign, $intervalOrdinal, \DateTime $dateRef)
{
$intervalTerm = 'WD';
$combined = $sign . $intervalTerm . $intervalOrdinal;
if (!$this->isValidDateSubExpression($combined)) {
$sanitized = str_replace(array('<', '>'), '', $combined);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$dateRefInitTimestamp = $dateRef->getTimestamp();
$dateRefInitWeekNo = $dateRef->format('W');
$dateRefInitDayOfWeek = date("N", $dateRefInitTimestamp);
$dateRefInitYear4digit = $dateRef->format('Y');
$startEndOfRefWeekArr = $this->getStartAndEndDateTimestampForWeek($dateRefInitWeekNo, $dateRefInitYear4digit);
$startOfRefWeek = $startEndOfRefWeekArr[0];
$startOfPrevWeek = strtotime("-1 weeks", $startOfRefWeek);
$startOfNextWeek = strtotime("+1 weeks", $startOfRefWeek);
$targetTimestamp = $startOfNextWeek;
if(($sign === '+' && ($dateRefInitDayOfWeek < $intervalOrdinal))||($sign === '-' && ($dateRefInitDayOfWeek > $intervalOrdinal))) {
$targetTimestamp = $startOfRefWeek;
} elseif($sign === '-') {
$targetTimestamp = $startOfPrevWeek;
}
if ($intervalOrdinal > 1) {
$noOfDaysToTraverse = $intervalOrdinal - 1;
$targetTimestamp = strtotime("+$noOfDaysToTraverse days", $targetTimestamp);
}
$dtStr = date("c", $targetTimestamp);
$newDateTime = new \DateTime($dtStr);
$dateRef->setTimestamp($newDateTime->getTimestamp());
}
/**
* @param $sign
* @param $intervalOrdinal
* @param \DateTime $dateRef
*/
protected function mutateDateTimeForWeekOrdinal($sign, $intervalOrdinal, \DateTime $dateRef)
{
$intervalTerm = 'W';
$combined = $sign . $intervalTerm . $intervalOrdinal;
if (!$this->isValidDateSubExpression($combined)) {
$sanitized = str_replace(array('<', '>'), '', $combined);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$dateRefInitTimestamp = $dateRef->getTimestamp();
$dateRefInitYear4digit = strftime('%Y', $dateRefInitTimestamp);
$dateRefInitWeekNo = strftime('%V', $dateRefInitTimestamp);
$finalTimestamp = strtotime(sprintf("%4dW%02d", $dateRefInitYear4digit, $intervalOrdinal));
if ($sign === '' && ($dateRefInitWeekNo >= $intervalOrdinal)) {
$calcYearNo = (int)$dateRefInitYear4digit + 1;
$finalTimestamp = strtotime(sprintf("%4dW%02d", $calcYearNo, $intervalOrdinal));
} elseif ($sign === '-' && ($dateRefInitWeekNo < $intervalOrdinal)) {
$calcYearNo = (int)$dateRefInitYear4digit - 1;
$finalTimestamp = strtotime(sprintf("%4dW%02d", $calcYearNo, $intervalOrdinal));
}
$dtStr = date("c", $finalTimestamp);
$newDateTime = new \DateTime($dtStr);
$dateRef->setTimestamp($newDateTime->getTimestamp());
}
/**
* @param $sign
* @param $intervalOrdinal
* @param \DateTime $dateRef
* @throws \InvalidArgumentException
*/
protected function mutateDateTimeForMonthOrdinal($sign, $intervalOrdinal, \DateTime $dateRef)
{
$intervalTerm = 'M';
$combined = $sign . $intervalTerm . $intervalOrdinal;
if (!$this->isValidDateSubExpression($combined)) {
$sanitized = str_replace(array('<', '>'), '', $combined);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$dateRefInitTimestamp = $dateRef->getTimestamp();
$dateRefInitYear4digit = strftime('%Y', $dateRefInitTimestamp);
$dateRefInitMonthNo = strftime('%m', $dateRefInitTimestamp);
$newDateTime = \DateTime::createFromFormat('d.m.Y', sprintf('%02d.%02d.%04d', '01', $intervalOrdinal, $dateRefInitYear4digit));
if ($sign === '' && ($dateRefInitMonthNo >= $intervalOrdinal)) {
$calcYearNo = (int)$dateRefInitYear4digit + 1;
$newDateTime = \DateTime::createFromFormat('d.m.Y', sprintf('%02d.%02d.%04d', '01', $intervalOrdinal, $calcYearNo));
} elseif ($sign === '-' && ($dateRefInitMonthNo < $intervalOrdinal)) {
$calcYearNo = (int)$dateRefInitYear4digit - 1;
$newDateTime = \DateTime::createFromFormat('d.m.Y', sprintf('%02d.%02d.%04d', '01', $intervalOrdinal, $calcYearNo));
}
$dateRef->setTimestamp($newDateTime->getTimestamp());
}
/**
* @param $sign
* @param $intervalOrdinal
* @param \DateTime $dateRef
*/
protected function mutateDateTimeForQuarterOrdinal($sign, $intervalOrdinal, \DateTime $dateRef)
{
$intervalTerm = 'Q';
$combined = $sign . $intervalTerm . $intervalOrdinal;
if (!$this->isValidDateSubExpression($combined)) {
$sanitized = str_replace(array('<', '>'), '', $combined);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$dateRefInitTimestamp = $dateRef->getTimestamp();
$dateRefInitYear4digit = strftime('%Y', $dateRefInitTimestamp);
$dateRefInitMonthNo = strftime('%m', $dateRefInitTimestamp);
$dateRefInitQuarterNo = ceil($dateRefInitMonthNo / 3);
if ($intervalOrdinal < 1) {
$intervalOrdinal = 1;
}
if ($intervalOrdinal > 4) {
$intervalOrdinal = 4;
}
$endMonthNoTargetQuarter = ($intervalOrdinal * 3);
$startMonthTargetQuarter = $endMonthNoTargetQuarter - 2;
$newDateTime = \DateTime::createFromFormat('d.m.Y', sprintf('%02d.%02d.%04d', '01', $startMonthTargetQuarter, $dateRefInitYear4digit));
if ($sign === '' && ($dateRefInitQuarterNo >= $intervalOrdinal)) {
$calcYearNo = (int)$dateRefInitYear4digit + 1;
$newDateTime = \DateTime::createFromFormat('d.m.Y', sprintf('%02d.%02d.%04d', '01', $startMonthTargetQuarter, $calcYearNo));
} elseif ($sign === '-' && ($dateRefInitQuarterNo < $intervalOrdinal)) {
$calcYearNo = (int)$dateRefInitYear4digit - 1;
$newDateTime = \DateTime::createFromFormat('d.m.Y', sprintf('%02d.%02d.%04d', '01', $startMonthTargetQuarter, $calcYearNo));
}
$dateRef->setTimestamp($newDateTime->getTimestamp());
}
/**
* @param $sign
* @param $intervalOrdinal
* @param \DateTime $dateRef
*/
protected function mutateDateTimeForYearOrdinal($sign, $intervalOrdinal, \DateTime $dateRef)
{
$intervalTerm = 'Y';
$combined = $sign . $intervalTerm . $intervalOrdinal;
if (!$this->isValidDateSubExpression($combined)) {
$sanitized = str_replace(array('<', '>'), '', $combined);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$dateRefInitTimestamp = $dateRef->getTimestamp();
$dateRefInitYear4digit = strftime('%y', $dateRefInitTimestamp);
$dateRefInitLast2Digits = substr($dateRefInitYear4digit, -2, 2);
$dateRefInitFirst2Digits = substr($dateRefInitYear4digit, 0, 2);
if ($intervalOrdinal >= $dateRefInitLast2Digits) {
$newYearStr = $dateRefInitFirst2Digits . $intervalOrdinal;
} else {
$newYearStr = sprintf('%02d%02d', ((int)$dateRefInitFirst2Digits + 1), $intervalOrdinal);
};
$newDateTime = \DateTime::createFromFormat('d.m.Y', sprintf('%02d.%02d.%04d', '01', '01', $newYearStr));
$dateRef->setTimestamp($newDateTime->getTimestamp());
}
/**
* @param $sign
* @param $noOfTraversals
* @param $intervalTerm
* @param \DateTime $dateRef
* @throws \InvalidArgumentException
*/
public function traverseDateAndMutateRef($sign, $noOfTraversals, $intervalTerm, \DateTime $dateRef)
{
$combined = $sign . $noOfTraversals . $intervalTerm;
if (!$this->isValidDateSubExpression($combined)) {
$sanitized = str_replace(array('<', '>'), '', $combined);
throw new \InvalidArgumentException("SubExpression $sanitized is invalid.");
}
$strtotimeIntervalTerm = $this->getIntervalTermStrtotimeMapping($intervalTerm);
$newTime = strtotime("$sign $noOfTraversals $strtotimeIntervalTerm", $dateRef->getTimestamp());
$dtStr = date("c", $newTime);
$newDateTime = new \DateTime($dtStr);
$dateRef->setTimestamp($newDateTime->getTimestamp());
}
/**
* @param $formula
* @return mixed
* @throws \InvalidArgumentException
*/
public function getSubExpressionArray($formula)
{
if (!$this->isValidDateExpression($formula)) {
throw new \InvalidArgumentException('Argument is not a valid DateFormula');
}
$firstChar = mb_substr($formula, 0);
$lastChar = mb_substr($formula, -1);
if ($firstChar === '<' && $lastChar === '>') {
$formula = rtrim(ltrim($formula, '<'), '>');
}
$subExpressionRegex = '/([\+\-]{0,1}(?:(?:[0-9]+(?:D|T|WD|WT|W|M|Q|Y|J))|(?:(?:D|T|WD|WT|W|M|Q|Y|J)[0-9]+)|(?:[CL]{1}(?:D|T|WD|WT|W|M|Q|Y|J))))/';
$allSubExpressions = array();
preg_match_all($subExpressionRegex, $formula, $allSubExpressions);
return $allSubExpressions[0];
}
/**
* @param \DateTime $dateTime
* @return int
*/
public function getCurrentQuarterStartDate(\DateTime $dateTime)
{
$currentMonth = date('m', $dateTime->getTimestamp());
$currentYear = date('Y', $dateTime->getTimestamp());
$startDate = $dateTime->getTimestamp();
if ($currentMonth >= 1 && $currentMonth <= 3) {
$startDate = strtotime('1-January-' . $currentYear); // timestamp or 1-January 12:00:00 AM
} elseif ($currentMonth >= 4 && $currentYear <= 6) {
$startDate = strtotime('1-April-' . $currentYear); // timestamp or 1-April 12:00:00 AM
} elseif ($currentMonth >= 7 && $currentMonth <= 9) {
$startDate = strtotime('1-July-' . $currentYear); // timestamp or 1-July 12:00:00 AM
} elseif ($currentMonth >= 10 && $currentMonth <= 12) {
$startDate = strtotime('1-October-' . $currentYear); // timestamp or 1-October 12:00:00 AM
}
return $startDate;
}
/**
* @param \DateTime $dateTime
* @return int
*/
public function getNextQuarterStartDate(\DateTime $dateTime)
{
$currentMonth = date('m', $dateTime->getTimestamp());
$currentYear = date('Y', $dateTime->getTimestamp());
$startDate = $dateTime->getTimestamp();
if ($currentMonth >= 1 && $currentMonth <= 3) {
$startDate = strtotime('1-April-' . $currentYear); // timestamp or 1-April 12:00:00 AM
} elseif ($currentMonth >= 4 && $currentYear <= 6) {
$startDate = strtotime('1-July-' . $currentYear); // timestamp or 1-July 12:00:00 AM
} elseif ($currentMonth >= 7 && $currentMonth <= 9) {
$startDate = strtotime('1-October-' . $currentYear); // timestamp or 1-October 12:00:00 AM
} elseif ($currentMonth >= 10 && $currentMonth <= 12) {
$startDate = strtotime('1-January-' . $currentYear); // timestamp or 1-January 12:00:00 AM
}
return $startDate;
}
/**
* @param \DateTime $dateTime
* @return array
*/
public function getStartEndDateForCurrentQuarter(\DateTime $dateTime)
{
$dtTimeStamp = $dateTime->getTimestamp();
$currentMonth = date('m', $dtTimeStamp);
$currentYear = date('Y', $dtTimeStamp);
$startDate = $dtTimeStamp;
$endDate = $dtTimeStamp;
if ($currentMonth >= 1 && $currentMonth <= 3) {
$startDate = strtotime('1-January-' . $currentYear); // timestamp or 1-Januray 12:00:00 AM
$endDate = strtotime('1-April-' . $currentYear); // timestamp or 1-April 12:00:00 AM means end of 31 March
} elseif ($currentMonth >= 4 && $currentMonth <= 6) {
$startDate = strtotime('1-April-' . $currentYear); // timestamp or 1-April 12:00:00 AM
$endDate = strtotime('1-July-' . $currentYear); // timestamp or 1-July 12:00:00 AM means end of 30 June
} elseif ($currentMonth >= 7 && $currentMonth <= 9) {
$startDate = strtotime('1-July-' . $currentYear); // timestamp or 1-July 12:00:00 AM
$endDate = strtotime('1-October-' . $currentYear); // timestamp or 1-October 12:00:00 AM means end of 30 September
} elseif ($currentMonth >= 10 && $currentMonth <= 12) {
$startDate = strtotime('1-October-' . $currentYear); // timestamp or 1-October 12:00:00 AM
$endDate = strtotime('1-January-' . ($currentYear + 1)); // timestamp or 1-January Next year 12:00:00 AM means end of 31 December this year
}
$dateArr = array($startDate, $endDate);
return $dateArr;
}
/**
* @param $term
* @return string
* @throws \InvalidArgumentException
*/
public function getIntervalTermStrtotimeMapping($term)
{
$matches = array();
if (!preg_match(self::REGEX_PATTERN_INTERVAL_TERM, $term, $matches)) {
throw new \InvalidArgumentException("$term is not a valid interval-term.");
}
$term = $matches[1];
$strtotimeExp = '';
switch ($term) {
case 'D':
$strtotimeExp = 'days';
break;
case 'T':
$strtotimeExp = 'days';
break;
case 'WD':
$strtotimeExp = 'weekdays';
break;
case 'WT':
$strtotimeExp = 'weekdays';
break;
case 'W':
$strtotimeExp = 'weeks';
break;
case 'M':
$strtotimeExp = 'months';
break;
case 'Q':
$strtotimeExp = 'months';
break; //special case - calculation by consumer is necessary
case 'Y':
$strtotimeExp = 'years';
break;
case 'J':
$strtotimeExp = 'years';
break;
}
return $strtotimeExp;
}
/**
* @param $week
* @param $year
* @return array
*/
public function getStartAndEndDateTimestampForWeek($week, $year)
{
$startDateTime = new \DateTime();
$startDateTime->setISODate($year, $week);
$endDateTime = new \DateTime();
$endDateTime->setISODate($year, $week, 7);
return array($startDateTime->getTimestamp(), $endDateTime->getTimestamp());
}
/**
* @param \DateTime $dateRef
* @param string $direction
*/
public function mutateToClosestWorkDay(\DateTime $dateRef,$direction = '>') {
$dateRefInitTimestamp = $dateRef->getTimestamp();
$dateRefInitDayOfWeek = date("N", $dateRefInitTimestamp);
if($dateRefInitDayOfWeek <= 5) {
return;
} else {
$targetTimestamp = strtotime('+1 weekdays',$dateRefInitTimestamp);
if($direction === '<') {
$targetTimestamp = strtotime('+1 weekdays',$dateRefInitTimestamp);
}
$dateRef->setTimestamp($targetTimestamp);
}
}
}

View File

@@ -0,0 +1,207 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\SessionFlashMessageBag;
/**
* Created by PhpStorm.
* User: bauer
* Date: 19.09.2016
* Time: 11:35
*/
class NativeSessionFlashMessageBag implements SessionFlashMessageBag
{
const STORAGE_KEY_SUFFIX = '_MSGBAG';
private $isInitialized = false;
/**
* @var string
*/
private $storageKeyPrefix;
/**
* @var string
*/
private $storageKey;
/**
* @var array messages
*/
private $messages;
/**
* NativeSessionFlashMessageBag constructor.
* @param string $storageKeyPrefix
*/
public function __construct($storageKeyPrefix = '')
{
$this->guardForActiveSession();
$this->storageKeyPrefix = $storageKeyPrefix;
$this->initialize($storageKeyPrefix);
}
/**
* sets message(s) for a given type
* @param string $type
* @param string|array $message
*/
public function set($type, $message)
{
$this->guardForActiveSession();
if (is_string($message)) {
$this->setMessage($type,$message);
} elseif(is_array($message)) {
foreach ($message as $msg) {
$this->setMessage($type,$msg);
}
}
}
/**
* Gets and clears messages of a given type
* @param string $type
* @param array $default
* @return array
*/
public function get($type, array $default = [])
{
$this->guardForActiveSession();
return $this->getMessages($type,true,$default);
}
/**
* Gets and clears messages of all types
* @return mixed
*/
public function all()
{
$this->guardForActiveSession();
return $this->getMessages();
}
/**
* Gets messages of given type without clearing
* @param string $type
* @param array $default
* @return array
*/
public function peek($type, array $default = [])
{
$this->guardForActiveSession();
return $this->getMessages($type,false,$default);
}
/**
* Gets messages of all types without clearing
* @return mixed
*/
public function peekAll()
{
$this->guardForActiveSession();
return $this->getMessages('',false);
}
/**
* @param string $type
* @return bool
*/
public function has($type)
{
$this->guardForActiveSession();
return (array_key_exists($type,$this->messages) && count($this->messages[$type]) > 0);
}
/**
* Gets all defined types
* @return array
*/
public function keys()
{
$this->guardForActiveSession();
return array_keys($this->messages);
}
/**
* Clears all messages
*/
public function clear()
{
$this->guardForActiveSession();
$this->messages = [];
$this->persistToSession();
}
/**
* @return bool
*/
private function isSessionActive()
{
return session_status() === PHP_SESSION_ACTIVE;
}
private function guardForActiveSession()
{
if (!$this->isSessionActive()) {
throw new \BadMethodCallException('Session must be active in order to use SessionFlashMessageBag.');
}
}
/**
* @param $storageKeyPrefix
*/
private function initialize($storageKeyPrefix)
{
if (!$this->isInitialized) {
$sessionID = session_id();
$this->storageKeyPrefix = $storageKeyPrefix ? $storageKeyPrefix . '_' : '';
$this->storageKey = $this->storageKeyPrefix . $sessionID . self::STORAGE_KEY_SUFFIX;
if (array_key_exists($this->storageKey, $_SESSION) && is_array($_SESSION[$this->storageKey])) {
$this->messages = $_SESSION[$this->storageKey];
}
$this->isInitialized = true;
}
}
/**
* @param $type
* @param $message
*/
private function setMessage($type, $message)
{
if (!array_key_exists($type,$this->messages) || !is_array($this->messages[$type]) || !in_array($message,$this->messages[$type],true)) {
$this->messages[$type][] = $message;
$this->persistToSession();
}
}
/**
* @param string $type
* @param bool $clear
* @param array $defaultValue
* @return array|mixed
*/
private function getMessages($type = '', $clear = true, $defaultValue = [])
{
if ($type !== '') {
$msgs = &$this->messages[$type];
} else {
$msgs = &$this->messages;
}
$returnArr = $defaultValue;
if (is_array($msgs) && count($msgs) > 0) {
$returnArr = $msgs;
}
if ($clear) {
$msgs = [];
}
$this->persistToSession();
return $returnArr;
}
private function persistToSession()
{
$_SESSION[$this->storageKey] = $this->messages;
}
}

View File

@@ -0,0 +1,845 @@
<?php
namespace DynCom\mysyde\common\classes;
use ReflectionClass;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/12/2015
* Time: 3:42 AM
*/
class NewValidator
{
const ORDINAL_COMPARATOR_EQ = '=';
const ORDINAL_COMPARATOR_LT = '<';
const ORDINAL_COMPARATOR_LTE = '<=';
const ORDINAL_COMPARATOR_GT = '>';
const ORDINAL_COMPARATOR_GTE = '>=';
const DECIMAL_SEPARATOR_COMMA = ',';
const DECIMAL_SEPARATOR_POINT = '.';
const DATE_FORMAT_ISO_8601 = 'yyyy-mm-dd';
const DATE_FORMAT_DDMMYY_DASHES = 'dd-mm-yy';
const DATE_FORMAT_DDMMYYYY_DASHES = 'dd-mm-yyyy';
const DATE_FORMAT_DDMMYY_DOTS = 'dd.mm.yy';
const DATE_FORMAT_DDMMYYYY_DOTS = 'dd.mm.yyyy';
const DATE_FORMAT_DDMMYY_SLASHES = 'dd/mm/yy';
const DATE_FORMAT_DDMMYYYY_SLASHES = 'dd/mm/yyyy';
const DATE_FORMAT_MMDDYY_DASHES = 'mm-dd-yy';
const DATE_FORMAT_MMDDYYYY_DASHES = 'mm-dd-yyyy';
const DATE_FORMAT_MMDDYY_DOTS = 'mm.dd.yy';
const DATE_FORMAT_MMDDYYYY_DOTS = 'mm.dd.yyyy';
const DATE_FORMAT_MMDDYY_SLASHES = 'mm/dd/yy';
const DATE_FORMAT_MMDDYYYY_SLASHES = 'mm/dd/yyyy';
const DATETIME_FORMAT_ISO_8601 = 'yyyy-mm-ddThh:mm:ss';
const DATETIME_FORMAT_MYSQL = 'yyyy-mm-dd hh:mm:ss';
const TIME_FORMAT_COLON = 'hh:mm:ss';
const CONF_RULE_SEPARATOR = '|';
const CONF_RULE_VALUE_SEPARATOR = ':';
const ERROR_MSG_CONST_SUFFIX = '_ERROR_MSG_CODE';
const RULE_REQUIRED = 'required';
const RULE_REQUIRED_ERROR_MSG_CODE = 'validation_error_required_not_set';
const RULE_EMAIL = 'email';
const RULE_EMAIL_ERROR_MSG_CODE = 'validation_error_email_invalid';
const RULE_NAME = 'name';
const RULE_NAME_ERROR_MSG_CODE = 'validation_error_name_invalid';
const RULE_ADDR_STREET = 'addrstreet';
const RULE_ADDR_STREET_ERROR_MSG_CODE = 'validation_error_addr_street_invalid';
const RULE_ADDR_STREET_NO = 'addrstreetno';
const RULE_ADDR_STREET_NO_ERROR_MSG_CODE = 'validation_error_addr_street_no_invalid';
const RULE_ADDR_STREET_PLUS_NO = 'addrstreetplusno';
const RULE_ADDR_STREET_PLUS_NO_ERROR_MSG_CODE = 'validation_error_addr_street_plus_no_invalid';
const RULE_ADDR_CITY = 'addrcity';
const RULE_ADDR_CITY_ERROR_MSG_CODE = 'validation_error_addr_city_invalid';
const RULE_ADDR_ZIP = 'addrzip';
const RULE_ADDR_ZIP_ERROR_MSG_CODE = 'validation_error_addr_zip_invalid';
const RULE_STR_WS_DASH_DOT = 'strwsdashdot';
const RULE_STR_WS_DASH_DOT_ERROR_MSG_CODE = 'validation_error_str_ws_dash_dot_invalid';
const RULE_STR_WS_DASH_DOT_PAR = 'strwsdashdotparen';
const RULE_STR_WS_DASH_DOT_PAR_ERROR_MSG_CODE = 'validation_error_str_ws_dash_dot_par_invalid';
const RULE_URL = 'url';
const RULE_URL_ERROR_MSG_CODE = 'validation_error_url_invalid';
const RULE_ALPHA = 'Alpha';
const RULE_ALPHA_ERROR_MSG_CODE = 'validation_error_alpha_invalid';
const RULE_ALPHA_CAPS = 'ALPHA';
const RULE_ALPHA_CAPS_ERROR_MSG_CODE = 'validation_error_alpha_caps_invalid';
const RULE_ALPHA_SMALL = 'alpha';
const RULE_ALPHA_SMALL_ERROR_MSG_CODE = 'validation_error_alpha_small_invalid';
const RULE_DIGIT = 'digit';
const RULE_DIGIT_ERROR_MSG_CODE = 'validation_error_alpha_digit_invalid';
const RULE_DECIMAL = 'decimal';
const RULE_DECIMAL_ERROR_MSG_CODE = 'validation_error_decimal_invalid';
const RULE_ALNUM = 'alnum';
const RULE_ALNUM_ERROR_MSG_CODE = 'validation_error_alnum_invalid';
const RULE_GENERAL_TEXT = 'text';
const RULE_GENERAL_TEXT_ERROR_MSG_CODE = 'validation_error_text_general_invalid';
const RULE_DATE = 'date';
const RULE_DATE_ERROR_MSG_CODE = 'validation_error_date_invalid';
const RULE_DATETIME = 'dateTime';
const RULE_DATETIME_ERROR_MSG_CODE = 'validation_error_datetime_invalid';
const RULE_MIN_LENGTH = 'minlen';
const RULE_MIN_LENGTH_ERROR_MSG_CODE = 'validation_error_minlen_exceeded';
const RULE_MAX_LENGTH = 'maxlen';
const RULE_MAX_LENGTH_ERROR_MSG_CODE = 'validation_error_maxlen_exceeded';
const RULE_MIN_NUMERIC = 'minnum';
const RULE_MIN_NUM_ERROR_MSG_CODE = 'validation_error_minnum_exceeded';
const RULE_MAX_NUMERIC = 'maxnum';
const RULE_MAX_NUM_ERROR_MSG_CODE = 'validation_error_maxnum_exceeded';
const RULE_MIN_DATE = 'mindate';
const RULE_MIN_DATE_ERROR_MSG_CODE = 'validation_error_mindate_exceeded';
const RULE_MAX_DATE = 'maxdate';
const RULE_MAX_DATE_ERROR_MSG_CODE = 'validation_error_max_date_exceeded';
const RULE_CUST_REGEX = 'regex';
const RULE_CUST_REGEX_ERROR_MSG_CODE = 'validation_error_cust_regex_unmatched';
const RULE_REQUIRES = 'requires';
const RULE_REQUIRES_ERROR_MSG_CODE = 'validation_error_required_field_not_set';
const RULE_EXTENDS = 'extends';
const RULE_IN = 'in';
const RULE_INSTANCEOF = 'instanceof';
const RULE_FIELD = 'field';
const RULE_METHOD = 'method';
const RULE_EMPTY_ALLOWED = 'orempty';
protected $decimalSeparator = self::DECIMAL_SEPARATOR_POINT;
protected $dateFormat = self::DATE_FORMAT_DDMMYY_DOTS;
protected $timeFormat = self::TIME_FORMAT_COLON;
protected $dateTimeFormat = self::DATETIME_FORMAT_MYSQL;
protected $dateValidation = array();
protected $ruleConstants = array();
protected $data = array();
protected $rules = array();
protected $languageCode = 'de';
/**
* @param $regex
* @return bool
*/
protected function _isValidRegex($regex)
{
return (preg_match($regex, null) !== false);
}
/**
* @param $fieldName
* @param $regex
*/
public function setCustomRegexRule($fieldName, $regex)
{
if (!array_key_exists($fieldName, $this->data)) {
throw new \InvalidArgumentException(
sprintf(
'%s is not the name of a data-item.',
strip_tags($fieldName)
)
);
}
if (!$this->_isValidRegex($regex)) {
throw new \InvalidArgumentException(
sprintf(
'%s is not a valid regex.',
strip_tags($regex)
)
);
}
$callable = function ($fieldName, $fieldValue, $validationParam) {
return (preg_match($validationParam, $fieldValue) > 0);
};
$this->rules[$fieldName][self::RULE_CUST_REGEX] = array('callable' => &$callable, 'ruleValue' => $regex);
}
protected function _setDefaultDateFormatValidation()
{
$this->dateValidation = array(
self::DATE_FORMAT_ISO_8601 => function ($dataSourceString) {
return $this->_isValidByDateFormat('Y-m-d', $dataSourceString);
},
self::DATE_FORMAT_DDMMYY_DASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('d-m-y', $dataSourceString);
},
self::DATE_FORMAT_DDMMYYYY_DASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('d-m-Y', $dataSourceString);
},
self::DATE_FORMAT_DDMMYY_DOTS => function ($dataSourceString) {
return $this->_isValidByDateFormat('d.m.y', $dataSourceString);
},
self::DATE_FORMAT_DDMMYYYY_DOTS => function ($dataSourceString) {
return $this->_isValidByDateFormat('d.m.Y', $dataSourceString);
},
self::DATE_FORMAT_DDMMYY_SLASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('d/m/y', $dataSourceString);
},
self::DATE_FORMAT_DDMMYYYY_SLASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('d/m/Y', $dataSourceString);
},
self::DATE_FORMAT_MMDDYY_DASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('m-d-y', $dataSourceString);
},
self::DATE_FORMAT_MMDDYYYY_DASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('m-d-Y', $dataSourceString);
},
self::DATE_FORMAT_MMDDYY_DOTS => function ($dataSourceString) {
return $this->_isValidByDateFormat('m.d.y', $dataSourceString);
},
self::DATE_FORMAT_MMDDYYYY_DOTS => function ($dataSourceString) {
return $this->_isValidByDateFormat('m.d.Y', $dataSourceString);
},
self::DATE_FORMAT_MMDDYY_SLASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('m/d/y', $dataSourceString);
},
self::DATE_FORMAT_MMDDYYYY_SLASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('m/d/Y', $dataSourceString);
},
self::DATETIME_FORMAT_ISO_8601 => function ($dataSourceString) {
return $this->_isValidByDateFormat('Y-m-dTH:i:s', $dataSourceString);
},
self::DATETIME_FORMAT_MYSQL => function ($dataSourceString) {
return $this->_isValidByDateFormat('Y-m-d H:i:s', $dataSourceString);
}
);
}
protected $ruleValidation = array();
protected function _setDefaultRuleValidation()
{
$this->ruleValidation = array(
self::RULE_REQUIRED => function () {
$fieldName = func_get_arg(0);
return array_key_exists($fieldName, $this->data);
},
self::RULE_EMAIL => function () {
$fieldValue = func_get_arg(1);
return filter_var($fieldValue, FILTER_VALIDATE_EMAIL);
},
self::RULE_NAME => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\s\-]+$/', $fieldValue) > 0);
},
self::RULE_ADDR_STREET => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\s\-\.]+$/', $fieldValue) > 0);
},
self::RULE_ADDR_STREET_NO => function () {
$fieldValue = func_get_arg(1);
return (preg_match(
'/^[[:digit:]]+[[:alpha:]]{0,1}(?:\s*\-\s*[[:digit:]]{0,}[[:alpha:]]*){0,1}$/',
$fieldValue
) > 0);
},
self::RULE_ADDR_STREET_PLUS_NO => function () {
$fieldValue = func_get_arg(1);
return (preg_match(
'/^[[:alpha:]äöüßÄÖÜ\s\-\.]+\s+[[:digit:]]+[[:alpha:]]{0,1}(?:\s*\-\s*[[:digit:]]{0,}[[:alpha:]]*){0,1}$/',
$fieldValue
) > 0);
},
self::RULE_ADDR_CITY => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\s\-\.]+$/', $fieldValue) > 0);
},
self::RULE_ADDR_ZIP => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:digit:]]{5}$/', $fieldValue) > 0);
},
self::RULE_STR_WS_DASH_DOT => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\-\.]+$/', $fieldValue) > 0);
},
self::RULE_STR_WS_DASH_DOT_PAR => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\-\.\(\)]+$/', $fieldValue) > 0);
},
self::RULE_URL => function () {
$fieldValue = func_get_arg(1);
return filter_var($fieldValue, FILTER_VALIDATE_URL);
},
self::RULE_ALPHA => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alpha:]äöüßÄÖÜ]+$/', $fieldValue) > 0);
},
self::RULE_ALPHA_CAPS => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:upper:]ÄÖÜ]+$/', $fieldValue) > 0);
},
self::RULE_ALPHA_SMALL => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:lower:]äöüß]+$/', $fieldValue) > 0);
},
self::RULE_DIGIT => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:digit:]]+$/', $fieldValue) > 0);
},
self::RULE_DECIMAL => function () {
$fieldValue = func_get_arg(1);
return (preg_match(
'/^[[:digit:]]+(\\' . $this->decimalSeparator . '[[:digit:]]{1,})|[[:digit:]]$/',
$fieldValue
) > 0);
},
self::RULE_ALNUM => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alnum:]äöüßÄÖÜ]+$/', $fieldValue) > 0);
},
self::RULE_GENERAL_TEXT => function () {
$fieldValue = func_get_arg(1);
return (strip_tags($fieldValue) === $fieldValue);
},
self::RULE_DATE => function () {
$fieldValue = func_get_arg(1);
return ($this->dateValidation[$this->dateFormat]($fieldValue));
},
self::RULE_DATETIME => function () {
$fieldValue = func_get_arg(1);
return ($this->dateValidation[$this->dateTimeFormat]($fieldValue));
},
self::RULE_MIN_LENGTH => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
return (mb_strlen($fieldValue, 'UTF-8') >= $validationParam);
},
self::RULE_MAX_LENGTH => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
return (mb_strlen($fieldValue, 'UTF-8') <= $validationParam);
},
self::RULE_MIN_NUMERIC => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
return ((float)$fieldValue >= (float)$validationParam);
},
self::RULE_MAX_NUMERIC => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
return ((float)$fieldValue <= (float)$validationParam);
},
self::RULE_MIN_DATE => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
return $this->_dateStrHasOrdinalRelToRefDateStr(
$fieldValue,
$validationParam,
self::ORDINAL_COMPARATOR_GTE
);
},
self::RULE_MAX_DATE => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
return $this->_dateStrHasOrdinalRelToRefDateStr(
$fieldValue,
$validationParam,
self::ORDINAL_COMPARATOR_LTE
);
},
self::RULE_REQUIRES => function () {
$validationParam = func_get_arg(2);
$dataExists = array_key_exists($validationParam, $this->data);
if (!$dataExists) { return false; }
$fieldData = $this->data[$validationParam];
$isValid = true;
$dummyFieldStatusArr = [];
//If rules exist for other field, they have to be valid;
$this->_validateField($validationParam, $fieldData, $dummyFieldStatusArr, $isValid);
return $isValid;
},
self::RULE_EXTENDS => function ($fieldName, $fieldValue, $validationParam, array &$fieldStatusArr) {
$isValid = true;
$extendedRulesExists = array_key_exists($validationParam, $this->rules);
if (!$extendedRulesExists) { return $isValid; }
//Validate the data of this field against the rules of the extended Field
$this->_validateField($validationParam, $fieldValue, $fieldStatusArr, $isValid);
return $isValid;
},
self::RULE_IN => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
$validValues = json_decode($validationParam, false);
$isValid = (is_array($validValues) && in_array($fieldValue, $validValues, true));
return $isValid;
},
self::RULE_INSTANCEOF => function () {
$obj = func_get_arg(1);
$objName = func_get_arg(2);
return (is_object($obj) && ($obj instanceof $objName));
},
self::RULE_FIELD => function () {
$obj = func_get_arg(1);
$nameValueStringArr = explode('=', func_get_arg(2), 2);
$fieldName = $nameValueStringArr[0];
$fieldValue = (array_key_exists(1, $nameValueStringArr) && strlen($nameValueStringArr[1]) > 0) ?
$nameValueStringArr[1] : true;
$objValue = false;
if (is_object($obj)) {
@$objValue = $obj->$fieldName;
}
return ($objValue == $fieldValue);
},
self::RULE_METHOD => function () {
$obj = func_get_arg(1);
$nameValueStringArr = explode('=', func_get_arg(2), 2);
$methodName = $nameValueStringArr[0];
$fieldValue = (array_key_exists(1, $nameValueStringArr) && strlen($nameValueStringArr[1]) > 0) ?
$nameValueStringArr[1] : true;
$objValue = false;
if (is_object($obj)) {
@$objValue = $obj->$methodName();
}
return ($objValue == $fieldValue);
},
self::RULE_EMPTY_ALLOWED => function () {
return true;
}
);
}
protected $errorMessages = array();
protected function _setDefaultErrorMsgCallables()
{
$this->errorMessages = array(
self::RULE_REQUIRED => function ($fieldName, $fieldValue, $validationParam) {
return (array_key_exists($fieldName, $this->data));
},
self::RULE_EMAIL => function ($fieldName, $fieldValue, $validationParam) {
return filter_var($fieldValue, FILTER_VALIDATE_EMAIL);
},
self::RULE_NAME => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\s\-]+$/', $fieldValue) > 0);
},
self::RULE_ADDR_STREET => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\s\-\.]+$/', $fieldValue) > 0);
},
self::RULE_ADDR_STREET_NO => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:digit:]]+[[:alpha:]]{0,1}(?:\s*\-\s*[[:digit:]]{0,}[[:alpha:]]*){0,1}$/', $fieldValue) > 0);
},
self::RULE_ADDR_STREET_PLUS_NO => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\s\-\.]+\s+[[:digit:]]+[[:alpha:]]{0,1}(?:\s*\-\s*[[:digit:]]{0,}[[:alpha:]]*){0,1}$/', $fieldValue) > 0);
},
self::RULE_ADDR_CITY => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\s\-\.]+$/', $fieldValue) > 0);
},
self::RULE_ADDR_ZIP => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[0-9]{5}$/', $fieldValue) > 0);
},
self::RULE_STR_WS_DASH_DOT => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\-\.]+$/', $fieldValue) > 0);
},
self::RULE_STR_WS_DASH_DOT_PAR => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\-\.\(\)]+$/', $fieldValue) > 0);
},
self::RULE_URL => function ($fieldName, $fieldValue, $validationParam) {
return filter_var($fieldValue, FILTER_VALIDATE_URL);
},
self::RULE_ALPHA => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>]+$/', $fieldValue) > 0);
},
self::RULE_ALPHA_CAPS => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:upper:]<5D><><EFBFBD>]+$/', $fieldValue) > 0);
},
self::RULE_ALPHA_SMALL => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:lower:]<5D><><EFBFBD><EFBFBD>]+$/', $fieldValue) > 0);
},
self::RULE_DIGIT => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:digit:]]+$/', $fieldValue) > 0);
},
self::RULE_DECIMAL => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:digit:]]+(\\' . $this->decimalSeparator . '[[:digit:]]{1,})|[[:digit:]]$/', $fieldValue) > 0);
},
self::RULE_ALNUM => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alnum:]<5D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>]+$/', $fieldValue) > 0);
},
self::RULE_GENERAL_TEXT => function ($fieldName, $fieldValue, $validationParam) {
return (strip_tags($fieldValue) === $fieldValue);
},
self::RULE_DATE => function ($fieldName, $fieldValue, $validationParam) {
return ($this->dateValidation[$this->dateFormat]($fieldValue));
},
self::RULE_DATETIME => function ($fieldName, $fieldValue, $validationParam) {
return $this->dateValidation[$this->dateTimeFormat]($fieldValue);
},
self::RULE_MIN_LENGTH => function ($fieldName, $fieldValue, $validationParam) {
return (mb_strlen($fieldValue, 'UTF-8') >= $validationParam);
},
self::RULE_MAX_LENGTH => function ($fieldName, $fieldValue, $validationParam) {
return (mb_strlen($fieldValue, 'UTF-8') <= $validationParam);
},
self::RULE_MIN_NUMERIC => function ($fieldName, $fieldValue, $validationParam) {
return ((float)$fieldValue >= (float)$validationParam);
},
self::RULE_MAX_NUMERIC => function ($fieldName, $fieldValue, $validationParam) {
return ((float)$fieldValue <= (float)$validationParam);
},
self::RULE_MIN_DATE => function ($fieldName, $fieldValue, $validationParam) {
return $this->_dateStrHasOrdinalRelToRefDateStr($fieldValue, $validationParam, self::ORDINAL_COMPARATOR_GTE);
},
self::RULE_MAX_DATE => function ($fieldName, $fieldValue, $validationParam) {
return $this->_dateStrHasOrdinalRelToRefDateStr($fieldValue, $validationParam, self::ORDINAL_COMPARATOR_LTE);
}
);
}
protected function _setRuleConstants()
{
$ref = new ReflectionClass($this);
$constants = $ref->getConstants();
foreach ($constants as $constName => $constVal) {
if (static::strStartsWith($constName, 'RULE_')) {
$this->ruleConstants[$constName] = $constVal;
}
}
}
/**
* @param $ruleName
* @return bool
*/
public function isValidRuleName($ruleName)
{
if (!(count($this->ruleConstants) > 0)) {
$this->_setRuleConstants();
}
return in_array($ruleName, $this->ruleConstants, true);
}
/**
* @param $ruleName
* @return bool
*/
public static function isValidDefaultInlineRuleName($ruleName)
{
$arr = array(
self::RULE_REQUIRED,
self::RULE_EMAIL,
self::RULE_NAME,
self::RULE_ADDR_STREET,
self::RULE_ADDR_STREET_NO,
self::RULE_ADDR_STREET_PLUS_NO,
self::RULE_ADDR_CITY,
self::RULE_ADDR_ZIP,
self::RULE_STR_WS_DASH_DOT,
self::RULE_STR_WS_DASH_DOT_PAR,
self::RULE_URL,
self::RULE_ALPHA,
self::RULE_ALPHA_CAPS,
self::RULE_ALPHA_SMALL,
self::RULE_DIGIT,
self::RULE_DECIMAL,
self::RULE_ALNUM,
self::RULE_GENERAL_TEXT,
self::RULE_DATE,
self::RULE_DATETIME,
self::RULE_MIN_LENGTH,
self::RULE_MAX_LENGTH,
self::RULE_MIN_NUMERIC,
self::RULE_MAX_NUMERIC,
self::RULE_MIN_DATE,
self::RULE_MAX_DATE,
self::RULE_CUST_REGEX
);
return in_array($ruleName, $arr, 1);
}
/**
* @param $dateFormatString
* @param $dataSourceString
* @return bool
*/
protected function _isValidByDateFormat($dateFormatString, $dataSourceString)
{
$dateTime = \DateTime::createFromFormat($dateFormatString, $dataSourceString);
$dateTimeString = $dateTime->format($dateFormatString);
return ($dateTimeString === $dataSourceString);
}
/**
* NewValidator constructor.
* @param array $dataRules
* @param array|null $data
*/
public function __construct(array $dataRules, array $data = null)
{
$this->_setDefaultRuleValidation();
$this->_setDefaultDateFormatValidation();
if(null === $data) { $data = []; }
$this->setData($data);
if (is_array($dataRules)) {
foreach ($dataRules as $fieldName => $ruleStr) {
$this->_parseRuleString($fieldName, $ruleStr);
}
}
}
/**
* @param array $data
*/
public function setData(array $data) {
foreach($data as $dataKey => $dataVal) {
$this->data[$dataKey] = $dataVal;
}
}
/**
* @param $fieldName
* @param $ruleString
*/
protected function _parseRuleString($fieldName, $ruleString)
{
if (!array_key_exists($fieldName, $this->data)) {
throw new \InvalidArgumentException(
sprintf(
'%s is not the name of a data-item.',
strip_tags($fieldName)
)
);
}
$rules = explode(self::CONF_RULE_SEPARATOR, $ruleString);
if (!is_array($rules) || count($rules) < 1) {
throw new \InvalidArgumentException(
sprintf(
'%s is not a string of rules split by %s.',
strip_tags($rules),
self::CONF_RULE_SEPARATOR
)
);
}
foreach ($rules as $rule) {
$ruleParts = explode(self::CONF_RULE_VALUE_SEPARATOR, $rule, 2);
$ruleName = $ruleParts[0];
$ruleValue = (isset($ruleParts[1]) ? $ruleParts[1] : '');
if (self::RULE_CUST_REGEX !== $ruleName && !array_key_exists($ruleName, $this->ruleValidation)) {
throw new \InvalidArgumentException(
sprintf(
'%s is not a valid rule.',
strip_tags($ruleName)
)
);
}
if (self::RULE_CUST_REGEX === $ruleName) {
throw new \InvalidArgumentException('A custom regex-rule can only be set via method.');
}
$this->rules[$fieldName][$ruleName] = array('callable' => &$this->ruleValidation[$ruleName], 'ruleValue' => $ruleValue);
}
}
/**
* @param $dateStr
* @param $refDateStr
* @param $comparator
* @return bool
*/
protected function _dateStrHasOrdinalRelToRefDateStr($dateStr, $refDateStr, $comparator)
{
$dt = new \DateTime(strtotime($dateStr));
$dtRef = new \DateTime(strtotime($refDateStr));
switch ($comparator) {
case self::ORDINAL_COMPARATOR_EQ:
$isValid = ($dt->getTimestamp() === $dtRef->getTimestamp());
break;
case self::ORDINAL_COMPARATOR_LT:
$isValid = ($dt->getTimestamp() < $dtRef->getTimestamp());
break;
case self::ORDINAL_COMPARATOR_LTE:
$isValid = ($dt->getTimestamp() <= $dtRef->getTimestamp());
break;
case self::ORDINAL_COMPARATOR_GT:
$isValid = ($dt->getTimestamp() > $dtRef->getTimestamp());
break;
case self::ORDINAL_COMPARATOR_GTE:
$isValid = ($dt->getTimestamp() >= $dtRef->getTimestamp());
break;
default:
$isValid = ($dt->getTimestamp() === $dtRef->getTimestamp());
break;
}
return $isValid;
}
/**
* After validation, $fieldStatusArr will contain detailed information about the validation result, including rule-mismatch error-messages
* @param array|null $fieldStatusArr
* @return bool
* @throws \InvalidArgumentException
*/
public function isValid(array &$fieldStatusArr)
{
if (null === $this->data) {
throw new \InvalidArgumentException(
'Method \'Cannot check validity while data is not set\''
);
}
$isValid = true;
$statusArr = array();
foreach ($this->data as $fieldName => $fieldValue) {
$singleFieldStatusArr = [];
$this->_validateField($fieldName,$fieldValue,$singleFieldStatusArr,$isValid);
$statusArr[$fieldName] = $singleFieldStatusArr;
}
$fieldStatusArr = $statusArr;
return $isValid;
}
/**
* @param $fieldName
* @param $fieldValue
* @param $singleFieldStatusArr
* @param $isValidTotal
* @return bool
*/
protected function _validateField($fieldName, $fieldValue, &$singleFieldStatusArr, &$isValidTotal) {
$isValidField = true;
$unmatchedRules = [];
$appliedRulesString = '';
$i = 0;
if (isset($this->rules[$fieldName])) {
$emptyAllowed = (array_key_exists(self::RULE_EMPTY_ALLOWED,$this->rules[$fieldName]) || !array_key_exists(self::RULE_REQUIRED,$this->rules[$fieldName]));
if (!$emptyAllowed) {
foreach ($this->rules[$fieldName] as $ruleName => $ruleArr) {
//$fieldValue = $this->data[$fieldName];
$ruleCallable = $ruleArr['callable'];
$ruleValue = $ruleArr['ruleValue'];
if ($i > 0) {
$appliedRulesString .= self::CONF_RULE_SEPARATOR;
}
$appliedRulesString .= $ruleName;
$fieldStatusArrTMP = [];
if (!$ruleCallable($fieldName, $fieldValue, $ruleValue, $fieldStatusArrTMP)) {
$isValidField = false;
$unmatchedRules = (isset($fieldStatusArrTMP['unmatchedRules']) ? $fieldStatusArrTMP['unmatchedRules'] : []);
$unmatchedRules[] = array('ruleName' => $ruleName, 'ruleValue' => $ruleValue, 'ruleError' => $this->getRuleErrorMessage($ruleName));
$isValidTotal = false;
}
++$i;
}
}
$singleFieldStatusArr = array('value' => $fieldValue, 'valid' => $isValidField, 'appliedRules' => $appliedRulesString, 'unmatchedRules' => $unmatchedRules);
}
return $isValidField;
}
/**
* @return bool
*/
public function isInvalid()
{
$dummyArr = [];
return !($this->isValid($dummyArr));
}
/**
* @param array $rules
*/
public function setRules(array $rules)
{
if (null === $this->data) {
throw new \BadMethodCallException(
'Method \'setRules cannot be called while data is not set\''
);
}
foreach ($rules as $fieldName => $ruleStr) {
$this->_parseRuleString($fieldName, $ruleStr);
}
}
/**
* @param $ruleName
* @return mixed|string
*/
public function getRuleErrorMessage($ruleName ) {
$errorMsgConstName = $ruleName . self::ERROR_MSG_CONST_SUFFIX;
$fqn = 'static::' . $errorMsgConstName;
if (defined($fqn)) {
return constant($fqn);
} else {
return '';
}
}
/**
* @param $haystack
* @param $needle
* @return bool
*/
public static function strStartsWith($haystack, $needle)
{
// search backwards starting from haystack length characters from the end
return $needle === '' || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}
/**
* @param $haystack
* @param $needle
* @return bool
*/
public static function strEndsWith($haystack, $needle)
{
// search forward starting from end minus needle length characters
return $needle === '' || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
}
/**
* @param $dataItem
* @param $ruleString
* @return array
*/
public static function evaluateDataItemAgainstRuleString($dataItem,$ruleString) {
$dataArr = array(
'dataItem' => $dataItem
);
$ruleArr = array(
'dataItem' => $ruleString
);
$validator = new self($ruleArr, $dataArr);
$fieldStatusArr = array();
$validator->isValid($fieldStatusArr);
unset($validator);
return $fieldStatusArr;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,47 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\Entity;
use DynCom\mysyde\common\interfaces\GenericDBModelInterface;
use DynCom\mysyde\common\traits\genericDBModelTrait;
use DynCom\mysyde\common\traits\universallyGettableTrait;
/**
* Class Page
* @package DynCom\mysyde\common\classes
*/
class Page implements GenericDBModelInterface, Entity
{
use genericDBModelTrait, universallyGettableTrait;
protected $id;
protected $title;
protected $subtitle;
protected $meta_keywords;
protected $meta_description;
protected $main_language_id;
protected $active;
protected $modified_date;
protected $modified_user;
protected $validity_from;
protected $validity_to;
/**
* @param PageConfig $config
*/
public function __construct(PageConfig $config)
{
$this->config = $config;
}
/**
* @return Page
*/
public function getNullObject()
{
return new self($this->config);
}
}

View File

@@ -0,0 +1,79 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\CriteriaHelperInterface;
use DynCom\mysyde\common\interfaces\GenericCollectionInterface;
use DynCom\mysyde\common\traits\genericCollectionTrait;
/**
* Class PageCollection
* @package DynCom\mysyde\common\classes
*/
class PageCollection implements GenericCollectionInterface
{
use genericCollectionTrait;
/**
* @param PageConfig $config
* @param CriteriaHelperInterface $criteriaValidationService
*/
public function __construct(PageConfig $config, CriteriaHelperInterface $criteriaValidationService)
{
$this->elements = new \SplObjectStorage();
$this->config = $config;
$this->criteriaValidationService = $criteriaValidationService;
$this->entryClassName = $config->getModelClassName();
}
/**
* @return PageCollection
*/
public function getEmptyCollection()
{
return new self($this->config, $this->criteriaValidationService);
}
/**
* @param mixed $instance
* @param bool $idCheck
*
* @return bool
*/
public function add($instance, $idCheck = FALSE)
{
return $this->_addPage($instance, $idCheck);
}
/**
* @param Page $page
* @param bool $idCheck
* @return bool
*/
protected function _addPage(Page $page, $idCheck = FALSE)
{
return $this->_add($page, $idCheck);
}
/**
* @param mixed $instance
* @param bool $idCheck
*
* @return bool
*/
public function remove($instance, $idCheck = FALSE)
{
return $this->_removePage($instance, $idCheck);
}
/**
* @param Page $page
* @param bool $idCheck
* @return bool
*/
protected function _removePage(Page $page, $idCheck = FALSE)
{
return $this->_remove($page, $idCheck);
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\ModelDBConfigInterface;
use DynCom\mysyde\common\traits\genericConfigTrait;
/**
* Class PageConfig
* @package DynCom\mysyde\common\classes
*/
class PageConfig implements ModelDBConfigInterface
{
use genericConfigTrait;
protected $modelClassName = 'DynCom\mysyde\common\classes\Page';
protected $tableName = 'main_page';
protected $baseTableName = 'main_page';
protected $altPrimary = [];
protected $mappedFields = [
['name' => 'id', 'type' => 'int', 'maxlen' => '10'],
['name' => 'title', 'type' => 'varchar', 'maxlen' => '255'],
['name' => 'subtitle', 'type' => 'varchar', 'maxlen' => '255'],
['name' => 'meta_keywords', 'type' => 'mediumtext', 'maxlen' => '11'],
['name' => 'active', 'type' => 'tinyint', 'maxlen' => '4'],
['name' => 'modified_date', 'type' => 'int', 'maxlen' => '11'],
['name' => 'modified_user', 'type' => 'int', 'maxlen' => '11'],
['name' => 'validity_from', 'type' => 'date', 'maxlen' => ''],
];
}

View File

@@ -0,0 +1,42 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\CriteriaHelperInterface;
use DynCom\mysyde\common\interfaces\GenericDBQueryWrapperInterface;
use DynCom\mysyde\common\interfaces\Repository;
use DynCom\mysyde\common\traits\genericRepositoryTrait;
/**
* Class PageRepository
* @package DynCom\mysyde\common\classes
*/
class PageRepository implements Repository
{
use genericRepositoryTrait;
/**
* @param GenericDBQueryWrapperInterface $db
* @param PageConfig $config
* @param CriteriaHelperInterface $criteriaValidationService
* @param PageCollection $collection
* @param $cacheAll
*/
public function __construct(GenericDBQueryWrapperInterface $db, PageConfig $config, CriteriaHelperInterface $criteriaValidationService, PageCollection $collection, $cacheAll=false)
{
$this->db = $db;
$this->config = $config;
$this->criteriaValidationService = $criteriaValidationService;
$this->collection = $collection;
$this->collectionEntryClassName = $this->collection->getEntryClassName();
$this->cacheAll = $cacheAll;
}
/**
* @return Page
*/
public function getNullObject()
{
return new Page($this->config);
}
}

View File

@@ -0,0 +1,120 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Registry pattern class
*
* Example usage:
* \DynCom\mysyde\common\classes\Registry::set('translation', new \DynCom\mysyde\common\classes\Translate());
* $translation = \DynCom\mysyde\common\classes\Registry::get('translation');
*
* @package DcCMS admin
* @author Tomasz Brniak <tomaszbrniak@web.de>
* @access public
*/
class Registry {
/**
* Registry array of objects
*
* @access private
*/
private static $objects = array();
/**
* The instance of the registry
*
* @access private
*/
private static $instance;
/**
* Prevent directly access.
*
* @access private
*/
private function __construct() {
}
/**
* Get stored object
*
* @param string $_key
*
* @access public
* @static
* @return mixed
*/
public static function get( $_key ) {
static $instance;
if ($instance === null) {
$instance =self::getInstance();
}
$obj = $instance->getObject($_key);
return $obj;
}
/**
* Get object protected function you can use only
* inside from this class.
*
* @param string $_key unique key
*
* @access protected
* @return mixed
*/
protected function getObject( $_key ) {
if (isset(self::$objects[$_key])) {
return self::$objects[$_key];
}
return NULL;
}
/**
* Singleton method used to access the object
*
* @access public
*/
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Store object
*
* @param $_key
* @param $_instance
*
* @access public
* @static
* @return mixed
*/
public static function set( $_key, $_instance ) {
return self::getInstance()->storeObject($_key, $_instance);
}
/**
* Set object protected function you can use only
* inside from this class.
*
* @param string $_key
* @param mixed $_val
*
* @access protected
* @return void
*/
protected function storeObject( $_key, $_val ) {
self::$objects[$_key] = $_val;
}
/**
* Prevent clone
*
* @access private
* @return void
*/
private function __clone() {
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Micha
* Date: 22.01.2015
* Time: 05:42
*/
class RememberMeHandlerService {
protected $cookieSID;
protected $cookieToken;
/**
* RememberMeHandlerService constructor.
* @param VisitorRepository $repository
* @param $siteCode
*/
public function __construct(VisitorRepository $repository, $siteCode ) {
}
}

View File

@@ -0,0 +1,165 @@
<?php
namespace DynCom\mysyde\common\classes;
use DOMDocument;
use DOMImplementation;
use DOMNode;
use DOMText;
use DynCom\mysyde\common\interfaces\GenericViewInterface;
use Traversable;
/**
* Created by PhpStorm.
* User: Michael Bauer
* Date: 7/13/2015
* Time: 8:28 PM
*/
class RenderableElementResolver
{
const TARGET_TYPE_DOMELEMENT = 'DOMElement';
const TARGET_TYPE_STRING = 'string';
const TARGET_TYPE_PHTML = 'PHTML';
/**
* @param $typeName
* @return bool
*/
public function isAllowedTargetType($typeName) {
return(in_array($typeName,[
self::TARGET_TYPE_STRING,
self::TARGET_TYPE_DOMELEMENT,
self::TARGET_TYPE_PHTML
],true));
}
/**
* @param $element
* @param string $targetType
* @return DOMNode|DOMText|string
*/
public function resolveElement($element,$targetType = self::TARGET_TYPE_STRING) {
if($targetType === self::TARGET_TYPE_STRING) {
return $this->resolveElementToString($element);
} elseif($targetType === self::TARGET_TYPE_DOMELEMENT) {
return $this->resolveElementToDOMElement($element);
} elseif($targetType === self::TARGET_TYPE_PHTML) {
return $this->resolveElementToPHTMLField($element);
}
throw new \InvalidArgumentException(
"targetType must be string or DOMElement."
);
}
/**
* @param $element
* @return DOMNode|DOMText
*/
public function resolveElementToDOMElement($element) {
$domImpl = new DOMImplementation();
$doc = $domImpl->createDocument(null, 'html',
$domImpl->createDocumentType("html",
"-//W3C//DTD XHTML 1.0 Transitional//EN",
"/mysyde/common/xhtml11.dtd"));
$doc->formatOutput = true;
$el = $doc->createTextNode('');
//Resolve callable
$element = is_callable($element) ? $element() : $element;
//Resolve stringlike no tags
if(((is_scalar($element) || is_bool($element)) && (strip_tags($element) === (string)$element))) {
$el = &$doc->createTextNode((string)$element);
//Resolve stringlike with tags
} elseif((is_scalar($element) || is_bool($element))) {
$tmpDOM = $domImpl->createDocument(null, 'html',
$domImpl->createDocumentType("html",
"-//W3C//DTD XHTML 1.0 Transitional//EN",
"/mysyde/common/xhtml11.dtd"));
$tmpDOM->formatOutput = true;
@$tmpDOM->loadXML($element);
$el = $doc->importNode($tmpDOM->documentElement);
//Resolve DOMNodes
} elseif( $element instanceof DOMNode) {
$el = $doc->importNode($element,true);
//Resolve DOMDocument
} elseif($element instanceof DOMDocument) {
$el = $doc->importNode($element->firstChild,true);
} elseif($element instanceof GenericViewInterface) {
if(!$element->isRendered()) {
$element->render(new TemplateInserterFactory());
}
$tmpDOM = $domImpl->createDocument(null, 'html',
$domImpl->createDocumentType("html",
"-//W3C//DTD XHTML 1.0 Transitional//EN",
"/mysyde/common/xhtml11.dtd"));
$tmpDOM->formatOutput = true;
@$tmpDOM->loadXML($element->getContent());
$el = $doc->importNode($tmpDOM->documentElement);
} elseif($element instanceof Form) {
if(!$element->isFormRendered()) {
$element->render();
}
$tmpDOM = $domImpl->createDocument(null, 'html',
$domImpl->createDocumentType("html",
"-//W3C//DTD XHTML 1.0 Transitional//EN",
"/mysyde/common/xhtml11.dtd"));
$tmpDOM->formatOutput = true;
@$tmpDOM->loadXML($el = $element->getRenderedContent());
$el = $doc->importNode($tmpDOM->documentElement);
} elseif ($element instanceof Traversable) {
$arr = [];
foreach($element as $elementField) {
$arr[] = $this->resolveElementToDOMElement($elementField);
}
$DOMElWrapper = $doc->createElement('div');
foreach($arr as $arrEl) {
$DOMElWrapper->appendChild($arrEl);
}
$el = $DOMElWrapper;
}
return $el;
}
/**
* @param $element
* @return string
*/
public function resolveElementToString($element) {
$el = '';
//Resolve callable
$element = is_callable($element) ? $element() : $element;
if(((is_scalar($element) || is_bool($element)))) {
$el = (string)$element;
} elseif( $element instanceof DOMNode) {
$el = $element->ownerDocument->saveXML($element);
} elseif($element instanceof DOMDocument) {
$el = $element->saveXML($element->firstChild);
} elseif($element instanceof GenericViewInterface) {
if(!$element->isRendered()) {
$element->render(new TemplateInserterFactory());
}
$el = $element->getContent();
} elseif($element instanceof Form) {
if(!$element->isFormRendered()) {
$element->render();
}
$el = $element->getRenderedContent();
} elseif ($element instanceof Traversable) {
$wrapperString = '';
foreach($element as $elementField) {
$wrapperString .= $this->resolveElementToString($elementField);
}
}
return $el;
}
/**
* @param $element
* @return mixed
*/
public function resolveElementToPHTMLField($element) {
//Do nothing
return $element;
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace DynCom\mysyde\common\classes;
use DOMDocument;
use DOMNode;
use DOMNodeList;
use DynCom\mysyde\common\interfaces\View;
use Traversable;
/**
* Created by PhpStorm.
* User: Michael Bauer
* Date: 7/14/2015
* Time: 1:13 AM
*/
class RenderableStringTransformer
{
/**
* @param $element
* @return string
*/
public function toString($element) {
$el = '';
//Resolve callable
$element = is_callable($element) ? $element() : $element;
if(((is_scalar($element) || is_bool($element)))) {
$el = (string)$element;
} elseif($element instanceof DOMDocument) {
$el = $element->saveXML($element->firstChild);
} elseif( $element instanceof DOMNode) {
$el = $element->ownerDocument->saveXML($element);
} elseif( $element instanceof DOMNodeList) {
$wrapperString = '';
$len = $element->length;
for($i = 0;$i < $len;++$i) {
$curr = $element->item($i);
$wrapperString .= $curr->ownerDocument->saveXML($curr);
}
} elseif($element instanceof View) {
$el = $element->render();
} elseif($element instanceof Form) {
if(!$element->isFormRendered()) {
$element->render();
}
$el = $element->getRenderedContent();
} elseif ($element instanceof Traversable) {
$wrapperString = '';
foreach($element as $elementField) {
$wrapperString .= $this->toString($elementField);
}
}
return $el;
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 14.07.2015
* Time: 16:54
*/
class SalutationOptions
{
/**
* @param Templating $templating
* @return array
*/
public function getOptionsArray(Templating $templating) {
return [
$templating->getText('mr') => $templating->getText('mr'),
$templating->getText('mrs') => $templating->getText('mrs'),
$templating->getText('salutation_company') => $templating->getText('salutation_company')
];
}
}

View File

@@ -0,0 +1,117 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\CriteriaHelperInterface;
use DynCom\mysyde\common\interfaces\ModelDBConfigInterface;
/**
* Created by PhpStorm.
* User: Micha
* Date: 15.01.2015
* Time: 21:43
*/
class SelectionCriteriaHelper implements CriteriaHelperInterface {
/**
* @param array $allowedComparisons
* @param ModelDBConfigInterface $modelConfig
* @param array $criteriaArray
*
* @return bool
*/
protected $allowedComparisonOperators = array('IS NULL','IS NOT NULL','=','!=','<','>','>=','<=','IN','LIKE');
/**
* @param ModelDBConfigInterface $modelConfig
* @param array $criteriaArray
* @return bool
*/
public function validateCriteria( ModelDBConfigInterface $modelConfig, array $criteriaArray ) {
return $this->_validateCriteria($modelConfig, $criteriaArray);
}
/**
* @param ModelDBConfigInterface $modelConfig
* @param array $criteriaArray
* @return bool
*/
protected function _validateCriteria(ModelDBConfigInterface $modelConfig, array $criteriaArray ) {
$fields = $modelConfig->getMappedFields();
$fieldNames = array();
foreach ($fields as $fieldArr) {
$fieldNames[] = $fieldArr['name'];
}
if (array_depth($criteriaArray) != 3) {
return FALSE;
}
foreach ($criteriaArray as $disjunct) {
foreach ($disjunct as $conjunct) {
if (
(count($conjunct) < 2)
|| (count($conjunct) > 3)
|| (count($conjunct) > 2 && ($conjunct[1] == 'IS NULL' || $conjunct[1] == 'IS NOT NULL'))
|| ($conjunct[1] == 'IN' && !(is_array($conjunct[2])))
|| !(in_array($conjunct[0], $fieldNames))
|| !(in_array($conjunct[1], $this->allowedComparisonOperators))
|| !(in_array($conjunct[1], $modelConfig->getAllowedComparisonOperators()))
) {
return FALSE;
}
}
}
return TRUE;
}
/**
* @param ModelDBConfigInterface $mapToConfig
* @param ModelDBConfigInterface $mapFromConfig
* @param array $criteriaFieldMappings
* @return bool
*/
protected function _validateCriteriaFieldMappings( ModelDBConfigInterface $mapToConfig, ModelDBConfigInterface $mapFromConfig, array $criteriaFieldMappings ) {
$mapToFields = $mapToConfig->getMappedFields();
$mapToFieldNames = array();
foreach ($mapToFields as $toFieldArr) {
$mapToFieldNames[] = $toFieldArr['name'];
}
$mapFromFields = $mapFromConfig->getMappedFields();
$mapFromFieldNames = array();
foreach ($mapFromFields as $fromFieldArr) {
$mapFromFieldNames[] = $fromFieldArr['name'];
}
foreach ($criteriaFieldMappings as $fieldMapping) {
if (
($mapFromConfig->getAllowedComparisonOperators() !== $mapToConfig->getAllowedComparisonOperators())
|| (count($fieldMapping) < 2)
|| (count($fieldMapping) > 3)
|| (count($fieldMapping) > 2 && ($fieldMapping[1] == 'IS NULL' || $fieldMapping[1] == 'IS NOT NULL'))
|| ($fieldMapping[1] == 'IN' && !(is_array($fieldMapping[2])))
|| !(in_array($fieldMapping[0], $mapToFieldNames))
|| !(in_array($fieldMapping[1], $this->allowedComparisonOperators))
|| !(in_array($fieldMapping[1], $mapFromConfig->getAllowedComparisonOperators()))
|| ((count($fieldMapping) > 2) && !(in_array($fieldMapping[2], $mapFromFieldNames)))
) {
return FALSE;
}
}
return TRUE;
}
/**
* @param ModelDBConfigInterface $mapToConfig
* @param ModelDBConfigInterface $mapFromConfig
* @param array $criteriaFieldMappings
* @return bool
*/
public function validateCriteriaFieldMappings( ModelDBConfigInterface $mapToConfig, ModelDBConfigInterface $mapFromConfig, array $criteriaFieldMappings ) {
return $this->_validateCriteriaFieldMappings($mapToConfig,$mapFromConfig,$criteriaFieldMappings);
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 17.08.2015
* Time: 11:08
*/
class ServiceRequestID
{
protected $id;
/**
* ServiceRequestID constructor.
* @param string $prefix
*/
public function __construct($prefix = '') {
$this->id = uniqid($prefix,true);
}
/**
* @return string
*/
public function getID() {
return $this->id;
}
/**
* @return string
*/
public function __toString()
{
return $this->id;
}
public function __clone()
{
throw new \BadMethodCallException('Cloning a ServiceRequestID is forbidden');
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Micha
* Date: 22.01.2015
* Time: 05:54
*/
class SessionHandlerService {
protected $site;
protected $useSessionID;
protected $sessionName;
/**
* @param Site $site
*/
public function __construct( Site $site ) {
$this->site = $site;
if($this->site->use_session_id) {
$this->useSessionID = TRUE;
ini_set("session.use_cookies", 1);
ini_set("session.use_only_cookies", 1);
ini_set("session.use_trans_sid", 1);
}
}
protected function _setSessionName() {
}
}

View File

@@ -0,0 +1,174 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\CRUDObjectStorage;
use DynCom\mysyde\common\interfaces\Entity;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 08.07.2015
* Time: 01:28
*/
class SessionStorage implements CRUDObjectStorage
{
protected $namespace;
protected $storedIDsPerClassName = [];
/**
* @param string $namespace
*/
public function __create($namespace = 'global') {
$this->namespace = (string)$namespace;
$this->hydrateFromSession();
}
protected function hydrateFromSession() {
if( !array_key_exists($this->namespace,$_SESSION['SessionObjectStorage']) ||
!is_array($_SESSION['SessionObjectStorage'][$this->namespace]) ||
!array_key_exists('storedIDsPerClassName',$_SESSION['SessionObjectStorage'][$this->namespace]) ||
!is_array($_SESSION['SessionObjectStorage'][$this->namespace]['storedIDsPerClassName'])) return;
$this->storedIDsPerClassName = $_SESSION['SessionObjectStorage'][$this->namespace]['storedIDsPerClassName'];
}
/**
* @param Entity $entity
*/
public function create(Entity $entity) {
$id = $entity->getID();
if($id > 0) {
throw new \InvalidArgumentException(
'Entities with ID > 0 cannot be created.'
);
}
$className = get_class($entity);
$newID = 1;
if(array_key_exists($className,$this->storedIDsPerClassName) && is_array($this->storedIDsPerClassName[$className])) {
$newID = ((int)max($this->storedIDsPerClassName[$className])) + 1;
}
$entityPropArray = $entity->getAllFieldsAsArray();
$entityPropArray['id'] = $newID;
$entity->mapFromArray($entityPropArray);
$_SESSION['SessionObjectStorage'][$this->namespace][$className][$newID] = serialize($entity);
}
/**
* @param Entity $entity
*/
public function replace(Entity $entity)
{
$id = $entity->getID();
if (!$id) {
throw new \InvalidArgumentException(
'Entities without ID > 0cannot be replaced.'
);
}
$className = get_class($entity);
if (!array_key_exists($className,$this->storedIDsPerClassName) || !is_array($this->storedIDsPerClassName[$className])) {
throw new \InvalidArgumentException(
"No objects for class $className are in SessionStorage of namespace $this->namespace"
);
}
if(!array_key_exists($id,$_SESSION['SessionObjectStorage'][$this->namespace][$className])) {
throw new \InvalidArgumentException(
"No object of class $className and with ID $id exists in SessionStorage of namespace $this->namespace"
);
}
$_SESSION['SessionObjectStorage'][$this->namespace][$className][$id] = serialize($entity);
}
/**
* @param Entity $entity
*/
public function update(Entity $entity) {
$id = $entity->getID();
if (!$id) {
throw new \InvalidArgumentException(
'Entities without ID > 0 cannot be updated.'
);
}
$className = get_class($entity);
if (!array_key_exists($className,$this->storedIDsPerClassName) || !is_array($this->storedIDsPerClassName[$className])) {
throw new \InvalidArgumentException(
"No objects for class $className are in SessionStorage of namespace $this->namespace"
);
}
if(!array_key_exists($id,$_SESSION['SessionObjectStorage'][$this->namespace][$className])) {
throw new \InvalidArgumentException(
"No object of class $className and with ID $id exists in SessionStorage of namespace $this->namespace"
);
}
$altPrimaryFields = $entity->getAltPrimaryFieldNames();
$entityPropArr = $entity->getAllFieldsAsArray();
foreach($altPrimaryFields as $primaryField) {
if(array_key_exists($primaryField,$altPrimaryFields)) unset($entityPropArr[$primaryField]);
}
$storedEntity = unserialize($_SESSION['SessionObjectStorage'][$this->namespace][$className][$id]);
$storedEntity->mapFromArray($storedEntity);
$_SESSION['SessionObjectStorage'][$this->namespace][$className][$id] = serialize($storedEntity);
}
/**
* @param Entity $entity
*/
public function delete(Entity $entity) {
$id = $entity->getID();
if (!($id > 0)) {
throw new \InvalidArgumentException(
'Entities without ID cannot be deleted.'
);
}
$className = get_class($entity);
if (!array_key_exists($className,$this->storedIDsPerClassName) || !is_array($this->storedIDsPerClassName[$className])) {
throw new \InvalidArgumentException(
"No objects for class $className are in SessionStorage of namespace $this->namespace"
);
}
if(!array_key_exists($id,$_SESSION['SessionObjectStorage'][$this->namespace][$className])) {
throw new \InvalidArgumentException(
"No object of class $className and with ID $id exists in SessionStorage of namespace $this->namespace"
);
}
$sessionObjVar = $_SESSION['SessionObjectStorage'][$this->namespace][$className][$id];
unset($_SESSION['SessionObjectStorage'][$this->namespace][$className][$id],$sessionObjVar);
}
/**
* @param $id
* @param $className
* @param string $namespace
* @return bool|string
*/
public function getByID($id, $className, $namespace = 'global') {
$return = $_SESSION['SessionObjectStorage'][$namespace][$className][(int)$id] ?
serialize($_SESSION['SessionObjectStorage'][$this->namespace][$className][(int)$id]) : false;
return $return;
}
/**
* @param $id
* @param $className
* @param string $namespace
* @return bool|string
*/
public function read($id, $className, $namespace = 'global') {
return $this->getByID($id,$className,$namespace);
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\Entity;
use DynCom\mysyde\common\interfaces\GenericDBModelInterface;
use DynCom\mysyde\common\traits\genericDBModelTrait;
use DynCom\mysyde\common\traits\universallyGettableTrait;
/**
* Created by PhpStorm.
* User: Micha
* Date: 18.01.2015
* Time: 23:43
*/
class Site implements GenericDBModelInterface, Entity {
use genericDBModelTrait, universallyGettableTrait;
protected $id;
protected $code;
protected $name;
protected $std_main_language_id;
protected $login_required;
protected $login_type;
protected $google_analytics_id;
protected $use_session_id;
protected $create_xml_sitemap;
protected $site_url;
protected $is_standard_site;
protected $use_ssl;
/**
* @param SiteConfig $config
*/
public function __construct( SiteConfig $config ) {
$this->config = $config;
}
/**
* @return Site
*/
public function getNullObject() {
return new self($this->config);
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\CriteriaHelperInterface;
use DynCom\mysyde\common\interfaces\GenericCollectionInterface;
use DynCom\mysyde\common\traits\genericCollectionTrait;
/**
* Created by PhpStorm.
* User: Micha
* Date: 18.01.2015
* Time: 23:45
*/
class SiteCollection implements GenericCollectionInterface {
use genericCollectionTrait;
/**
* @param SiteConfig $config
* @param CriteriaHelperInterface $criteriaValidationService
*/
public function __construct( SiteConfig $config, CriteriaHelperInterface $criteriaValidationService ) {
$this->elements = new \SplObjectStorage();
$this->config = $config;
$this->criteriaValidationService = $criteriaValidationService;
$this->entryClassName = $config->getModelClassName();
}
/**
* @return SiteCollection
*/
public function getEmptyCollection() {
return new self($this->config,$this->criteriaValidationService);
}
/**
* @param mixed $instance
* @param bool $idCheck
*
* @return bool
*/
public function add( $instance, $idCheck = FALSE ) {
return $this->_addSite($instance, $idCheck);
}
/**
* @param Site $site
* @param bool $idCheck
* @return bool
*/
protected function _addSite( Site $site, $idCheck = FALSE ) {
return $this->_add($site, $idCheck);
}
/**
* @param mixed $instance
* @param bool $idCheck
*
* @return bool
*/
public function remove( $instance, $idCheck = FALSE ) {
return $this->_removeSite($instance,$idCheck);
}
/**
* @param Site $site
* @param bool $idCheck
* @return bool
*/
protected function _removeSite( Site $site, $idCheck = FALSE ) {
return $this->_remove($site,$idCheck);
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\ModelDBConfigInterface;
use DynCom\mysyde\common\traits\genericConfigTrait;
/**
* Created by PhpStorm.
* User: Micha
* Date: 18.01.2015
* Time: 23:40
*/
class SiteConfig implements ModelDBConfigInterface {
use genericConfigTrait;
protected $modelClassName = 'DynCom\mysyde\common\classes\Site';
protected $tableName = 'main_site';
protected $altPrimary = array('code');
protected $mappedFields = array(
array('name'=>'id','type'=>'INT'),
array('name'=>'code','type'=>'VARCHAR'),
array('name'=>'name','type'=>'VARCHAR'),
array('name'=>'std_main_language_id','type'=>'INT'),
array('name'=>'login_required','type'=>'TINYINT'),
array('name'=>'login_type','type'=>'TINYINT'),
array('name'=>'google_analytics_id','type'=>'VARCHAR'),
array('name'=>'use_session_id','type'=>'TINYINT'),
array('name'=>'create_xml_sitemap','type'=>'TINYINT'),
array('name'=>'site_url','type'=>'VARCHAR'),
array('name'=>'is_standard_site','type'=>'TINYINT'),
array('name'=>'use_ssl','type'=>'TINYINT'),
);
}

View File

@@ -0,0 +1,50 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\CriteriaHelperInterface;
use DynCom\mysyde\common\interfaces\GenericDBQueryWrapperInterface;
use DynCom\mysyde\common\interfaces\Repository;
use DynCom\mysyde\common\traits\genericRepositoryTrait;
/**
* Created by PhpStorm.
* User: Micha
* Date: 18.01.2015
* Time: 23:59
*/
class SiteRepository implements Repository {
use genericRepositoryTrait;
/**
* @param GenericDBQueryWrapperInterface $db
* @param SiteConfig $config
* @param CriteriaHelperInterface $criteriaValidationService
* @param SiteCollection $collection
* @param $cacheAll
*/
public function __construct( GenericDBQueryWrapperInterface $db, SiteConfig $config, CriteriaHelperInterface $criteriaValidationService, SiteCollection $collection, $cacheAll=false) {
$this->db = $db;
$this->config = $config;
$this->criteriaValidationService = $criteriaValidationService;
$this->collection = $collection;
$this->collectionEntryClassName = $this->collection->getEntryClassName();
}
/**
* @return mixed
*/
public function getFromRequest() {
$site = $this->findByAltPrimary(array('code' => filter_var($_GET['site'],FILTER_SANITIZE_SPECIAL_CHARS)));
return $site;
}
/**
* @return mixed
*/
public function getMainSiteIDFromRequest() {
$inst = $this->getFromRequest();
return $inst->id;
}
}

View File

@@ -0,0 +1,316 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Class Siteparts
* @package DynCom\mysyde\common\classes
*/
class Siteparts {
private static $siteparts = NULL;
/**
* Siteparts constructor.
*/
private function __construct() {
}
/**
* @return array|null
*/
public static function get() {
if (self::$siteparts === NULL) {
$translation = \DynCom\mysyde\common\classes\Registry::get('translation');
self::$siteparts = array(
1 => array( // textcontent
'header_table' => 'textcontent_header',
'line_table' => '',
'description' => $translation->get('left_text'),
'class' => 'inhalt_text',
'code' => 'textcontent',
'folder' => 'textcontent',
'is_collection'=> TRUE
),
4 => array( // Bild
'header_table' => 'image_header',
'description' => $translation->get('left_image'),
'class' => 'inhalt_image',
'code' => 'image',
'folder' => 'image'
),
15 => array( // Intranet
'header_table' => 'main_intranet_sitepart',
'line_table' => '',
'description' => $translation->get('top_intranet'),
'class' => 'intranet',
'folder' => 'intranet/siteparts',
'code' => 'intranet'
),
// 2 => array( // slideshow
// 'header_table' => 'slideshow_header',
// 'line_table' => 'slideshow_line',
// 'description' => $translation->get('left_slideshows'),
// 'class' => 'inhalt_slideshow',
// 'code' => 'slideshow',
// 'folder' => 'slideshow',
// 'is_collection'=> TRUE
// ),
// 4 => array( // Accordion
// 'header_table' => 'slidecontent_header',
// 'line_table' => 'slidecontent_line',
// 'description' => $translation->get('left_slidecontent'),
// 'class' => 'inhalt_accordion',
// 'code' => 'slidecontent',
// 'folder' => 'slidecontent'
// ),
5 => array( // Dateigalerie
'header_table' => 'filegallery_header',
'line_table' => 'filegallery_line',
'description' => $translation->get('left_filecontent'),
'class' => 'inhalt_files',
'code' => 'filegallery',
'folder' => 'filegallery',
'is_collection'=> TRUE
),
6 => array( // Bildergalerie
'header_table' => 'gallery_header',
'line_table' => 'gallery_line',
'description' => $translation->get('left_imagegallery'),
'class' => 'inhalt_bildergalerie',
'code' => 'gallery',
'folder' => 'gallery',
'is_collection'=> TRUE
),
// 7 => array( // scrollleiste
// 'header_table' => 'scrollbar_header',
// 'line_table' => 'scrollbar_line',
// 'description' => $translation->get('left_scrollbars'),
// 'class' => 'inhalt_scrollbar',
// 'code' => 'magicscroll',
// 'folder' => 'magicscroll'
// ),
// 8 => array( // Google maps
// 'header_table' => 'google_maps_header',
// 'line_table' => 'google_maps_line',
// 'description' => $translation->get('left_googlemaps'),
// 'class' => 'inhalt_maps',
// 'code' => 'googlemaps',
// 'folder' => 'googlemaps'
// ),
// 9 => array( // Facebook Inhalte
// 'header_table' => 'facebook_header',
// 'line_table' => '',
// 'description' => $translation->get('left_facebook'),
// 'class' => 'inhalt_facebook',
// 'code' => 'facebook',
// 'folder' => 'facebook'
// ),
10 => array( // Youtube Inhalte
'header_table' => 'youtube_header',
'line_table' => '',
'description' => $translation->get('left_youtube'),
'class' => 'inhalt_youtube',
'code' => 'youtube',
'folder' => 'youtube',
'is_collection'=> TRUE
),
// 11 => array( // Externe inhalte
// 'header_table' => 'iframe_header',
// 'line_table' => '',
// 'description' => $translation->get('left_extern'),
// 'class' => 'inhalt_iframe',
// 'code' => 'iframe',
// 'folder' => 'iframe'
// ),
//FAQ Modul
16 => array(
'header_table' => 'main_faq_header',
'line_table' => '',
'description' => $translation->get('faq'),
'class' => 'inhalt_faq',
'folder' => 'faq',
'code' => 'faq',
'is_collection'=> TRUE
),
//Forwarding/Weiterleitung
17 => array(
'header_table' => 'forwarding_header',
'line_table' => '',
'description' => $translation->get('left_forwarding'),
'folder' => 'forwarding',
'class' => 'inhalt_forwarding',
'code' => 'forwarding'
),
// 18 => array( // Kontaktformular
// 'header_table' => 'contactform_header',
// 'line_table' => 'contactform_line',
// 'description' => $translation->get('left_multistep_contactforms'),
// 'class' => 'inhalt_contact',
// 'code' => 'multistep_forms',
// 'folder' => 'contactform'
// )
3 => array( // Kontaktformular
'header_table' => 'contactform_header',
'line_table' => 'contactform_line',
'description' => $translation->get('left_contactforms'),
'class' => 'inhalt_contact',
'code' => 'contactform',
'folder' => 'contactform',
'is_collection'=> TRUE
),
);
}
// Shopmenu
static $instance;
if ($instance === null) {
$instance = new self();
}
// self::create_module_siteparts(19);
return self::$siteparts;
}
public static function getCustom()
{
$translation = \DynCom\mysyde\common\classes\Registry::get('translation');
self::$siteparts = array(
1 => array( // textcontent
'header_table' => 'textcontent_header',
'line_table' => '',
'description' => $translation->get('left_text'),
'class' => 'inhalt_text',
'code' => 'textcontent',
'folder' => 'textcontent'
),
// 2 => array( // slideshow
// 'header_table' => 'slideshow_header',
// 'line_table' => 'slideshow_line',
// 'description' => $translation->get('left_slideshows'),
// 'class' => 'inhalt_slideshow',
// 'code' => 'slideshow',
// 'folder' => 'slideshow'
// ),
// 3 => array( // Kontaktformular
// 'header_table' => 'contactform_header',
// 'line_table' => 'contactform_line',
// 'description' => $translation->get('left_contactforms'),
// 'class' => 'inhalt_contact',
// 'code' => 'contactform',
// 'folder' => 'contactform'
// ),
// 4 => array( // Accordion
// 'header_table' => 'slidecontent_header',
// 'line_table' => 'slidecontent_line',
// 'description' => $translation->get('left_slidecontent'),
// 'class' => 'inhalt_accordion',
// 'code' => 'slidecontent',
// 'folder' => 'slidecontent'
// ),
5 => array( // Dateigalerie
'header_table' => 'filegallery_header',
'line_table' => 'filegallery_line',
'description' => $translation->get('left_filecontent'),
'class' => 'inhalt_files',
'code' => 'filegallery',
'folder' => 'filegallery'
),
6 => array( // Bildergalerie
'header_table' => 'gallery_header',
'line_table' => 'gallery_line',
'description' => $translation->get('left_imagegallery'),
'class' => 'inhalt_bildergalerie',
'code' => 'gallery',
'folder' => 'gallery'
),
// 9 => array( // Facebook Inhalte
// 'header_table' => 'facebook_header',
// 'line_table' => '',
// 'description' => $translation->get('left_facebook'),
// 'class' => 'inhalt_facebook',
// 'code' => 'facebook',
// 'folder' => 'facebook'
// ),
10 => array( // Youtube Inhalte
'header_table' => 'youtube_header',
'line_table' => '',
'description' => $translation->get('left_youtube'),
'class' => 'inhalt_youtube',
'code' => 'youtube',
'folder' => 'youtube'
),
// 11 => array( // Externe inhalte
// 'header_table' => 'iframe_header',
// 'line_table' => '',
// 'description' => $translation->get('left_extern'),
// 'class' => 'inhalt_iframe',
// 'code' => 'iframe',
// 'folder' => 'iframe'
// ),
// 15 => array( // Newsletter
// 'header_table' => 'newsletter_sitepart',
// 'line_table' => '',
// 'description' => $translation->get('left_newsletter_sitepart'),
// 'class' => 'newsletter_sitepart',
// 'code' => 'newsletter_sitepart',
// 'folder' => 'newsletter'
// ),
);
return self::$siteparts;
}
public function create_module_siteparts($nr){
$translation = \DynCom\mysyde\common\classes\Registry::get('translation');
$query = "SELECT * FROM main_module WHERE has_sitepart = 1 AND active = 1";
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
while ($row = @mysqli_fetch_assoc($result)) {
$code = $row['code'];
self::$siteparts[$nr] = array(
// $nr => array( // Custom Modules
'header_table' => $code.'_header',
'line_table' => '',
'description' => $translation->get('left_'.$code),
'class' => 'inhalt_'.$code,
'code' => $code,
'folder' => $code
);
// );
$nr++;
}
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\PasswordCheckerInterface;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 13.01.2015
* Time: 13:56
*/
class StdMD5PasswordCheckerStrategy implements PasswordCheckerInterface {
/**
* @param $storedPass
* @param $inputPass
*
* @return bool
*/
public function isValid( $storedPass, $inputPass ) {
return $this->_isValid($storedPass, $inputPass);
}
/**
* @param $storedPass
* @param $inputPass
*
* @return bool
*/
protected function _isValid( $storedPass, $inputPass ) {
$stored = trim((string)$storedPass);
$input = trim((string)$inputPass);
return (strlen($stored) > 0 && strlen($input) > 0 && $input === md5($stored));
}
}

View File

@@ -0,0 +1,126 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\abstracts\TemplateInserterBase;
use DynCom\mysyde\common\interfaces\DOMTemplate;
use DynCom\mysyde\common\interfaces\GenericViewInterface;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/22/2015
* Time: 6:02 PM
*/
class TemplateDOMInserter extends TemplateInserterBase {
protected $prefix = 'tmplinsert-';
/**
* TemplateDOMInserter constructor.
* @param DOMTemplate $template
* @param array $fieldData
* @param bool $allowTags
* @param string $replacementAttrPrefix
*/
public function __construct(DOMTemplate $template, array $fieldData, $allowTags = false, $replacementAttrPrefix = 'tmplinsert-') {
$this->allowTags = false;
$this->template = $template;
$this->allowTags = (bool)$allowTags;
$this->fieldData = (($this->_validateFieldData($fieldData)) ? $fieldData : array());
if(strip_tags($replacementAttrPrefix) === $replacementAttrPrefix) {
$this->prefix = $replacementAttrPrefix;
}
}
/**
* @param array $fieldValues
* @return bool
*/
protected function _validateFieldData(array $fieldValues) {
foreach($fieldValues as $key => $value) {
if(
!($value instanceof \DOMNode) &&
!($value instanceof GenericViewInterface) &&
!($value instanceof Form) &&
!($this->allowTags && is_scalar($value)) &&
!(!$this->allowTags && (strip_tags($value) === (string)$value))
) {
return false;
}
}
return true;
}
public function insertData() {
$doc = $this->template->getDOMDocument();
$XPath = new \DOMXPath($doc);
$query = "//@*[starts-with(name(),'{$this->prefix}')]";
$nodeList = $XPath->query($query);
$nodeArr = [];
$len = $nodeList->length;
$el = $doc->createTextNode('');
for($i = 0;$i <= $len;++$i) {
$node = $nodeList->item($i);
$attrName = $node->nodeName;
$fieldName = str_replace($this->prefix, '', $attrName);
$owner = $node->parentNode;
if($owner instanceof \DOMElement) {
$owner->removeAttribute($attrName);
$nodeArr[$fieldName] = $owner;
}
}
foreach($this->fieldData as $key => $val) {
//Resolve callable
$val = is_callable($val) ? $val() : $val;
//Resolve stringlike no tags
if(((is_scalar($val) || is_bool($val)) && (strip_tags($val) === (string)$val))) {
$el = $doc->createTextNode((string)$val);
//Resolve stringlike with tags
} elseif((is_scalar($val) || is_bool($val))) {
$domImpl = new \DOMImplementation();
$tmpDoc = $domImpl->createDocument(null, 'html',
$domImpl->createDocumentType("html",
"-//W3C//DTD XHTML 1.0 Transitional//EN",
"/mysyde/common/xhtml11.dtd"));
$tmpDoc->formatOutput = true;
@$tmpDoc->loadXML((string)$val);
$el = $doc->importNode($tmpDoc->documentElement);
unset($tmpDoc);
//Resolve DOMDocument
} elseif($val instanceof \DOMDocument) {
$el = $doc->importNode($val->firstChild,true);
//Resolve DOMNodes
} elseif( $val instanceof \DOMNode) {
$el = $doc->importNode($val,true);
//Resolve Sub-Views
} elseif($val instanceof GenericViewInterface) {
if(!$val->isRendered()) {
$val->render(new TemplateInserterFactory());
}
$el = $val->getContent();
//Resolve Forms
} elseif($val instanceof Form) {
if(!$val->isFormRendered()) {
$val->render();
}
$renderedVal = $val->getDOMDocument();
$el = $doc->importNode($renderedVal->documentElement->firstChild,true);
}
$nodeArr[$key]->appendChild($el);
}
$this->template->setRenderedContent($doc->saveXML($doc->documentElement));
}
/**
* @param $prefix
*/
public function setReplacementDataPrefix($prefix) {
$this->prefix = strip_tags($prefix);
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\abstracts\TemplateInserterBase;
use DynCom\mysyde\common\interfaces\PHTMLTemplate;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/22/2015
* Time: 11:23 PM
*/
class TemplateDefaultInserter extends TemplateInserterBase {
protected $model;
/**
* TemplateDefaultInserter constructor.
* @param PHTMLTemplate $template
* @param array $viewModel
* @param bool $allowTags
*/
public function __construct(PHTMLTemplate $template, $viewModel, $allowTags = false) {
$this->template = $template;
$this->model = $viewModel;
$this->allowTags = (bool)$allowTags;
}
/**
* @param array $fieldValues
* @return bool
*/
protected function _validateFieldData(array $fieldValues) {
return true;
}
public function insertData() {
$path = $this->template->getPHTMLPath();
if(file_exists(realpath($path))) {
ob_start();
include($path);
$content = ob_get_clean();
} else {
throw new \InvalidArgumentException("No file under '" . $path . "'.");
}
$this->template->setRenderedContent($content);
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\DOMTemplate;
use DynCom\mysyde\common\interfaces\PHTMLTemplate;
use DynCom\mysyde\common\interfaces\PlainTemplate;
use DynCom\mysyde\common\interfaces\Template;
use DynCom\mysyde\common\interfaces\ViewModel;
/**
* Created by PhpStorm.
* User: Michael Bauer
* Date: 7/13/2015
* Time: 11:45 PM
*/
class TemplateInserter
{
/**
* @var RenderableElementResolver
*/
protected $resolver;
/**
* TemplateInserter constructor.
* @param RenderableElementResolver $resolver
*/
public function __construct(RenderableElementResolver $resolver) {
$this->resolver = $resolver;
}
/**
* @param Template $template
* @param ViewModel $viewModel
*/
public function insertViewModelIntoTemplate(Template $template, ViewModel $viewModel) {
$targetType = $this->getTargetType($template);
$renderedFields = $this->resolveFields($template,$viewModel,$targetType);
switch($targetType) {
case RenderableElementResolver::TARGET_TYPE_STRING:
$rawContent = '';
break;
case RenderableElementResolver::TARGET_TYPE_PHTML:
break;
case RenderableElementResolver::TARGET_TYPE_DOMELEMENT:
break;
default:
throw new \InvalidArgumentException('Template must be either of type plain, PHTML or DOM');
break;
}
}
/**
* @param Template $template
* @return string
*/
protected function getTargetType(Template $template) {
$targetType = RenderableElementResolver::TARGET_TYPE_STRING;
if($template instanceof PlainTemplate) {
$targetType = RenderableElementResolver::TARGET_TYPE_STRING;
} elseif($template instanceof PHTMLTemplate) {
$targetType = RenderableElementResolver::TARGET_TYPE_PHTML;
} elseif($template instanceof DOMTemplate) {
$targetType = RenderableElementResolver::TARGET_TYPE_DOMELEMENT;
}
return $targetType;
}
/**
* @param Template $template
* @param ViewModel $viewModel
* @param $targetType
* @return array
*/
protected function resolveFields(Template $template, ViewModel $viewModel, $targetType) {
$renderedTemplateFields = [];
$templateFields = $template->getFields();
$viewModelFields = $viewModel->getData();
foreach($templateFields as $templateFieldName) {
if(array_key_exists($templateFieldName,$viewModelFields)) {
$renderedTemplateFields[$templateFieldName] = $this->resolver->resolveElement($viewModelFields[$templateFieldName],$targetType);
}
}
return $renderedTemplateFields;
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\DOMTemplate;
use DynCom\mysyde\common\interfaces\PHTMLTemplate;
use DynCom\mysyde\common\interfaces\PlainTemplate;
use DynCom\mysyde\common\interfaces\Template;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/23/2015
* Time: 1:21 AM
*/
class TemplateInserterFactory {
/**
* @param Template $template
* @param array $fieldData
* @param bool $allowTags
* @param string $delimiter
* @param string $prefix
* @return TemplateDefaultInserter|TemplateDOMInserter|TemplateStringInserter
*/
public function getInserter(Template $template, array $fieldData, $allowTags = true, $delimiter = '%', $prefix = 'tmplinsert-') {
//Default is PHTML-Template
if($template instanceof PHTMLTemplate) {
$inserter = new TemplateDefaultInserter($template,(object)$fieldData,true);
} elseif($template instanceof PlainTemplate) {
$inserter = new TemplateStringInserter($template,$fieldData,true,$delimiter);
} elseif($template instanceof DOMTemplate) {
$inserter = new TemplateDOMInserter($template,$fieldData,true,$prefix);
}
if(!isset($inserter)) {
throw new \InvalidArgumentException('Template is not an allowed type. Allowed types: Default, String, DOM.');
}
return $inserter;
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\abstracts\TemplateInserterBase;
use DynCom\mysyde\common\interfaces\GenericViewInterface;
use DynCom\mysyde\common\interfaces\PlainTemplate;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/18/2015
* Time: 10:52 PM
*/
class TemplateStringInserter extends TemplateInserterBase {
const DELIMITER_PERCENT = '%';
const DELIMITER_TILDE = '~';
const DELIMITER_PIPE = '~';
protected $allowedDelimiters = array(
self::DELIMITER_PERCENT,
self::DELIMITER_TILDE,
self::DELIMITER_PIPE
);
protected $delimiter = '%';
/**
* TemplateStringInserter constructor.
* @param PlainTemplate $template
* @param array $fieldData
* @param bool $allowTags
* @param string $delimiter
*/
public function __construct(PlainTemplate $template, array $fieldData, $allowTags = false, $delimiter = '%') {
$this->template = $template;
$this->fieldData = (($this->_validateFieldData($fieldData)) ? $fieldData : array());
$this->allowTags = (bool)$allowTags;
if(isset($delimiter) && (in_array($delimiter,$this->allowedDelimiters,true))) {
$this->delimiter = $delimiter;
}
}
/**
* @param array $fieldValues
* @return bool
*/
protected function _validateFieldData(array $fieldValues) {
foreach($fieldValues as $key => $value) {
if(
($this->allowTags && !is_scalar($value)) ||
(!$this->allowTags && (!is_scalar($value) ||
(strip_tags($value) !== (string)$value)))) {
return false;
}
}
return true;
}
public function insertData() {
$content = $this->template->getTemplateString();
foreach($this->fieldData as $key => $val) {
$token = $this->delimiter . $key . $this->delimiter;
$val = is_callable($val) ? $val() : $val;
$valIsDOMDocument = $val instanceof \DOMDocument;
$valIsDOMNode = $val instanceof \DOMNode;
$valIsView = $val instanceof GenericViewInterface;
if($valIsDOMNode) {
$val = $val->ownerDocument->saveXML($val);
} elseif($valIsDOMDocument) {
$val = $val->saveXML($val->documentElement);
} elseif($valIsView) {
if($val->isRendered) $val = $val->getContent();
else {
$val->render(new TemplateInserterFactory());
$val = $val->getContent();
}
}
$content = str_replace($token,$val,$content);
}
$this->template->setRenderedContent($content);
}
/**
* @param $delimiter
*/
public function setReplacementDelimiter($delimiter) {
if(in_array($delimiter,$this->allowedDelimiters,true)) {
$this->delimiter = $delimiter;
}
}
}

View File

@@ -0,0 +1,531 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\dcShop\interfaces\TemplatingInterface;
use DynCom\mysyde\dcShop\interfaces\TextProviderInterface;
/**
* Class Templating
*/
class Templating implements TemplatingInterface, TextProviderInterface {
protected $tmpFile;
protected $error;
protected $content;
protected $HTMLSnippetProvider;
protected $locTextConstants;
protected $templateDirs = array();
protected $view;
/**
* @param HTMLSnippetProvider $snippetProvider
* @param array $locTextConstants
*/
public function __construct( HTMLSnippetProvider $snippetProvider, array $locTextConstants ) {
$this->HTMLSnippetProvider = $snippetProvider;
$this->locTextConstants = $locTextConstants;
}
/**
* @param $path
*
* @return bool
*/
public function registerTemplateDir( $path ) {
return $this->_registerTemplateDir($path);
}
/**
* @param $path
* @return bool
* @throws \Exception
*/
protected function _registerTemplateDir( $path ) {
if (!is_dir($path)) {
throw new \Exception('Given path is not a valid directory!');
}
$this->templateDirs[] = $path;
return TRUE;
}
/**
* @param $fileName
*
* @return bool
*/
public function includeTemplateFileByName( $fileName ) {
return $this->_includeTemplateFileByName($fileName);
}
/**
* @param array $locTextConstants
*/
public function updateLocTextConstants(array $locTextConstants) {
$this->locTextConstants = $locTextConstants;
}
/**
* @param $fileName
* @return bool
* @throws \Exception
*/
protected function _includeTemplateFileByName( $fileName ) {
if (empty($fileName)) {
return FALSE;
}
if (count($this->templateDirs) == 0) {
throw new \Exception('No template directories registered!');
}
for ($i = (count($this->templateDirs) - 1); $i >= 0; ++$i) {
$fileRealpath = realpath($this->templateDirs[$i]) . DIRECTORY_SEPARATOR . $fileName;
if (file_exists($fileRealpath) && is_readable($fileRealpath)) {
if (isset($this->view)) {
$this->view->includeTemplateHere($fileRealpath);
} else {
include($fileRealpath);
}
return TRUE;
}
}
return FALSE;
}
/**
* @param $name
*
* @return bool|mixed|null
*/
public function getText( $name ) {
return $this->_getText($name);
}
/**
* @param $name
*
* @return bool|mixed|null
*/
protected function _getText( $name ) {
$value = $this->HTMLSnippetProvider->getText($name);
if (isset($value)) {
return $this->HTMLSnippetProvider->getText($name);
} elseif (isset($this->locTextConstants[$name])) {
return $this->locTextConstants[$name];
}
return $name;
}
/**
* @param $name
*
* @return mixed|void
*/
public function printText( $name ) {
$this->_printText($name);
}
/**
* @param $name
*
* @return bool
*/
protected function _printText( $name ) {
$value = $this->HTMLSnippetProvider->getText($name);
if (isset($value)) {
$this->HTMLSnippetProvider->printText($name);
} elseif (isset($this->locTextConstants[$name])) {
echo $this->locTextConstants[$name];
}
return FALSE;
}
/**
* @param $file
*
* @return mixed|void
*/
public function setTemplateFileByPath( $file ) {
$this->_setTemplateFileByPath($file);
}
/**
* @param $filePath
*
* @return bool
*/
protected function _setTemplateFileByPath( $filePath ) {
if (!file_exists($filePath)) {
$error = 'No template file found!';
$this->error = $error;
throw new \Exception($this->error);
return FALSE;
} else {
$this->tmpFile = $filePath;
}
$this->content = "";
if ($this->_readTemplate()) {
return TRUE;
}
return FALSE;
}
/**
* @return bool
*/
protected function _readTemplate() {
$file = @fopen($this->tmpFile, "r");
if (!$file) {
throw new \Exception('Template file does not exist or could not be opened for reading');
return FALSE;
} else {
while (!feof($file)) {
$temp = fgets($file, 4096);
$this->content .= $temp;
}
}
return TRUE;
}
/**
* @param $string
*
* @return mixed|void
*/
public function setTemplateString( $string ) {
$this->_setTemplateString($string);
}
/**
* @param $string
*
* @return bool
*/
protected function _setTemplateString( $string ) {
$preppedString = (string)$string;
if (strlen($preppedString) > 0) {
$this->content = $preppedString;
return TRUE;
}
throw new \Exception('No template string');
return FALSE;
}
/**
* @param $title
* @param $value
*
* @return mixed|void
*/
public function replace( $title, $value ) {
$this->_replace($title, $value);
}
/**
* @param $title
* @param $value
*/
protected function _replace( $title, $value ) {
$this->content = str_replace("{" . $title . "}", $value, $this->content);
}
/**
* @param array $arr
*
* @return mixed|void
*/
public function replaceArray( array $arr ) {
$this->_replaceArray($arr);
}
/**
* @param array $arr
*/
protected function _replaceArray( array $arr ) {
foreach ($arr as $replacement) {
if (isset($replacement['title']) && isset($replacement['value'])) {
$title = (string)$replacement['title'];
$value = (string)$replacement['value'];
$this->_replace($title, $value);
}
}
}
/**
*
*/
public function printContent() {
$this->_printContent();
}
/**
*
*/
protected function _printContent() {
echo $this->content;
}
/**
*
*/
public function returnContent() {
$this->_returnContent();
}
/**
* @return mixed
*/
protected function _returnContent() {
return $this->content;
}
/**
*
*/
public function reset() {
$this->_reset();
}
/**
*
*/
protected function _reset() {
$this->content = NULL;
$this->error = NULL;
$this->tmpFile = NULL;
}
/**
* @param $fileName
*
* @return bool
*/
public function setTemplateFileByName( $fileName ) {
return $this->_setTemplateFileByName($fileName);
}
/**
* @param $fileName
*
* @return bool
*/
protected function _setTemplateFileByName( $fileName ) {
if (count($this->templateDirs) == 0) {
throw new \Exception('No template directories registered!');
return FALSE;
}
for ($i = (count($this->templateDirs) - 1); $i >= 0; --$i) {
$dir = realpath($this->templateDirs[$i]) . DIRECTORY_SEPARATOR . $fileName;
if (file_exists($dir)) {
$this->tmpFile = $dir;
$this->content = "";
if ($this->_readTemplate()) {
return TRUE;
}
return FALSE;
}
}
throw new \Exception('Template File not found');
return FALSE;
}
/**
*
*/
public function readTemplate() {
$this->_readTemplate();
}
/**
*
*/
public function deleteNonReplaced() {
$this->_deleteNonReplaced();
}
/**
*
*/
protected function _deleteNonReplaced() {
$sanitized = preg_replace("/\{[^\}]*\}/", "", $this->content);
$this->content = $sanitized;
}
/**
*
*/
public function deleteNonReplacedWithInnerWrapper() {
$this->_deleteNonReplacedWithInnerWrapper();
}
/**
*
*/
protected function _deleteNonReplacedWithInnerWrapper() {
$sanitized1 = preg_replace("/(<([A-Za-z][a-zA-Z0-9]*)\b[^>]*>[\r\n\t\s]*)\{[^\}]*\}([\r\n\t\s]*<\/\2>)/", "", $this->content);
$sanitized2 = preg_replace("/\{[^\}]*\}/", "", $sanitized1);
$this->content = $sanitized2;
}
/**
*
*/
public function deleteNonReplacedWithAttrs() {
$this->_deleteNonReplacedWithAttrs();
}
/**
*
*/
protected function _deleteNonReplacedWithAttrs() {
$sanitized = preg_replace('/(?:<[^>])?([\w\-.:]*\s*=\s*){0,1}([\'"]{0,1}\{[^\}]+?\}[\'"]{0,1}\s*)/', '', $this->content);
$this->content = $sanitized;
}
/**
* @param $string
*
* @return mixed
*/
public function stringCleanupEmptyAttributes( $string ) {
return $this->_stringCleanupEmptyAttributes($string);
}
/**
* @param $string
*
* @return mixed
*/
protected function _stringCleanupEmptyAttributes( $string ) {
//Cleanup unreplaced or empty named attributes, i.e. all patterns like: emptyatTtr1_but-e="]{SOMETHING}" - alternatively with single quotes and/or nothing between quotes
$sanitized1 = preg_replace('/(\b[a-zA-Z][a-zA-Z_\-0-9]+\=)([\'"])((?:\{[^}]*\}|))(\2)(\s*)/', '', $string);
//Cleanup unreplaced non-named attributes, i.e. all {SOMETHING}-patterns that are neither within quotation-marks nor between a closing and opening bracket
$sanitized2 = preg_replace('/(?:>[\r\n\s\t]*\{[^}]*\}[\r\n\s\t]*<)|(?:[\'"]\{[^}]*\}[\'"])|(\{[^}]*\})/', '', $sanitized1);
return $sanitized2;
}
/**
* @param $string
*
* @return mixed
*/
public function stringDeleteNonReplacedWithAttrs( $string ) {
return $this->_stringDeleteNonReplacedWithAttrs($string);
}
/**
* @param $string
*
* @return mixed
*/
protected function _stringDeleteNonReplacedWithAttrs( $string ) {
$sanitized = preg_replace('/(?:<[^>])?([\w\-.:]*\s*=\s*){0,1}(([\'"]){0,1}\{[^\}]+?\}\3{0,1}\s*)/', '', $string);
return $sanitized;
}
/**
* @param $snippetName
* @param array $replaceArray
* @param string $cleanupFlag
*
* @return mixed|null
*/
public function prepareHTMLSnippet( $snippetName, array $replaceArray, $cleanupFlag = 'NO_CLEANUP' ) {
return $this->_prepareHTMLSnippet($snippetName, $replaceArray, $cleanupFlag);
}
/**
* @param $snippetName
* @param array $replaceArray
* @param string $cleanupFlag
* @return mixed|null
* @throws \Exception
*/
protected function _prepareHTMLSnippet( $snippetName, array $replaceArray, $cleanupFlag = 'NOCLEANUP' ) {
$snippet = $this->HTMLSnippetProvider->getText($snippetName);
if (empty($snippet)) {
throw new \Exception('HTML Snippet not found');
}
if (empty($replaceArray) || !(count($replaceArray) > 0)) {
throw new \Exception('replaceArray not set or has no content');
}
$replacedSnippet = $this->_stringReplaceArray($snippet, $replaceArray);
$output = NULL;
if ($cleanupFlag == 'CLEANUP_ALL') {
$cleanedSnippet = $this->_stringDeleteNonReplacedWithAttrs($replacedSnippet);
$output = $cleanedSnippet;
} elseif ($cleanupFlag == 'CLEANUP_ATTRS') {
$cleanedSnippet = $this->_stringCleanupEmptyAttributes($replacedSnippet);
$output = $cleanedSnippet;
} elseif ($cleanupFlag == 'NO_CLEANUP') {
$output = $replacedSnippet;
}
return $output;
}
/**
* @param $string
* @param array $arr
*
* @return mixed
*/
protected function _stringReplaceArray( $string, array $arr ) {
foreach ($arr as $replacement) {
if (isset($replacement['title']) && isset($replacement['value'])) {
$title = (string)$replacement['title'];
$value = (string)$replacement['value'];
$string = str_replace('{' . $title . '}', $value, $string);
}
}
return $string;
}
/**
* @param $class
*/
protected function _setView( $class ) {
$this->view = $class;
}
/**
* @param $class
*/
public function setView( $class ) {
$this->_setView($class);
}
/**
* @param $price
* @return string
*/
public function formatPriceEUR($price) {
$orig = (float)$price;
return number_format($orig,2,',','.') . ' €';
}
/**
* @param $price
* @param null $currencyCode
* @return string
*/
public function formatPrice($price, $currencyCode = null) {
if($currencyCode === '' || $currencyCode === 'EUR' || null === $currencyCode) {
return $this->formatPriceEUR($price);
} else {
switch($currencyCode) {
case 'USD': return '$ ' . number_format((float)$price,2,'.',','); break;
case 'CHF': return number_format((float)$price,2,',','.'); break;
default: return $currencyCode . ' ' . number_format((float)$price,2,'.',','); break;
}
}
}
/**
* @param $text
* @param $placeholderName
* @param $replacementText
*/
public function replacePlaceholder(&$text, $placeholderName, $replacementText ) {
if(stripos($text,'%'.$placeholderName.'%') !== -1) {
$text = str_replace('%'.$placeholderName.'%',$replacementText,$text);
}
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Translation class for admin backend translation
*
* Example usage:
* $translate = new \DynCom\mysyde\common\classes\Translate();
* echo $translate->get('translation_index');
*
* @package DcCMS admin
* @author Tomasz Brniak <tomaszbrniak@web.de>
* @access public
*/
class Translate {
/**
* Store all text constants of the current language
*
* @access private
*/
private $_constants = array();
/**
* current language
*
* @access private
*/
private $_language;
/**
* init translation class
*
* @param string $_lang current language code
*
* @access public
*/
public function __construct( $_lang = 'de' ) {
$this->_language = $_lang;
$this->_loadFile();
}
/**
* Load all Text constants
* Uses a fixed file "text_constants.inc.php"
*
* @access private
* @return void
*/
private function _loadFile() {
$text_constant = array();
$path = CMS_PATH . "admin/text_constants.inc.php";
require($path);
$this->_constants = $text_constant[$this->_language];
}
/**
* Get the translation of the given key
*
* @param string $_key unique key of the translation constant
*
* @access public
* @return string
*/
public function get( $_key ) {
if (isset($this->_constants[$_key])) {
return $this->_constants[$_key];
} else {
return $_key;
}
}
}

View File

@@ -0,0 +1,427 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/22/2015
* Time: 12:09 PM
*/
final class URL
{
const PROTOCOL_HTTP = 'http';
const PROTOCOL_HTTPS = 'https';
const PROTOCOL_FTP = 'ftp';
private $protocol;
private $user;
private $password;
private $domain;
private $port;
private $path;
private $queryParams;
private $anchor;
/**
* URL constructor.
* @param $protocol
* @param null $user
* @param null $password
* @param $domain
* @param null $port
* @param null $path
* @param array|null $queryParams
* @param null $anchor
*/
public function __construct($protocol, $user = null, $password = null, $domain, $port = null, $path = null, array $queryParams = null, $anchor = null)
{
if (null === $protocol || !$this->isProtocolValid($protocol)) {
throw new \InvalidArgumentException(
'Protocol `' . $protocol . '`is not a valid protocol. Only http, https & ftp are allowed'
);
}
if (null === $domain || !$this->isDomainValid($domain)) {
throw new \InvalidArgumentException(
'Domain is not valid.'
);
}
if (null !== $port && !$this->isPortValid($port)) {
throw new \InvalidArgumentException(
'Port is not valid. Valid range is 0-65535'
);
}
if (null !== $path && !$this->isPathValid($path)) {
throw new \InvalidArgumentException(
'Path is not a valid URL-path'
);
}
if (null !== $queryParams) {
foreach ($queryParams as $paramKey => $paramValue) {
if (!$this->isQueryParamValid([$paramKey => $paramValue])) {
throw new \InvalidArgumentException(
'Query parameter name must not differ from its URL-encoding. Paramter `' . htmlentities($paramKey) . '` does not meet this criterion.'
);
}
}
}
if (null !== $anchor && !$this->isAnchorValid($anchor)) {
throw new \InvalidArgumentException(
'Ancher is not valid.'
);
}
$this->protocol = $protocol;
$this->user = $user;
$this->password = $password;
$this->domain = $domain;
$this->port = $port;
$this->path = $path;
$this->queryParams = $queryParams;
$this->anchor = $anchor;
}
/**
* @param $protocol
* @return URL
*/
public function withProtocol($protocol)
{
return new self($protocol, $this->user, $this->password, $this->domain, $this->port, $this->path, $this->queryParams, $this->anchor);
}
/**
* @param $user
* @return URL
*/
public function withUser($user)
{
return new self($this->protocol, $user, $this->password, $this->domain, $this->port, $this->path, $this->queryParams, $this->anchor);
}
/**
* @param $password
* @return URL
*/
public function withPassword($password)
{
return new self($this->protocol, $this->user, $password, $this->domain, $this->port, $this->path, $this->queryParams, $this->anchor);
}
/**
* @param $user
* @param $password
* @return URL
*/
public function withUserPassword($user, $password)
{
return new self($this->protocol, $user, $password, $this->domain, $this->port, $this->path, $this->queryParams, $this->anchor);
}
/**
* @param $domain
* @return URL
*/
public function withDomain($domain)
{
return new self($this->protocol, $this->user, $this->password, $domain, $this->port, $this->path, $this->queryParams, $this->anchor);
}
/**
* @param $port
* @return URL
*/
public function withPort($port)
{
return new self($this->protocol, $this->user, $this->password, $this->domain, $port, $this->path, $this->queryParams, $this->anchor);
}
/**
* @param $path
* @return URL
*/
public function withPath($path)
{
return new self($this->protocol, $this->user, $this->password, $this->domain, $this->port, $path, $this->queryParams, $this->anchor);
}
/**
* @param array $params
* @return static
*/
public function withAddedQueryParams(array $params)
{
$newParamArray = array_merge($this->queryParams, $params);
return new static($this->protocol, $this->user, $this->password, $this->domain, $this->port, $this->path, $newParamArray, $this->anchor);
}
/**
* @param array $params
* @return static
*/
public function withNewQueryParams(array $params)
{
return new static($this->protocol, $this->user, $this->password, $this->domain, $this->port, $this->path, $params, $this->anchor);
}
/**
* @param $anchor
* @return URL
*/
public function withAnchor($anchor)
{
return new self($this->protocol, $this->user, $this->password, $this->domain, $this->port, $this->path, $this->queryParams, $anchor);
}
/**
* @return string
*/
public function getQueryString()
{
$queryString = '';
if (is_array($this->queryParams) && count($this->queryParams) > 0) {
$queryString .= '?';
$i = 0;
foreach ($this->queryParams as $paramName => $paramVal) {
if ($i > 0) {
$queryString .= '&';
}
$queryString .= $paramName . '=' . $paramVal;
++$i;
}
}
return $queryString;
}
/**
* @return string
*/
public function getFullURL()
{
if (null === $this->domain) {
throw new \RuntimeException('No domain-name set.');
}
if (null === $this->protocol) {
throw new \RuntimeException('No protocol set.');
}
//Protocol
$url = $this->protocol . '://';
//User/Pass
if (null !== $this->user) {
$url .= rawurlencode($this->user) . ':';
if (null !== $this->password) {
$url .= rawurlencode($this->password);
}
$url .= '@';
}
//Domain
$url .= $this->domain;
//Port
if (null !== $this->port) {
$url .= ':' . $this->port;
}
//Path
if (null !== $this->path) {
$url .= $this->path;
}
//QueryString
if (null !== $this->queryParams) {
$url .= $this->getQueryString();
}
//Anchor
if (null !== $this->anchor) {
$url .= '#' . $this->anchor;
}
return $url;
}
/**
* @param $protocol
* @return bool
*/
protected function isProtocolValid($protocol)
{
return in_array($protocol, [
self::PROTOCOL_HTTP,
self::PROTOCOL_HTTPS,
self::PROTOCOL_FTP
], true);
}
/**
* @param $domain
* @return bool
*/
private function isDomainValid($domain)
{
return (preg_match('/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i', $domain) //valid chars check
&& preg_match('/^.{1,253}$/', $domain) //overall length check
&& preg_match('/^[^\.]{1,63}(\.[^\.]{1,63})*$/', $domain)); //length of each label
}
/**
* @param $port
* @return bool
*/
private function isPortValid($port)
{
return ((is_int($port) || ctype_digit($port)) && $port >= 0 && $port <= 65535);
}
/**
* @param $path
* @return int
*/
private function isPathValid($path)
{
return preg_match('|^\/[a-zA-Z0-9\-\+\_%]+(?:[\/\a-zA-Z0-9\-\+\_%]+)*$|', $path);
}
/**
* @param array $queryParam
* @return bool
*/
private function isQueryParamValid(array $queryParam)
{
$firstKey = array_keys($queryParam)[0];
$firstVal = array_values($queryParam)[0];
return (count($queryParam) === 1 && $firstKey === urlencode($firstKey) && is_scalar($firstVal));
}
/**
* @param $anchor
* @return int
*/
private function isAnchorValid($anchor)
{
return preg_match('/^[a-zA-Z0-9_\-]+$/', $anchor);
}
public function getProtocol()
{
return $this->protocol;
}
/**
* @return null
*/
public function getUser()
{
return $this->user;
}
/**
* @return null
*/
public function getPassword()
{
return $this->password;
}
public function getDomain()
{
return $this->domain;
}
/**
* @return null
*/
public function getPort()
{
return $this->port;
}
/**
* @return null
*/
public function getPath()
{
return $this->path;
}
/**
* @return array
*/
public function getQueryParams()
{
return $this->queryParams;
}
/**
* @return null
*/
public function getAnchor()
{
return $this->anchor;
}
/**
* @param $domain
* @return URL
*/
public static function createHTTPFromDomain($domain)
{
return new self(self::PROTOCOL_HTTP,null,null,$domain,null,null,null,null);
}
/**
* @param $domain
* @return URL
*/
public static function createHTTPSFromDomain($domain)
{
return new self(self::PROTOCOL_HTTPS,null,null,$domain,null,null,null,null);
}
/**
* @param $domain
* @param $path
* @return URL
*/
public static function createHTTPFromDomainAndPath($domain, $path)
{
return new self(self::PROTOCOL_HTTP,null,null,$domain,null,$path,null,null);
}
/**
* @param $domain
* @param $path
* @return URL
*/
public static function createHTTPSFromDomainAndPath($domain, $path)
{
return new self(self::PROTOCOL_HTTPS,null,null,$domain,null,$path,null,null);
}
/**
* @return string
*/
public function __toString() {
return $this->getFullURL();
}
}
/*
$url1 = new URL(URL::PROTOCOL_HTTPS, 'bauer@dc-solution.de', '!mB11121983!', 'www.pearson-friends.de', 88, '/mysyde/de/software/dccms/', ['test1name' => 'test1value'], 'anchor1');
$url2 = $url1->withDomain('www.pearson-friends.de')
->withUserPassword(null,null)
->withPort(null)
->withNewQueryParams([])
->withAnchor(null);
$url3 = URL::createHTTPFromDomain('www.arstechnica.com');
$url4 = URL::createHTTPSFromDomainAndPath('www.arstechnica.com','/httpstest/is/here/in/this/file.php');
echo 'URL1: ' . $url1->getFullURL();
echo '
URL2: ' . $url2->getFullURL();
echo '
URL3: ' . $url3->getFullURL();
echo '
URL4: ' . $url4->getFullURL();*/

View File

@@ -0,0 +1,41 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\abstracts\URLBase;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/22/2015
* Time: 12:09 PM
*/
class URLImmutable extends URLBase {
/**
* URLImmutable constructor.
* @param $protocol
* @param $user
* @param $password
* @param $domain
* @param $port
* @param $path
* @param $queryParams
* @param $anchor
*/
public function __construct($protocol, $user, $password, $domain, $port, $path, $queryParams, $anchor) {
$trace = debug_backtrace();
if(!isset($trace[1]['class']) || $trace[1]['class'] != 'URLMaker') {
throw new \DomainException('URLImmutable must only be constructed from URLMaker, not ' . $trace[1]['class']);
}
$this->protocol = $protocol;
$this->user = $user;
$this->password = $password;
$this->domain = $domain;
$this->path = $path;
$this->queryParams = $queryParams;
$this->anchor = $anchor;
}
}

View File

@@ -0,0 +1,207 @@
<?php
namespace DynCom\mysyde\common\classes;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/5/2015
* Time: 2:31 PM
*/
class URLMaker {
const PROTOCOL_HTTP = 'http';
const PROTOCOL_HTTPS = 'https';
const PROTOCOL_FTP = 'ftp';
protected $protocol;
protected $user;
protected $password;
protected $domain;
protected $port;
protected $path;
protected $queryParams;
protected $anchor;
/**
* @param $protocol
*/
public function setProtocol( $protocol ) {
$allowedProtocols = array(
self::PROTOCOL_HTTP,
self::PROTOCOL_HTTPS,
self::PROTOCOL_FTP
);
if(!in_array($protocol,$allowedProtocols,true)) {
throw new \InvalidArgumentException('Protocol \'' . $protocol . '\' is not supported');
}
$this->protocol = $protocol;
}
/**
* @param $user
*/
public function setUser( $user ) {
$this->user = urlencode($user);
}
/**
* @param $pass
*/
public function setPassword( $pass ) {
$this->password = urlencode($pass);
}
/**
* @param $domain
*/
public function setDomain( $domain ) {
if(!$this->_isValidDomainName($domain)) {
throw new \InvalidArgumentException('Domain-Name \'' . $domain . '\' is not valid.');
}
$this->domain = $domain;
}
/**
* @param $port
*/
public function setPort( $port ) {
if(!preg_match('/^[[:digit:]]+$/',$port)) {
throw new \InvalidArgumentException('Port is not numeric');
}
$this->port = (int)$port;
}
/**
* @param $path
*/
public function setPath( $path ) {
if(!preg_match('|^\/[\/\.a-zA-Z0-9\-\+\_%]+$|',$path)) {
throw new \InvalidArgumentException('Path is not valid. Must start with slash and contain only [a-zA-Z0-9-+_%/].');
}
$this->path = $path;
}
/**
* @param $name
* @param $nonURLEncodedValue
* @internal param $value
*/
public function addQueryParam( $name, $nonURLEncodedValue ) {
if(!(urlencode($name) === $name)) {
throw new \InvalidArgumentException('Parameter-Name \'' . $name . '\' is not valid in URLs');
}
$this->queryParams[] = array('paramName' => $name, 'paramValue' => urlencode($nonURLEncodedValue));
}
/**
* @param $name
*/
public function addAnchor( $name ) {
if(!preg_match('/^[a-zA-Z0-9_\-]+$/',$name)) {
throw new \InvalidArgumentException('Anchor-string is not valid. Must contain only [a-zA-Z0-9_\-].');
}
$this->anchor = $name;
}
/**
* @return string
*/
public function getFullURL() {
if(null === ($this->domain)) {
throw new \RuntimeException('No domain-name set.');
}
if(null === ($this->protocol)) {
throw new \RuntimeException('No protocol set.');
}
//Protocol
$url = $this->protocol . '://';
//User/Pass
if(null !== $this->user) {
$url .= $this->user . ':';
if(null !== $this->password) {
$url .= $this->password;
}
$url .= '@';
}
//Domain
$url .= $this->domain;
//Port
if(null !== $this->port) {
$url .= ':' . $this->port;
}
//Path
if(null !== $this->path) {
$url .= $this->path;
}
//QueryString
if(null !== $this->queryParams) {
$url .= $this->getQueryString();
}
//Anchor
if(null !== $this->anchor) {
$url .= '#' . $this->anchor;
}
return $url;
}
/**
* @return string
*/
public function getQueryString() {
$queryString = '';
if(is_array($this->queryParams)) {
$queryString .= '?';
$i = 0;
foreach($this->queryParams as $paramArr) {
$paramName = $paramArr['paramName'];
$paramVal = $paramArr['paramValue'];
if($i > 0) {
$queryString .= '&';
}
$queryString .= $paramName . '=' . $paramVal;
++$i;
}
}
return $queryString;
}
/**
* @param $domainName
* @return bool
*/
protected function _isValidDomainName( $domainName ) {
return (preg_match('/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i', $domainName) //valid chars check
&& preg_match('/^.{1,253}$/', $domainName) //overall length check
&& preg_match('/^[^\.]{1,63}(\.[^\.]{1,63})*$/', $domainName) ); //length of each label
}
public function reset() {
$this->anchor = null;
$this->queryParams = null;
$this->path = null;
$this->port = null;
$this->domain = null;
$this->user = null;
$this->password = null;
$this->protocol = null;
}
/**
* @param array $params
* @return string
*/
public function getQueryStringFromParamArray(array $params ) {
$queryString = '';
$i = 0;
foreach ($params as $paramKey => $paramVal) {
if ($i > 0) {
$queryString .= '&';
}
$queryString .= $paramKey . '=' . urlencode($paramVal);
++$i;
}
return $queryString;
}
}

View File

@@ -0,0 +1,247 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\GenericDBModelInterface;
use DynCom\mysyde\common\interfaces\GenericDBQueryWrapperInterface;
use DynCom\mysyde\common\interfaces\Repository;
use DynCom\mysyde\common\interfaces\RepositoryUnitOfWorkInterface;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/2/2015
* Time: 10:04 AM
*/
class UnitOfWork implements RepositoryUnitOfWorkInterface
{
const ENTITY_STATE_NEW = 'ENTITY_STATE_NEW';
const ENTITY_STATE_CLEAN = 'ENTITY_STATE_CLEAN';
const ENTITY_STATE_DIRTY = 'ENTITY_STATE_DIRTY';
const ENTITY_STATE_REMOVED = 'ENTITY_STATE_REMOVED';
protected $possibleStates = array(self::ENTITY_STATE_NEW, self::ENTITY_STATE_CLEAN, self::ENTITY_STATE_DIRTY, self::ENTITY_STATE_REMOVED);
protected $repositories;
protected $entityCollection;
protected $db;
/**
* UnitOfWork constructor.
* @param GenericDBQueryWrapperInterface $queryWrapper
*/
public function __construct(GenericDBQueryWrapperInterface $queryWrapper)
{
$this->entityCollection = new GenericObjectStorage();
$this->db = $queryWrapper;
}
/**
* @param Repository $repository
*/
public function registerRepository(Repository $repository)
{
$objectClass = $repository->getObjectClass();
$this->repositories[$objectClass] = $repository;
}
/**
* @param GenericDBModelInterface $entity
*/
public function registerNew(GenericDBModelInterface $entity)
{
$this->registerEntity($entity, self::ENTITY_STATE_NEW);
}
/**
* @param GenericDBModelInterface $entity
*/
public function registerClean(GenericDBModelInterface $entity)
{
$this->registerEntity($entity, self::ENTITY_STATE_CLEAN);
}
/**
* @param GenericDBModelInterface $entity
*/
public function registerDirty(GenericDBModelInterface $entity)
{
$this->registerEntity($entity, self::ENTITY_STATE_DIRTY);
}
/**
* @param GenericDBModelInterface $entity
*/
public function registerRemoved(GenericDBModelInterface $entity)
{
$this->registerEntity($entity, self::ENTITY_STATE_REMOVED);
}
/**
* @param GenericDBModelInterface $entity
* @param $state
*/
public function registerEntity(GenericDBModelInterface $entity, $state)
{
if (!in_array($state, $this->possibleStates, true)) {
throw new \InvalidArgumentException('State \'' . $state . '\' to register is not defined');
}
$className = get_class($entity);
if (!array_key_exists($className, $this->repositories)) {
throw new \InvalidArgumentException('UoW has no repository for entity of class ' . $className);
}
$data = array('className' => get_class($entity),'state' => $state);
if (isset($entity->id) && ((int)$entity->id > 0)) {
$this->repositories[$className]->lockRecordByID((int)$entity->id);
}
if($this->entityCollection->contains($entity)) {
$data = $this->entityCollection->offsetGet($entity);
$existingObjState = $data['state'];
if($existingObjState === $state) {
$this->entityCollection->detach($entity);
} else {
throw new \LogicException('Cannot register the same entity with different states');
}
}
$this->entityCollection->attach($entity, $data);
}
/**
* @param GenericDBModelInterface $entity
*/
public function unregisterEntity(GenericDBModelInterface $entity)
{
$className = get_class($entity);
if (!array_key_exists($className, $this->repositories)) {
throw new \InvalidArgumentException('UoW has no repository of entity of class ' . $className);
}
if ($this->entityCollection->contains($entity)) {
$this->entityCollection->detach($entity);
}
if (isset($entity->id) && ((int)$entity->id > 0)) {
$this->repositories[$className]->releaseRecordLock((int)$entity->id);
}
}
/**
* @param Repository $repository
*/
public function unregisterRepository(Repository $repository)
{
$className = $repository->getObjectClass();
if (array_key_exists($className, $this->repositories)) {
unset($this->repositories[$className]);
}
}
/**
* @return $this
*/
public function clear()
{
$this->entityCollection->clear();
return $this;
}
public function commit()
{
if (!$this->db->startTransaction()) {
throw new \BadMethodCallException('Could not start transaction. ' . $this->db->getErrorMessage());
}
$c = $this->entityCollection;
$c->rewind();
while ($c->valid()) {
$object = $c->current();
$data = $c->getInfo();
$className = $data['className'];
$state = $data['state'];
$repository = $this->repositories[$className];
if($repository instanceof Repository && $object instanceof GenericDBModelInterface) {
switch ($state) {
case self::ENTITY_STATE_CLEAN:
break;
case self::ENTITY_STATE_NEW:
$currInsertQuery = $repository->getCreateInDBQuery($object);
$this->db->setQuery($currInsertQuery);
if (!$this->db->doQuery()) {
throw new \BadMethodCallException('Could not execute Query in transaction. ' . $this->db->getErrorMessage());
}
break;
case self::ENTITY_STATE_DIRTY:
$currUpdateQuery = $repository->getUpdateSingleQuery($object);
$this->db->setQuery($currUpdateQuery);
if (!$this->db->doQuery()) {
throw new \BadMethodCallException('Could not execute Query in transaction. ' . $this->db->getErrorMessage());
}
break;
case self::ENTITY_STATE_REMOVED:
$currDeleteQuery = $repository->getDeleteByIDQuery($object);
$this->db->setQuery($currDeleteQuery);
if (!$this->db->doQuery()) {
throw new \BadMethodCallException('Could not execute Query in transaction. ' . $this->db->getErrorMessage());
}
break;
}
}
$c->next();
}
if (!$this->db->commitTransaction()) {
throw new \BadMethodCallException('Could not commit transaction. ' . $this->db->getErrorMessage());
}
$c->rewind();
while ($c->valid()) {
$index = $c->key();
$object = $c->current();
$data = $c->getInfo();
$className = $data['className'];
$state = $data['state'];
$repository = $this->repositories[$className];
if ($repository instanceof Repository && $object instanceof GenericDBModelInterface)
{
switch ($state) {
case self::ENTITY_STATE_CLEAN: break;
case self::ENTITY_STATE_NEW:
$repository->add($object,false);
break;
case self::ENTITY_STATE_DIRTY:
$repository->releaseRecordLock($object->id);
$repository->recacheEntityFromDBByID($object->id);
break;
case self::ENTITY_STATE_REMOVED:
$repository->releaseRecordLock($object->id);
$repository->removeEntityFromCache($object);
break;
}
}
$c->next();
}
$this->clear();
}
public function rollback()
{
//Only release record locks - transaction actually happens only on commit(),
//but entities with ID are locked from registration in their repositories
$c = $this->entityCollection;
$c->rewind();
while ($c->valid()) {
$index = $c->key();
$object = $c->current();
$data = $c->getInfo();
$className = $data['className'];
$state = $data['state'];
$repository = $this->repositories[$className];
if (isset($object->id) && ((int)$object->id > 0) && $repository instanceof Repository) {
$repository->releaseRecordLock($object->id);
}
$c->next();
}
$c->rewind();
}
}

View File

@@ -0,0 +1,112 @@
<?php
namespace DynCom\mysyde\common\classes;
use finfo;
/**
* Created by PhpStorm.
* User: bauer
* Date: 29.04.2016
* Time: 11:17
*/
class UploadedFileTypeCheckingService
{
const TYPE_BMP_JPG_PNG_GIF = 0;
const TYPE_NO_PHP_JS = 1;
private $allowedValidationTypes = [
self::TYPE_BMP_JPG_PNG_GIF,
self::TYPE_NO_PHP_JS,
];
/**
* @var UploadedFileTypeCheckingService
*/
private static $instance;
private static $type_bmp_jpg_png_gif_mime = [
'bmp' => 'image/bmp',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpe' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
];
private static $type_no_php_js_mime = [
'js' => 'application/javascript',
'plain' => 'text/plain',
];
/**
* @param $validationType
* @return \Closure
*/
private function getValidationFunctionForType($validationType) {
if ($validationType === self::TYPE_BMP_JPG_PNG_GIF) {
return function($filePath, &$extension) {
$finfo = new finfo(FILEINFO_MIME_TYPE);
$fileInfo = $finfo->file($filePath);
$ext = array_search(
$fileInfo,
self::$type_bmp_jpg_png_gif_mime,
true);
if (false === $ext) {
return false;
}
if (null !== $extension) {
$extension = $ext;
}
return true;
};
} elseif ($validationType === self::TYPE_NO_PHP_JS) {
return function($filePath, &$extension) {
$finfo = new finfo(FILEINFO_MIME_TYPE);
$fileInfo = $finfo->file($filePath);
if (false === $ext = array_search(
$fileInfo,
self::$type_no_php_js_mime,
true)
) {
if (null !== $extension) {
$extension = $ext;
}
return true;
}
return false;
};
} else {
return function ($filePath) {
return false;
};
}
}
/**
* @param $pathToFile
* @param $validationType
* @param $extension
* @return mixed
*/
public function isFileAllowed($pathToFile, $validationType, &$extension) {
if (!file_exists($pathToFile) || !is_readable($pathToFile) || !in_array($validationType,$this->allowedValidationTypes,true)) {
throw new \InvalidArgumentException('Parameters must specify a valid path to a readable file and an allowed validation type.');
}
$validationFunction = $this->getValidationFunctionForType($validationType);
$isValid = $validationFunction($pathToFile,$extension);
return $isValid;
}
/**
* @param $filePath
* @param $validationType
* @param $extension
* @return mixed
*/
public static function checkFileAgainstValidationType($filePath, $validationType, &$extension)
{
if (null === self::$instance) {
self::$instance = new static();
}
return self::$instance->isFileAllowed($filePath,$validationType,$extension);
}
}

View File

@@ -0,0 +1,944 @@
<?php
namespace DynCom\mysyde\common\classes;
use ReflectionClass;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 6/12/2015
* Time: 3:42 AM
*/
class Validator
{
const ORDINAL_COMPARATOR_EQ = '=';
const ORDINAL_COMPARATOR_LT = '<';
const ORDINAL_COMPARATOR_LTE = '<=';
const ORDINAL_COMPARATOR_GT = '>';
const ORDINAL_COMPARATOR_GTE = '>=';
const DECIMAL_SEPARATOR_COMMA = ',';
const DECIMAL_SEPARATOR_POINT = '.';
const DATE_FORMAT_ISO_8601 = 'yyyy-mm-dd';
const DATE_FORMAT_DDMMYY_DASHES = 'dd-mm-yy';
const DATE_FORMAT_DDMMYYYY_DASHES = 'dd-mm-yyyy';
const DATE_FORMAT_DDMMYY_DOTS = 'dd.mm.yy';
const DATE_FORMAT_DDMMYYYY_DOTS = 'dd.mm.yyyy';
const DATE_FORMAT_DDMMYY_SLASHES = 'dd/mm/yy';
const DATE_FORMAT_DDMMYYYY_SLASHES = 'dd/mm/yyyy';
const DATE_FORMAT_MMDDYY_DASHES = 'mm-dd-yy';
const DATE_FORMAT_MMDDYYYY_DASHES = 'mm-dd-yyyy';
const DATE_FORMAT_MMDDYY_DOTS = 'mm.dd.yy';
const DATE_FORMAT_MMDDYYYY_DOTS = 'mm.dd.yyyy';
const DATE_FORMAT_MMDDYY_SLASHES = 'mm/dd/yy';
const DATE_FORMAT_MMDDYYYY_SLASHES = 'mm/dd/yyyy';
const DATETIME_FORMAT_ISO_8601 = 'yyyy-mm-ddThh:mm:ss';
const DATETIME_FORMAT_MYSQL = 'yyyy-mm-dd hh:mm:ss';
const TIME_FORMAT_COLON = 'hh:mm:ss';
const CONF_RULE_SEPARATOR = '|';
const CONF_RULE_VALUE_SEPARATOR = ':';
const RULE_REQUIRED = 'required';
const ERRORMSG_RULE_REQUIRED_DE = 'Bitte füllen Sie das Feld %fieldname% aus';
const ERRORMSG_RULE_REQUIRED_EN = 'Please fill in the field %fieldname%.';
const RULE_EMAIL = 'email';
const ERRORMSG_RULE_EMAIL_DE = 'Bitte geben Sie eine gültige E-Mail Adresse in das Feld %fieldname% ein.';
const ERRORMSG_RULE_EMAIL_EN = 'Please enter a valid email-address into field %fieldname%.';
const RULE_NAME = 'name';
const ERRORMSG_RULE_NAME_DE = 'Bitte geben Sie einen gültigen Namen in das Feld %fieldname% ein.';
const ERRORMSG_RULE_NAME_EN = 'Please enter a valid name into field %fieldname%.';
const RULE_ADDR_STREET = 'addrstreet';
const ERRORMSG_RULE_ADDR_STREET_DE = 'Bitte geben Sie einen gültigen Straßennamen in das Feld %fieldname% ein.';
const ERRORMSG_RULE_ADDR_STREET_EN = 'Please enter a valid street-name into field %fieldname%.';
const RULE_ADDR_STREET_NO = 'addrstreetno';
const ERRORMSG_RULE_ADDR_STREET_NO_DE = 'Bitte geben Sie eine gültige Hausnummer in das Feld %fieldname% ein.';
const ERRORMSG_RULE_ADDR_STREET_NO_EN = 'Please enter a valid street-number into field %fieldname%.';
const RULE_ADDR_STREET_PLUS_NO = 'addrstreetplusno';
const ERRORMSG_RULE_ADDR_STREET_PLUS_NO_DE = 'Bitte geben Sie eien gültige Kombination aus Straßennamen und Hausnummer in das Feld %fieldname% ein.';
const ERRORMSG_RULE_ADDR_STREET_PLUS_NO_EN = 'Please enter a valid combination of street-name and street-number into field %fieldname%.';
const RULE_ADDR_CITY = 'addrcity';
const ERRORMSG_RULE_ADDR_CITY_DE = 'Bitte geben Sie eine gültige Stadt im Feld %fieldname% an,';
const ERRORMSG_RULE_ADDR_CITY_EN = 'Please enter a valid city into field %fieldname%,';
const RULE_ADDR_ZIP = 'addrzip';
const ERRORMSG_RULE_ADDR_ZIP_DE = 'Bitte geben Sie eine gültige Postleitzahl in das Feld %fieldname% ein.';
const ERRORMSG_RULE_ADDR_ZIP_EN = 'Please enter a valid ZIP-Code into field %fieldname%.';
const RULE_STR_WS_DASH_DOT = 'strwsdashdot';
const ERRORMSG_RULE_STR_WS_DASH_DOT_DE = 'Bitte geben Sie nur Buchstaben, Leerzeichen, Minuszeichen und Punkte in das Feld %fieldname% ein.';
const ERRORMSG_RULE_STR_WS_DASH_DOT_EN = 'Please enter only letters, spaces, minus-signs and stops into field %fieldname%';
const RULE_STR_WS_DASH_DOT_PAR = 'strwsdashdotparen';
const ERRORMSG_RULE_STR_WS_DASH_DOT_PAR_DE = 'Bitte geben Sie nur Buchstaben, Leerzeichen, Minuszeichen runde Klammern und Punkte in das Feld %fieldname% ein.';
const ERRORMSG_RULE_STR_WS_DASH_DOT_PAR_EN = 'Please enter only letters, spaces, minus-signs, parantheses and stops into field %fieldname%.';
const RULE_URL = 'url';
const ERRORMSG_RULE_URL_DE = 'Bitte geben Sie eine gültige URL im Feld %fieldname% an';
const ERRORMSG_RULE_URL_EN = 'Please enter a valid URL into field %fieldname%.';
const RULE_ALPHA = 'Alpha';
const ERRORMSG_RULE_ALPHA_DE = 'Bitte geben Sie nur Buchstaben in das Feld %fieldname% ein.';
const ERRORMSG_RULE_ALPHA_EN = 'Please enter only letters into field %fieldname%.';
const RULE_ALPHA_CAPS = 'ALPHA';
const ERRORMSG_RULE_ALPHA_CAPS_DE = 'Bitte geben Sie nur Großbuchstaben in das Feld %fieldname% ein.';
const ERRORMSG_RULE_ALPHA_CAPS_EN = 'Please enter only capital letters into field %fieldname%.';
const RULE_ALPHA_SMALL = 'alpha';
const ERRORMSG_RULE_ALPHA_SMALL_DE = 'Bitte geben Sie nur Kleinbuchstabenb in das Feld %fieldname% ein.';
const ERRORMSG_RULE_ALPHA_SMALL_EN = 'Please enter only small letters into field %fieldname%.';
const RULE_DIGIT = 'digit';
const ERRORMSG_RULE_DIGIT_DE = 'Bitte geben Sie nur Ziffern in das Feld %fieldname% ein.';
const ERRORMSG_RULE_DIGIT_EN = 'Please enter only digits into field %fieldname%.';
const RULE_DECIMAL = 'decimal';
const ERRORMSG_RULE_DECIMAL_DE = 'Bitte geben Sie eine Dezimalzahl in das Feld %fieldname% ein.';
const ERRORMSG_RULE_DECIMAL_EN = 'Please enter a valid decimal number into field %fieldname%.';
const RULE_ALNUM = 'alnum';
const ERRORMSG_RULE_ALNUM_DE = 'Bitte geben Sie nur Buchstaben und Ziffern in das Feld %fieldname% ein.';
const ERRORMSG_RULE_ALNUM_EN = 'Please enter only letters and digits into field %fieldname%.';
const RULE_GENERAL_TEXT = 'text';
const ERRORMSG_RULE_GENERAL_TEXT_DE = 'Die Eingabe in das Feld %fieldname% war ungültig. Bitte versuchen Sie es noch einmal.';
const ERRORMSG_RULE_GENERAL_TEXT_EN = 'Your input into field %fieldname% was invalid. Please try again.';
const RULE_DATE = 'date';
const ERRORMSG_RULE_DATE_DE = 'Bitte geben Sie ein gültiges Datum in das Feld %fieldname% ein.';
const ERRORMSG_RULE_DATE_EN = 'Please enter a valid date into field %fieldname%.';
const RULE_DATETIME = 'dateTime';
const ERRORMSG_RULE_DATETIME_DE = 'Bitte geben Sie eine gültige Datum-Uhrzeit-Kombination in das Feld %fieldname% ein.';
const ERRORMSG_RULE_DATETIME_EN = 'Please enter a valid datetime into field %fieldname%.';
const RULE_MIN_LENGTH = 'minlen';
const ERRORMSG_RULE_MIN_LENGTH_DE = 'Bitte geben Sie mindestens %validationparam% Zeichen in das Feld %fieldname% ein.';
const ERRORMSG_RULE_MIN_LENGTH_EN = 'Please enter at least %validationparam% characters into field %fieldname%.';
const RULE_MAX_LENGTH = 'maxlen';
const ERRORMSG_RULE_MAX_LENGTH_DE = 'Bitte geben Sie höchstens %vaidationparam% Zeichen in das Feld %fieldname% ein.';
const ERRORMSG_RULE_MAX_LENGTH_EN = 'Please enter at most %validationparam% characters into field %fieldname%.';
const RULE_MIN_NUMERIC = 'minnum';
const ERRORMSG_RULE_MIN_NUMERIC_DE = 'Bitte geben Sie einen Wert größer oder gleich %validationparam% in das Feld %fieldname% ein.';
const ERRORMSG_RULE_MIN_NUMERIC_EN = 'Please enter a number greater than or equal to %validationparam% into field %fieldname%.';
const RULE_MAX_NUMERIC = 'maxnum';
const ERRORMSG_RULE_MAX_NUMERIC_DE = 'Bitte geben Sie einen Wert kleiner oder gleich %validationparam% in das Feld %fieldname% ein.';
const ERRORMSG_RULE_MAX_NUMERIC_EN = 'Please enter a number less than or equal to %validationparam% into field %fieldname%.';
const RULE_MIN_DATE = 'mindate';
const ERRORMSG_RULE_MIN_DATE_DE = 'Bitte geben Sie ein Datum frühestens ab dem %validationparam% in das Feld %fieldname% ein.';
const ERRORMSG_RULE_MIN_DATE_EN = 'Please enter a date greater than or equal to %validationparam% into field %fieldname%.';
const RULE_MAX_DATE = 'maxdate';
const ERRORMSG_RULE_MAX_DATE_DE = 'Bitte geben Sie ein Datum bis höchstens den %validationparam% in das Feld %fieldname% ein.';
const ERRORMSG_RULE_MAX_DATE_EN = 'Please enter a date less than or equal to %validationparam% into field %fieldname%.';
const RULE_CUST_REGEX = 'regex';
const ERRORMSG_RULE_CUST_REGEX_DE = 'Das Format Ihrer Eingabe in das Feld %fieldname% war ungültig. Bitte versuchen Sie es nocheinmal.';
const ERRORMSG_RULE_CUST_REGEX_EN = 'Your input into field %fieldname% was invalid. Please try again.';
const RULE_REQUIRES = 'requires';
const ERRORMSG_RULE_REQUIRES_DE = 'Das Feld %validationparam% muss gefüllt sein';
const ERRORMSG_RULE_REQUIRES_EN = 'The field %validationparam% has to be filled in.';
const RULE_EXTENDS = 'extends';
const RULE_IN = 'in';
const ERRORMSG_RULE_IN_DE = 'Ihre Eingabe in das Feld %fieldname% war ungültig. Bitte versuchen Sie es nocheinmal.';
const ERRORMSG_RULE_IN_EN = 'Your input into field %fieldname% was invalid. Please try again.';
const RULE_INSTANCEOF = 'instanceof';
const RULE_FIELD = 'field';
const RULE_METHOD = 'method';
const RULE_EMPTY_ALLOWED = 'orempty';
const ERRORMSG_RULE_EMPTY_ALLOWED_DE = '';
const ERRORMSG_RULE_EMPTY_ALLOWED_EN = '';
protected $decimalSeparator = self::DECIMAL_SEPARATOR_POINT;
protected $dateFormat = self::DATE_FORMAT_DDMMYY_DOTS;
protected $timeFormat = self::TIME_FORMAT_COLON;
protected $dateTimeFormat = self::DATETIME_FORMAT_MYSQL;
protected $dateValidation = array();
protected $ruleConstants = array();
protected $data = array();
protected $rules = array();
protected $languageCode = 'de';
/**
* @param $code
*/
public function setLanguageCode($code)
{
$this->languageCode = $code;
}
/**
* @param $regex
* @return bool
*/
protected function _isValidRegex($regex)
{
return (preg_match($regex, null) !== false);
}
/**
* @param $fieldName
* @param $regex
*/
public function setCustomRegexRule($fieldName, $regex)
{
if (!array_key_exists($fieldName, $this->data)) {
throw new \InvalidArgumentException(
sprintf(
'%s is not the name of a data-item.',
strip_tags($fieldName)
)
);
}
if (!$this->_isValidRegex($regex)) {
throw new \InvalidArgumentException(
sprintf(
'%s is not a valid regex.',
strip_tags($regex)
)
);
}
$callable = function ($fieldName, $fieldValue, $validationParam) {
return (preg_match($validationParam, $fieldValue) > 0);
};
$this->rules[$fieldName][self::RULE_CUST_REGEX] = array('callable' => &$callable, 'ruleValue' => $regex);
}
protected function _setDefaultDateFormatValidation()
{
$this->dateValidation = array(
self::DATE_FORMAT_ISO_8601 => function ($dataSourceString) {
return $this->_isValidByDateFormat('Y-m-d', $dataSourceString);
},
self::DATE_FORMAT_DDMMYY_DASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('d-m-y', $dataSourceString);
},
self::DATE_FORMAT_DDMMYYYY_DASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('d-m-Y', $dataSourceString);
},
self::DATE_FORMAT_DDMMYY_DOTS => function ($dataSourceString) {
return $this->_isValidByDateFormat('d.m.y', $dataSourceString);
},
self::DATE_FORMAT_DDMMYYYY_DOTS => function ($dataSourceString) {
return $this->_isValidByDateFormat('d.m.Y', $dataSourceString);
},
self::DATE_FORMAT_DDMMYY_SLASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('d/m/y', $dataSourceString);
},
self::DATE_FORMAT_DDMMYYYY_SLASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('d/m/Y', $dataSourceString);
},
self::DATE_FORMAT_MMDDYY_DASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('m-d-y', $dataSourceString);
},
self::DATE_FORMAT_MMDDYYYY_DASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('m-d-Y', $dataSourceString);
},
self::DATE_FORMAT_MMDDYY_DOTS => function ($dataSourceString) {
return $this->_isValidByDateFormat('m.d.y', $dataSourceString);
},
self::DATE_FORMAT_MMDDYYYY_DOTS => function ($dataSourceString) {
return $this->_isValidByDateFormat('m.d.Y', $dataSourceString);
},
self::DATE_FORMAT_MMDDYY_SLASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('m/d/y', $dataSourceString);
},
self::DATE_FORMAT_MMDDYYYY_SLASHES => function ($dataSourceString) {
return $this->_isValidByDateFormat('m/d/Y', $dataSourceString);
},
self::DATETIME_FORMAT_ISO_8601 => function ($dataSourceString) {
return $this->_isValidByDateFormat('Y-m-dTH:i:s', $dataSourceString);
},
self::DATETIME_FORMAT_MYSQL => function ($dataSourceString) {
return $this->_isValidByDateFormat('Y-m-d H:i:s', $dataSourceString);
}
);
}
protected $ruleValidation = array();
protected function _setDefaultRuleValidation()
{
$this->ruleValidation = array(
self::RULE_REQUIRED => function () {
$fieldName = func_get_arg(0);
return (array_key_exists($fieldName, $this->data));
},
self::RULE_EMAIL => function () {
$fieldValue = func_get_arg(1);
return filter_var($fieldValue, FILTER_VALIDATE_EMAIL);
},
self::RULE_NAME => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\s\-]+$/', $fieldValue) > 0);
},
self::RULE_ADDR_STREET => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\s\-\.]+$/', $fieldValue) > 0);
},
self::RULE_ADDR_STREET_NO => function () {
$fieldValue = func_get_arg(1);
return (preg_match(
'/^[[:digit:]]+[[:alpha:]]{0,1}(?:\s*\-\s*[[:digit:]]{0,}[[:alpha:]]*){0,1}$/',
$fieldValue
) > 0);
},
self::RULE_ADDR_STREET_PLUS_NO => function () {
$fieldValue = func_get_arg(1);
return (preg_match(
'/^[[:alpha:]äöüßÄÖÜ\s\-\.]+\s+[[:digit:]]+[[:alpha:]]{0,1}(?:\s*\-\s*[[:digit:]]{0,}[[:alpha:]]*){0,1}$/',
$fieldValue
) > 0);
},
self::RULE_ADDR_CITY => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\s\-\.]+$/', $fieldValue) > 0);
},
self::RULE_ADDR_ZIP => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[0-9]{5}$/', $fieldValue) > 0);
},
self::RULE_STR_WS_DASH_DOT => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\-\.]+$/', $fieldValue) > 0);
},
self::RULE_STR_WS_DASH_DOT_PAR => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\-\.\(\)]+$/', $fieldValue) > 0);
},
self::RULE_URL => function () {
$fieldValue = func_get_arg(1);
return filter_var($fieldValue, FILTER_VALIDATE_URL);
},
self::RULE_ALPHA => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alpha:]äöüßÄÖÜ]+$/', $fieldValue) > 0);
},
self::RULE_ALPHA_CAPS => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:upper:]ÄÖÜ]+$/', $fieldValue) > 0);
},
self::RULE_ALPHA_SMALL => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:lower:]äöüß]+$/', $fieldValue) > 0);
},
self::RULE_DIGIT => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:digit:]]+$/', $fieldValue) > 0);
},
self::RULE_DECIMAL => function () {
$fieldValue = func_get_arg(1);
return (preg_match(
'/^[[:digit:]]+(\\' . $this->decimalSeparator . '[[:digit:]]{1,})|[[:digit:]]$/',
$fieldValue
) > 0);
},
self::RULE_ALNUM => function () {
$fieldValue = func_get_arg(1);
return (preg_match('/^[[:alnum:]äöüßÄÖÜ]+$/', $fieldValue) > 0);
},
self::RULE_GENERAL_TEXT => function () {
$fieldValue = func_get_arg(1);
return (strip_tags($fieldValue) === $fieldValue);
},
self::RULE_DATE => function () {
$fieldValue = func_get_arg(1);
return ($this->dateValidation[$this->dateFormat]($fieldValue));
},
self::RULE_DATETIME => function () {
$fieldValue = func_get_arg(1);
return ($this->dateValidation[$this->dateTimeFormat]($fieldValue));
},
self::RULE_MIN_LENGTH => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
return (mb_strlen($fieldValue, 'UTF-8') >= $validationParam);
},
self::RULE_MAX_LENGTH => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
return (mb_strlen($fieldValue, 'UTF-8') <= $validationParam);
},
self::RULE_MIN_NUMERIC => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
return ((float)$fieldValue >= (float)$validationParam);
},
self::RULE_MAX_NUMERIC => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
return ((float)$fieldValue <= (float)$validationParam);
},
self::RULE_MIN_DATE => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
return ($this->_dateStrHasOrdinalRelToRefDateStr(
$fieldValue,
$validationParam,
self::ORDINAL_COMPARATOR_GTE
));
},
self::RULE_MAX_DATE => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
return ($this->_dateStrHasOrdinalRelToRefDateStr(
$fieldValue,
$validationParam,
self::ORDINAL_COMPARATOR_LTE
));
},
self::RULE_REQUIRES => function () {
$validationParam = func_get_arg(2);
$dataExists = array_key_exists($validationParam, $this->data);
if (!$dataExists) return false;
$fieldData = $this->data[$validationParam];
$isValid = true;
$dummyFieldStatusArr = [];
//If rules exist for other field, they have to be valid;
$this->_validateField($validationParam, $fieldData, $dummyFieldStatusArr, $isValid);
return $isValid;
},
self::RULE_EXTENDS => function ($fieldName, $fieldValue, $validationParam, array &$fieldStatusArr) {
$isValid = true;
$extendedRulesExists = array_key_exists($validationParam, $this->rules);
if (!$extendedRulesExists) return $isValid;
//Validate the data of this field against the rules of the extended Field
$this->_validateField($validationParam, $fieldValue, $fieldStatusArr, $isValid);
return $isValid;
},
self::RULE_IN => function () {
$fieldValue = func_get_arg(1);
$validationParam = func_get_arg(2);
$validValues = json_decode($validationParam, false);
$isValid = (is_array($validValues) && in_array($fieldValue, $validValues, true));
return $isValid;
},
self::RULE_INSTANCEOF => function () {
$obj = func_get_arg(1);
$objName = func_get_arg(2);
return (is_object($obj) && ($obj instanceof $objName));
},
self::RULE_FIELD => function () {
$obj = func_get_arg(1);
$nameValueStringArr = explode('=', func_get_arg(2), 2);
$fieldName = $nameValueStringArr[0];
$fieldValue = (array_key_exists(1, $nameValueStringArr) && strlen($nameValueStringArr[1]) > 0) ?
$nameValueStringArr[1] : true;
$objValue = false;
if (is_object($obj)) {
@$objValue = $obj->$fieldName;
}
return ($objValue == $fieldValue);
},
self::RULE_METHOD => function () {
$obj = func_get_arg(1);
$nameValueStringArr = explode('=', func_get_arg(2), 2);
$methodName = $nameValueStringArr[0];
$fieldValue = (array_key_exists(1, $nameValueStringArr) && strlen($nameValueStringArr[1]) > 0) ?
$nameValueStringArr[1] : true;
$objValue = false;
if (is_object($obj)) {
@$objValue = $obj->$methodName();
}
return ($objValue == $fieldValue);
},
self::RULE_EMPTY_ALLOWED => function () {
return true;
}
);
}
protected $errorMessages = array();
protected function _setDefaultErrorMsgCallables()
{
$this->errorMessages = array(
self::RULE_REQUIRED => function ($fieldName, $fieldValue, $validationParam) {
return (array_key_exists($fieldName, $this->data));
},
self::RULE_EMAIL => function ($fieldName, $fieldValue, $validationParam) {
return filter_var($fieldValue, FILTER_VALIDATE_EMAIL);
},
self::RULE_NAME => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\s\-]+$/', $fieldValue) > 0);
},
self::RULE_ADDR_STREET => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\s\-\.]+$/', $fieldValue) > 0);
},
self::RULE_ADDR_STREET_NO => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match(
'/^[[:digit:]]+[[:alpha:]]{0,1}(?:\s*\-\s*[[:digit:]]{0,}[[:alpha:]]*){0,1}$/',
$fieldValue
) > 0);
},
self::RULE_ADDR_STREET_PLUS_NO => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match(
'/^[[:alpha:]äöüßÄÖÜ\s\-\.]+\s+[[:digit:]]+[[:alpha:]]{0,1}(?:\s*\-\s*[[:digit:]]{0,}[[:alpha:]]*){0,1}$/',
$fieldValue
) > 0);
},
self::RULE_ADDR_CITY => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\s\-\.]+$/', $fieldValue) > 0);
},
self::RULE_ADDR_ZIP => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[0-9]{5}$/', $fieldValue) > 0);
},
self::RULE_STR_WS_DASH_DOT => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\-\.]+$/', $fieldValue) > 0);
},
self::RULE_STR_WS_DASH_DOT_PAR => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]äöüßÄÖÜ\-\.\(\)]+$/', $fieldValue) > 0);
},
self::RULE_URL => function ($fieldName, $fieldValue, $validationParam) {
return filter_var($fieldValue, FILTER_VALIDATE_URL);
},
self::RULE_ALPHA => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alpha:]äöüßÄÖÜ]+$/', $fieldValue) > 0);
},
self::RULE_ALPHA_CAPS => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:upper:]ÄÖÜ]+$/', $fieldValue) > 0);
},
self::RULE_ALPHA_SMALL => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:lower:]äöüß]+$/', $fieldValue) > 0);
},
self::RULE_DIGIT => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:digit:]]+$/', $fieldValue) > 0);
},
self::RULE_DECIMAL => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match(
'/^[[:digit:]]+(\\' . $this->decimalSeparator . '[[:digit:]]{1,})|[[:digit:]]$/',
$fieldValue
) > 0);
},
self::RULE_ALNUM => function ($fieldName, $fieldValue, $validationParam) {
return (preg_match('/^[[:alnum:]äöüßÄÖÜ]+$/', $fieldValue) > 0);
},
self::RULE_GENERAL_TEXT => function ($fieldName, $fieldValue, $validationParam) {
return (strip_tags($fieldValue) === $fieldValue);
},
self::RULE_DATE => function ($fieldName, $fieldValue, $validationParam) {
return ($this->dateValidation[$this->dateFormat]($fieldValue));
},
self::RULE_DATETIME => function ($fieldName, $fieldValue, $validationParam) {
return ($this->dateValidation[$this->dateTimeFormat]($fieldValue));
},
self::RULE_MIN_LENGTH => function ($fieldName, $fieldValue, $validationParam) {
return (mb_strlen($fieldValue, 'UTF-8') >= $validationParam);
},
self::RULE_MAX_LENGTH => function ($fieldName, $fieldValue, $validationParam) {
return (mb_strlen($fieldValue, 'UTF-8') <= $validationParam);
},
self::RULE_MIN_NUMERIC => function ($fieldName, $fieldValue, $validationParam) {
return ((float)$fieldValue >= (float)$validationParam);
},
self::RULE_MAX_NUMERIC => function ($fieldName, $fieldValue, $validationParam) {
return ((float)$fieldValue <= (float)$validationParam);
},
self::RULE_MIN_DATE => function ($fieldName, $fieldValue, $validationParam) {
return ($this->_dateStrHasOrdinalRelToRefDateStr(
$fieldValue,
$validationParam,
self::ORDINAL_COMPARATOR_GTE
));
},
self::RULE_MAX_DATE => function ($fieldName, $fieldValue, $validationParam) {
return ($this->_dateStrHasOrdinalRelToRefDateStr(
$fieldValue,
$validationParam,
self::ORDINAL_COMPARATOR_LTE
));
}
);
}
protected function _setRuleConstants()
{
$ref = new ReflectionClass($this);
$constants = $ref->getConstants();
foreach ($constants as $constName => $constVal) {
if (static::strStartsWith($constName, 'RULE_')) {
$this->ruleConstants[$constName] = $constVal;
}
}
}
/**
* @param $ruleName
* @return bool
*/
public function isValidRuleName($ruleName)
{
if (!(count($this->ruleConstants) > 0)) {
$this->_setRuleConstants();
}
return in_array($ruleName, $this->ruleConstants, true);
}
/**
* @param $ruleName
* @return bool
*/
public static function isValidDefaultInlineRuleName($ruleName)
{
$arr = array(
self::RULE_REQUIRED,
self::RULE_EMAIL,
self::RULE_NAME,
self::RULE_ADDR_STREET,
self::RULE_ADDR_STREET_NO,
self::RULE_ADDR_STREET_PLUS_NO,
self::RULE_ADDR_CITY,
self::RULE_ADDR_ZIP,
self::RULE_STR_WS_DASH_DOT,
self::RULE_STR_WS_DASH_DOT_PAR,
self::RULE_URL,
self::RULE_ALPHA,
self::RULE_ALPHA_CAPS,
self::RULE_ALPHA_SMALL,
self::RULE_DIGIT,
self::RULE_DECIMAL,
self::RULE_ALNUM,
self::RULE_GENERAL_TEXT,
self::RULE_DATE,
self::RULE_DATETIME,
self::RULE_MIN_LENGTH,
self::RULE_MAX_LENGTH,
self::RULE_MIN_NUMERIC,
self::RULE_MAX_NUMERIC,
self::RULE_MIN_DATE,
self::RULE_MAX_DATE,
self::RULE_CUST_REGEX
);
return (in_array($ruleName, $arr, 1));
}
/**
* @param $dateFormatString
* @param $dataSourceString
* @return bool
*/
protected function _isValidByDateFormat($dateFormatString, $dataSourceString)
{
$dateTime = \DateTime::createFromFormat($dateFormatString, $dataSourceString);
$dateTimeString = $dateTime->format($dateFormatString);
return ($dateTimeString === $dataSourceString);
}
/**
* Validator constructor.
* @param array $dataRules
* @param array|null $data
*/
public function __construct(array $dataRules, array $data = null)
{
$this->_setDefaultRuleValidation();
$this->_setDefaultDateFormatValidation();
if (null === $data) {
$data = [];
}
$this->setData($data);
if (is_array($dataRules)) {
foreach ($dataRules as $fieldName => $ruleStr) {
$this->_parseRuleString($fieldName, $ruleStr);
}
}
}
/**
* @param array $data
*/
public function setData(array $data)
{
foreach ($data as $dataKey => $dataVal) {
$this->data[$dataKey] = $dataVal;
}
}
/**
* @param $fieldName
* @param $ruleString
*/
protected function _parseRuleString($fieldName, $ruleString)
{
if (!array_key_exists($fieldName, $this->data)) {
throw new \InvalidArgumentException(
sprintf(
'%s is not the name of a data-item.',
strip_tags($fieldName)
)
);
}
$rules = explode(self::CONF_RULE_SEPARATOR, $ruleString);
if (!is_array($rules) || count($rules) < 1) {
throw new \InvalidArgumentException(
sprintf(
'%s is not a string of rules split by %s.',
strip_tags($rules),
self::CONF_RULE_SEPARATOR
)
);
}
foreach ($rules as $rule) {
$ruleParts = explode(self::CONF_RULE_VALUE_SEPARATOR, $rule, 2);
$ruleName = $ruleParts[0];
$ruleValue = (isset($ruleParts[1]) ? $ruleParts[1] : '');
if (self::RULE_CUST_REGEX !== $ruleName && !array_key_exists($ruleName, $this->ruleValidation)) {
throw new \InvalidArgumentException(
sprintf(
'%s is not a valid rule.',
strip_tags($ruleName)
)
);
}
if (self::RULE_CUST_REGEX === $ruleName) {
throw new \InvalidArgumentException('A custom regex-rule can only be set via method.');
}
$this->rules[$fieldName][$ruleName] = array('callable' => &$this->ruleValidation[$ruleName], 'ruleValue' => $ruleValue);
}
}
/**
* @param $dateStr
* @param $refDateStr
* @param $comparator
* @return bool
*/
protected function _dateStrHasOrdinalRelToRefDateStr($dateStr, $refDateStr, $comparator)
{
$dt = new \DateTime(strtotime($dateStr));
$dtRef = new \DateTime(strtotime($refDateStr));
switch ($comparator) {
case self::ORDINAL_COMPARATOR_EQ:
$isValid = ($dt->getTimestamp() === $dtRef->getTimestamp());
break;
case self::ORDINAL_COMPARATOR_LT:
$isValid = ($dt->getTimestamp() < $dtRef->getTimestamp());
break;
case self::ORDINAL_COMPARATOR_LTE:
$isValid = ($dt->getTimestamp() <= $dtRef->getTimestamp());
break;
case self::ORDINAL_COMPARATOR_GT:
$isValid = ($dt->getTimestamp() > $dtRef->getTimestamp());
break;
case self::ORDINAL_COMPARATOR_GTE:
$isValid = ($dt->getTimestamp() >= $dtRef->getTimestamp());
break;
default:
$isValid = ($dt->getTimestamp() === $dtRef->getTimestamp());
break;
}
return $isValid;
}
/**
* After validation, $fieldStatusArr will contain detialed information about the validation result, including rule-mismatch error-messages
* @param array|null $fieldStatusArr
* @param $data
* @return bool
*/
public function isValid(array &$fieldStatusArr,$data)
{
$this->_setErrorMessages();
if (null === $this->data) {
throw new \InvalidArgumentException(
'Method \'Cannot check validity while data is not set\''
);
}
$isValid = true;
$statusArr = array();
foreach ($this->data as $fieldName => $fieldValue) {
$singleFieldStatusArr = [];
$this->_validateField($fieldName, $fieldValue, $singleFieldStatusArr, $isValid);
$statusArr[$fieldName] = $singleFieldStatusArr;
}
$fieldStatusArr = $statusArr;
return $isValid;
}
/**
* @param $fieldName
* @param $fieldValue
* @param $singleFieldStatusArr
* @param $isValidTotal
* @return bool
*/
protected function _validateField($fieldName, $fieldValue, &$singleFieldStatusArr, &$isValidTotal)
{
$isValidField = true;
$unmatchedRules = [];
$appliedRulesString = '';
$i = 0;
if (isset($this->rules[$fieldName])) {
$emptyAllowed = (array_key_exists(Validator::RULE_EMPTY_ALLOWED,$this->rules[$fieldName]) || !array_key_exists(Validator::RULE_REQUIRED,$this->rules[$fieldName]));
if ($emptyAllowed && empty($fieldValue)) {
foreach ($this->rules[$fieldName] as $ruleName => $ruleArr) {
//$fieldValue = $this->data[$fieldName];
$ruleCallable = $ruleArr['callable'];
$ruleValue = $ruleArr['ruleValue'];
if ($i > 0) {
$appliedRulesString .= self::CONF_RULE_SEPARATOR;
}
$appliedRulesString .= $ruleName;
$fieldStatusArrTMP = [];
if (!$ruleCallable($fieldName, $fieldValue, $ruleValue, $fieldStatusArrTMP)) {
$isValidField = false;
$unmatchedRules = (isset($fieldStatusArrTMP['unmatchedRules']) ? $fieldStatusArrTMP['unmatchedRules'] : []);
$unmatchedRules[] = array('ruleName' => $ruleName, 'ruleValue' => $ruleValue, 'ruleError' => $this->getRuleErrorMessage(
$ruleName
));
$isValidTotal = false;
}
++$i;
}
}
$singleFieldStatusArr = array('value' => $fieldValue, 'valid' => $isValidField, 'appliedRules' => $appliedRulesString, 'unmatchedRules' => $unmatchedRules);
}
return $isValidField;
}
/**
* @return bool
*/
public function isInvalid()
{
$dummyArr = [];
return !($this->isValid($dummyArr));
}
/**
* @param array $rules
*/
public function setRules(array $rules)
{
if (null === $this->data) {
throw new \BadMethodCallException(
'Method \'setRules cannot be called while data is not set\''
);
}
foreach ($rules as $fieldName => $ruleStr) {
$this->_parseRuleString($fieldName, $ruleStr);
}
}
/**
* @param $ruleName
* @return mixed|string
*/
public function getRuleErrorMessage($ruleName)
{
if (isset($this->errorMessages[$ruleName])) {
return $this->errorMessages[$ruleName];
} else {
return '';
}
}
protected function _setErrorMessages()
{
$languageSuffix = strtoupper($this->languageCode);
$constRuleRequired = 'ERRORMSG_RULE_REQUIRED_' . $languageSuffix;
$constRuleEmail = 'ERRORMSG_RULE_EMAIL_' . $languageSuffix;
$constRuleName = 'ERRORMSG_RULE_NAME_' . $languageSuffix;
$constRuleAddrStreet = 'ERRORMSG_RULE_ADDR_STREET_' . $languageSuffix;
$constRuleAddrStreetNo = 'ERRORMSG_RULE_ADDR_STREET_NO_' . $languageSuffix;
$constRuleAddrStreetPlusNo = 'ERRORMSG_RULE_ADDR_STREET_PLUS_NO_' . $languageSuffix;
$constRuleAddrCity = 'ERRORMSG_RULE_ADDR_CITY_' . $languageSuffix;
$constRuleAddrZip = 'ERRORMSG_RULE_ADDR_ZIP_' . $languageSuffix;
$constRuleStrWsDashDot = 'ERRORMSG_RULE_STR_WS_DASH_DOT_' . $languageSuffix;
$constRuleStrWsDashDotPar = 'ERRORMSG_RULE_STR_WS_DASH_DOT_PAR_' . $languageSuffix;
$constRuleUrl = 'ERRORMSG_RULE_URL_' . $languageSuffix;
$constRuleAlpha = 'ERRORMSG_RULE_ALPHA_' . $languageSuffix;
$constRuleAlphaCaps = 'ERRORMSG_RULE_ALPHA_CAPS_' . $languageSuffix;
$constRuleAlphaSmall = 'ERRORMSG_RULE_ALPHA_SMALL_' . $languageSuffix;
$constRuleDigit = 'ERRORMSG_RULE_DIGIT_' . $languageSuffix;
$constRuleAlnum = 'ERRORMSG_RULE_ALNUM_' . $languageSuffix;
$constRuleDate = 'ERRORMSG_RULE_DATE_' . $languageSuffix;
$constRuleDatetime = 'ERRORMSG_RULE_DATETIME_' . $languageSuffix;
$constRuleMinNumeric = 'ERRORMSG_RULE_MIN_NUMERIC_' . $languageSuffix;
$constRuleMaxNumeric = 'ERRORMSG_RULE_MAX_NUMERIC_' . $languageSuffix;
$constRuleMinDate = 'ERRORMSG_RULE_MIN_DATE_' . $languageSuffix;
$constRuleMaxDate = 'ERRORMSG_RULE_MAX_DATE_' . $languageSuffix;
$constRuleCustRegex = 'ERRORMSG_RULE_CUST_REGEX_' . $languageSuffix;
$constRuleRequires = 'ERRORMSG_RULE_REQUIRES_' . $languageSuffix;
$constRuleMinLen = 'ERRORMSG_RULE_MIN_LENGTH_' . $languageSuffix;
$constRuleMaxLen = 'ERRORMSG_RULE_MAX_LENGTH_' . $languageSuffix;
$className = __CLASS__;
$ruleErrors = array(
self::RULE_REQUIRED => constant("$className::$constRuleRequired"),
self::RULE_EMAIL => constant("$className::$constRuleEmail"),
self::RULE_NAME => constant("$className::$constRuleName"),
self::RULE_ADDR_STREET => constant("$className::$constRuleAddrStreet"),
self::RULE_ADDR_STREET_NO => constant("$className::$constRuleAddrStreetNo"),
self::RULE_ADDR_STREET_PLUS_NO => constant("$className::$constRuleAddrStreetPlusNo"),
self::RULE_ADDR_CITY => constant("$className::$constRuleAddrCity"),
self::RULE_ADDR_ZIP => constant("$className::$constRuleAddrZip"),
self::RULE_STR_WS_DASH_DOT => constant("$className::$constRuleStrWsDashDot"),
self::RULE_STR_WS_DASH_DOT_PAR => constant("$className::$constRuleStrWsDashDotPar"),
self::RULE_URL => constant("$className::$constRuleUrl"),
self::RULE_ALPHA => constant("$className::$constRuleAlpha"),
self::RULE_ALPHA_CAPS => constant("$className::$constRuleAlphaCaps"),
self::RULE_ALPHA_SMALL => constant("$className::$constRuleAlphaSmall"),
self::RULE_DIGIT => constant("$className::$constRuleDigit"),
self::RULE_ALNUM => constant("$className::$constRuleAlnum"),
self::RULE_DATE => constant("$className::$constRuleDate"),
self::RULE_DATETIME => constant("$className::$constRuleDatetime"),
self::RULE_MIN_NUMERIC => constant("$className::$constRuleMinNumeric"),
self::RULE_MAX_NUMERIC => constant("$className::$constRuleMaxNumeric"),
self::RULE_MIN_DATE => constant("$className::$constRuleMinDate"),
self::RULE_MAX_DATE => constant("$className::$constRuleMaxDate"),
self::RULE_CUST_REGEX => constant("$className::$constRuleCustRegex"),
self::RULE_REQUIRES => constant("$className::$constRuleRequires"),
self::RULE_MIN_LENGTH => constant("$className::$constRuleMinLen"),
self::RULE_MAX_LENGTH => constant("$className::$constRuleMaxLen")
);
$this->errorMessages = $ruleErrors;
}
/**
* @param $haystack
* @param $needle
* @return bool
*/
public static function strStartsWith($haystack, $needle)
{
// search backwards starting from haystack length characters from the end
return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
}
/**
* @param $haystack
* @param $needle
* @return bool
*/
public static function strEndsWith($haystack, $needle)
{
// search forward starting from end minus needle length characters
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos(
$haystack,
$needle,
$temp
) !== false);
}
/**
* @param $dataItem
* @param $ruleString
* @return array
*/
public static function evaluateDataItemAgainstRuleString($dataItem, $ruleString)
{
$dataArr = array(
'dataItem' => $dataItem
);
$ruleArr = array(
'dataItem' => $ruleString
);
$validator = new self($ruleArr, $dataArr);
$fieldStatusArr = array();
$validator->isValid($fieldStatusArr);
unset($validator);
return $fieldStatusArr;
}
}

View File

@@ -0,0 +1,73 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\DOMTemplate;
use DynCom\mysyde\common\interfaces\PHTMLTemplate;
use DynCom\mysyde\common\interfaces\PlainTemplate;
use DynCom\mysyde\common\interfaces\Template;
use DynCom\mysyde\common\interfaces\ViewModel;
/**
* Created by PhpStorm.
* User: Michael Bauer
* Date: 7/14/2015
* Time: 2:43 AM
*/
class ViewFactory
{
protected $transformer;
/**
* @param RenderableStringTransformer $transformer
*/
public function __construct(RenderableStringTransformer $transformer) {
$this->transformer = $transformer;
}
/**
* @param Template $template
* @param ViewModel $viewModel
* @return GenericDOMView|GenericPHTMLView|GenericPlainView
* @throws \InvalidArgumentException
*/
public function getView(Template $template, ViewModel $viewModel) {
if($template instanceof PHTMLTemplate) {
return $this->getPHTMLView($template,$viewModel);
} elseif($template instanceof PlainTemplate) {
return $this->getPlainView($template,$viewModel);
} elseif($template instanceof DOMTemplate) {
return $this->getDOMView($template,$viewModel);
}
throw new \InvalidArgumentException(
"Temlate must be either PHTMLTemplate, PlainTemplate or DOMTemplate"
);
}
/**
* @param DOMTemplate $template
* @param ViewModel $viewModel
* @return GenericDOMView
*/
protected function getDOMView(DOMTemplate $template, ViewModel $viewModel) {
return new GenericDOMView($template,$viewModel,$this->transformer);
}
/**
* @param PlainTemplate $template
* @param ViewModel $viewModel
* @return GenericPlainView
*/
protected function getPlainView(PlainTemplate $template, ViewModel $viewModel) {
return new GenericPlainView($template,$viewModel,$this->transformer);
}
/**
* @param PHTMLTemplate $template
* @param ViewModel $viewModel
* @return GenericPHTMLView
*/
protected function getPHTMLView(PHTMLTemplate $template, ViewModel $viewModel) {
return new GenericPHTMLView($template,$viewModel);
}
}

View File

@@ -0,0 +1,135 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\Entity;
use DynCom\mysyde\common\interfaces\GenericDBModelInterface;
use DynCom\mysyde\common\traits\genericDBModelTrait;
use DynCom\mysyde\common\traits\universallyGettableTrait;
use DynCom\mysyde\dcShop\classes\Customer;
use DynCom\mysyde\dcShop\classes\Shop;
use DynCom\mysyde\dcShop\classes\ShopLanguage;
use DynCom\mysyde\dcShop\classes\User;
/**
* Class Visitor
*/
class Visitor implements GenericDBModelInterface, Entity
{
use genericDBModelTrait, universallyGettableTrait;
protected $id;
protected $session_id;
protected $last_ipv4_anon;
protected $last_ipv6_anon;
protected $session_date;
protected $valid_until;
protected $frontend_login;
protected $cookie_only;
protected $main_user_id;
protected $shop_salesperson_id;
protected $admin_login;
protected $main_admin_user_id;
protected $currency_code;
protected $data;
protected $remember_token;
protected $nav_login;
protected $serialized_objects;
/**
* @param mixed $serialized_objects
*/
public function setSerializedObjects($serialized_objects)
{
$this->serialized_objects = $serialized_objects;
}
/**
* Visitor constructor.
* @param VisitorConfig $config
*/
public function __construct(VisitorConfig $config)
{
$this->config = $config;
}
/**
* @return Visitor
*/
public function getNullObject()
{
return new self($this->config);
}
protected $user;
/**
* @param User $user
*/
public function setUser(User $user)
{
if (!((int)$user->last_visitor_id === (int)$this->id)) {
throw new \InvalidArgumentException('User\'s last visitor id must match id of visitor.');
}
$this->user = $user;
$this->updateHooks('changed',$this);
}
protected $customer;
/**
* @param Customer $customer
*/
public function setCustomer(Customer $customer)
{
if (!isset($this->user) || ($this->user->customer_no !== $customer->customer_no)) {
throw new \InvalidArgumentException('User needs to be set at visitor and user\'s customer no must match customer\'s customer no.');
}
$this->customer = $customer;
$this->updateHooks('changed',$this);
}
protected $site;
/**
* @param Site $site
*/
public function setSite(Site $site)
{
$this->site = $site;
$this->updateHooks('changed',$this);
}
protected $language;
/**
* @param Language $language
*/
public function setLanguage(Language $language)
{
$this->language = $language;
$this->updateHooks('changed',$this);
}
protected $shop;
/**
* @param Shop $shop
*/
public function setShop(Shop $shop)
{
$this->shop = $shop;
$this->updateHooks('changed',$this);
}
protected $shopLanguage;
/**
* @param ShopLanguage $shopLanguage
*/
public function setShopLanguage(ShopLanguage $shopLanguage)
{
$this->shopLanguage = $shopLanguage;
$this->updateHooks('changed',$this);
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\CriteriaHelperInterface;
use DynCom\mysyde\common\interfaces\GenericCollectionInterface;
use DynCom\mysyde\common\traits\genericCollectionTrait;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 15.01.2015
* Time: 11:27
*/
class VisitorCollection implements GenericCollectionInterface
{
use genericCollectionTrait;
/**
* @param VisitorConfig $config
* @param CriteriaHelperInterface $criteriaValidationService
*/
public function __construct( VisitorConfig $config, CriteriaHelperInterface $criteriaValidationService ) {
$this->elements = new \SplObjectStorage();
$this->config = $config;
$this->criteriaValidationService = $criteriaValidationService;
$this->entryClassName = $config->getModelClassName();
}
/**
* @return VisitorCollection
*/
public function getEmptyCollection() {
return new self($this->config,$this->criteriaValidationService);
}
/**
* @param mixed $instance
* @param bool $idCheck
*
* @return bool
*/
public function add($instance, $idCheck = FALSE) {
return $this->_addVisitor($instance, $idCheck);
}
/**
* @param Visitor $visitor
* @param bool $idCheck
* @return bool
*/
protected function _addVisitor(Visitor $visitor, $idCheck = FALSE) {
return $this->_add($visitor, $idCheck);
}
/**
* @param mixed $instance
* @param bool $idCheck
*
* @return bool
*/
public function remove($instance, $idCheck = FALSE) {
return $this->_removeVisitor($instance, $idCheck);
}
/**
* @param Visitor $visitor
* @param bool $idCheck
* @return bool
*/
protected function _removeVisitor(Visitor $visitor, $idCheck = FALSE) {
return $this->_remove($visitor, $idCheck);
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\ModelDBConfigInterface;
use DynCom\mysyde\common\traits\genericConfigTrait;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 15.01.2015
* Time: 11:26
*/
class VisitorConfig implements ModelDBConfigInterface {
use genericConfigTrait;
protected $modelClassName = 'DynCom\mysyde\common\classes\Visitor';
protected $tableName = 'main_visitor';
protected $altPrimary = array('session_id');
protected $mappedFields = array(
array('name'=>'id','type'=>'INT'),
array('name'=>'session_id','type'=>'VARCHAR'),
array('name'=>'last_ipv4_anon','type' => 'VARCHAR'),
array('name'=>'last_ipv6_anon','type' => 'VARCHAR'),
array('name'=>'session_date','type'=>'DATETIME'),
array('name'=>'valid_until','type'=>'DATETIME'),
array('name'=>'frontend_login','type'=>'TINYINT'),
array('name'=>'cookie_only','type'=>'TINYINT'),
array('name'=>'main_user_id','type'=>'INT'),
array('name'=>'shop_salesperson_id','type'=>'INT'),
array('name'=>'admin_login','type'=>'TINYINT'),
array('name'=>'main_admin_user_id','type'=>'INT'),
array('name'=>'currency_code','type'=>'VARCHAR'),
array('name'=>'data','type'=>'LONGTEXT'),
array('name'=>'remember_token','type'=>'VARCHAR'),
array('name'=>'nav_login','type'=>'TINYINT'),
array('name'=>'serialized_objects','type'=>'MEDIUMBLOB')
);
}

View File

@@ -0,0 +1,81 @@
<?php
namespace DynCom\mysyde\common\classes;
use DynCom\mysyde\common\interfaces\CriteriaHelperInterface;
use DynCom\mysyde\common\interfaces\GenericDBQueryWrapperInterface;
use DynCom\mysyde\common\interfaces\Repository;
use DynCom\mysyde\common\traits\genericRepositoryTrait;
use DynCom\mysyde\dcShop\classes\UserRepository;
/**
* Created by PhpStorm.
* User: Bauer
* Date: 15.01.2015
* Time: 11:27
*/
class VisitorRepository implements Repository
{
use genericRepositoryTrait;
/**
* VisitorRepository constructor.
* @param GenericDBQueryWrapperInterface $db
* @param VisitorConfig $config
* @param CriteriaHelperInterface $criteriaValidationService
* @param VisitorCollection $collection
* @param $cacheAll
*/
public function __construct( GenericDBQueryWrapperInterface $db, VisitorConfig $config, CriteriaHelperInterface $criteriaValidationService, VisitorCollection $collection, $cacheAll=false) {
$this->db = $db;
$this->config = $config;
$this->collection = $collection;
$this->collectionEntryClassName = $this->collection->getEntryClassName();
$this->tableName = $this->config->getTableName();
$this->altPrimary = $this->config->getAltPrimary();
$this->mappedFields = $this->config->getMappedFields();
}
/**
* @param $sessionID
* @return \DynCom\mysyde\common\interfaces\Entity
*/
public function findBySessionID( $sessionID ) {
$visitor = $this->getNullObject();
if($this->cacheAll) {
$this->_cacheAll();
}
//Try from collection
foreach($this->collection as $instance) {
if(isset($instance->session_id) && ($instance->session_id == $sessionID)) {
return $instance;
}
}
//Else try from db
$query = "SELECT * FROM `" . $this->tableName . "` WHERE `session_id` = :sessionID";
if ($this->db->setQuery($query) && $this->db->prepareQuery() && $this->db->bindParameters(array(array(':sessionID', $sessionID, \PDO::PARAM_STR))) && $this->db->executePreparedStatement() && ($resArr = $this->db->getResultArray()) && (count($resArr) == 1)) {
$visitor->mapFromArray($resArr[0]);
return $visitor;
}
return $visitor;
}
/**
* @return Visitor
*/
public function getFromSession() {
return $this->findBySessionID(session_id());
}
/**
* @param UserRepository $userRepository
* @return mixed
*/
public function getUserFromSession(UserRepository $userRepository) {
$currVisitor = $this->getFromSession();
return $userRepository->findByID($currVisitor->main_user_id);
}
}

File diff suppressed because it is too large Load Diff

327
mysyde/common/common.js Normal file
View File

@@ -0,0 +1,327 @@
function changeBg(a, img1, img2) {
if (!a) {
return true;
}
if (a.style.backgroundImage == "url(" + img1 + ")") {
a.style.backgroundImage = "url(" + img2 + ")";
} else {
a.style.backgroundImage = "url(" + img1 + ")";
}
return true;
}
function toggleOn(a) {
var e = document.getElementById(a);
if (!e) {
return true;
}
e.style.display = "block";
return true;
}
function toggleOff(a) {
var e = document.getElementById(a);
if (!e) {
return true;
}
e.style.display = "none";
return true;
}
function toggle(a) {
var e = document.getElementById(a);
if (e.style.display != "block") {
if (!e) {
return true;
}
e.style.display = "block";
} else {
e.style.display = "none";
}
}
function toggleOnnb(a) {
var e = document.getElementById(a);
if (!e) {
return true;
}
e.style.display = "";
return true;
}
function toggleOffnb(a) {
var e = document.getElementById(a);
if (!e) {
return true;
}
e.style.display = "none";
return true;
}
function togglenb(a) {
var e = document.getElementById(a);
if (e.style.display != "") {
if (!e) {
return true;
}
e.style.display = "";
} else {
e.style.display = "none";
}
}
function toggleByClass(a) {
var e = document.getElementByClassName(a);
if (e.style.display != "block") {
if (!e) {
return true;
}
e.style.display = "block";
} else {
e.style.display = "none";
}
}
function MM_jumpMenu(targ, selObj, restore) { //v3.0
eval(targ + ".location='" + selObj.options[selObj.selectedIndex].value + "'");
if (restore) {
selObj.selectedIndex = 0;
}
}
function openPopup(URL, WIDTH, HEIGHT) {
if (!WIDTH) {
WIDTH = 600;
}
if (!HEIGHT) {
HEIGHT = 600;
}
WIDTH = 600;
HEIGHT = 600;
popup = window.open(URL, "popup", "width=" + WIDTH + ", height=" + HEIGHT + ", scrollbars=no");
}
function showLayer(lyr) {
makeHistory(lyr);
document.getElementById(currentLayer).className = 'hide';
document.getElementById(lyr).className = 'show';
currentLayer = lyr;
}
function showTab(lyr) {
document.getElementById(currentTab).className = 'taboff';
document.getElementById(lyr).className = 'tabon';
currentTab = lyr;
}
function makeHistory(newHash) {
window.location.hash = "_" + newHash;
expectedHash = window.location.hash;
return true;
}
function handleHistory() {
if (window.location.hash != expectedHash) {
expectedHash = window.location.hash;
if (expectedHash.match('tab')) {
showLayer(expectedHash.substring(2));
}
}
return true;
}
function pollHash() {
handleHistory();
window.setInterval("handleHistory()", 200);
return true;
}
function toggleDiv(id) {
/*
var obj=document.getElementsByTagName("div");
for(i=0;i<obj.length;i++) {
if(obj[i].collectionEntityClassName =="func") {
obj[i].style.display="none";
}
}
*/
if (document.getElementById(id).style.display == 'none') {
document.getElementById(id).style.display = 'block';
document.getElementById('head_' + id).className = 'function_cat open';
} else {
document.getElementById(id).style.display = 'none';
document.getElementById('head_' + id).className = 'function_cat closed';
}
}
function MM_swapImgRestore() { //v3.0
var i, x, a = document.MM_sr;
for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) {
x.src = x.oSrc;
}
}
function MM_preloadImages() { //v3.0
var d = document;
if (d.images) {
if (!d.MM_p) {
d.MM_p = new Array();
}
var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
for (i = 0; i < a.length; i++) {
if (a[i].indexOf("#") != 0) {
d.MM_p[j] = new Image;
d.MM_p[j++].src = a[i];
}
}
}
}
function MM_findObj(n, d) { //v4.01
var p, i, x;
if (!d) {
d = document;
}
if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
d = parent.frames[n.substring(p + 1)].document;
n = n.substring(0, p);
}
if (!(x = d[n]) && d.all) {
x = d.all[n];
}
for (i = 0; !x && i < d.forms.length; i++) {
x = d.forms[i][n];
}
for (i = 0; !x && d.layers && i < d.layers.length; i++) {
x = MM_findObj(n, d.layers[i].document);
}
if (!x && d.getElementById) {
x = d.getElementById(n);
}
return x;
}
function MM_swapImage() { //v3.0
var i, j = 0, x, a = MM_swapImage.arguments;
document.MM_sr = new Array;
for (i = 0; i < (a.length - 2); i += 3) {
if ((x = MM_findObj(a[i])) != null) {
document.MM_sr[j++] = x;
if (!x.oSrc) {
x.oSrc = x.src;
}
x.src = a[i + 2];
}
}
}
$(document).ready(function () {
$('.modal-iframe').click(function () {
e = $(this);
$('iframe', '#iframeContent').load(e.data("target"));
$('#iframeContent').modal({show: true})
});
$('.share_popup').on("click", function (e) {
e.preventDefault();
var t = $(this).data("target"), r = "_blank", i = "600", n = "460", a = "width=" + i + ",height=" + n;
window.open(t, r, a)
});
/* $('#itemcard_order_button_form_indiv select').attr('disabled', 'disabled');
$('#itemcard_order_button_form_std select').removeAttr('disabled');
*/
$('.itemcard_order_button_radio_wrapper_inner').change('input', function () {
if ($('#itemcard_order_type_choice_1').is(":checked")) {
$('#itemcard_order_button_form_indiv_outer').addClass('itemcard_order_button_inactive');
$('#itemcard_order_button_form_std_outer').removeClass('itemcard_order_button_inactive');
$('div[u="slides"] > div:nth-child(2) > div > img[cust_img="0"]').click();
$('#itemcard_order_button_form_indiv select').attr('disabled', 'disabled');
$('#itemcard_order_button_form_std select').removeAttr('disabled');
} else {
$('#itemcard_order_button_form_indiv_outer').removeClass('itemcard_order_button_inactive');
$('#itemcard_order_button_form_std_outer').addClass('itemcard_order_button_inactive');
$('div[u="thumbnavigator"] img[cust_img="1"]').click();
$('#itemcard_order_button_form_std select').attr('disabled', 'disabled');
$('#itemcard_order_button_form_indiv select').removeAttr('disabled');
}
});
$('.customize_delete_pic').click(function (e) {
var obj = $(this);
e.preventDefault();
var request = $.ajax({
url: '/module/dcshop/b2c/ajax.php' + $(obj).attr('href'),
method: "POST"
});
request.done(function (msg) {
var obj2 = $(obj).parents(".cust_img_area")
$(obj2).html(msg);
$(obj2).on("change", "input[type='file']", function () {
$(obj2).find('input[type="text"]').val(this.files[0].name);
})
});
});
$('.slidecontent_headline').click(function () {
$(this).toggleClass('active');
$(this).next('.slidecontent_content_container').slideToggle('fast');
});
$('#header_shop_icons .header_icon_search').click(function () {
$('#header_4').slideToggle('fast');
$('#header_4 #input_search').focus();
});
$('.datepicker').datepicker({
format: "dd.mm.yyyy",
language: "de"
});
$("#form_search").submit(function (e) {
if (!$("#form_search").find('#input_search').val()) {
e.preventDefault(e);
e.stopPropagation(e);
}
});
var flashMessage = $('.flashMessage');
var flashSpeed = 'slow';
var flashDelay = '20000';
$(window).load(function(){
flashMessage.fadeIn(flashSpeed);
$(function() {
setTimeout(function() {
flashMessage.fadeOut(flashSpeed);
},flashDelay);
});
flashMessage.click(function(){
$(this).fadeOut(flashSpeed);
});
});
$('.jumpmark').click(function () {
scrolling($(this).attr('href'));
})
});
!function (a) {
a.fn.datepicker.dates.de = {
days: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
daysShort: ["Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam"],
daysMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
monthsShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
today: "Heute",
monthsTitle: "Monate",
clear: "Löschen",
weekStart: 1,
format: "dd.mm.yyyy"
}
}(jQuery);
function isTouchDevice() {
var el = document.createElement('div');
el.setAttribute('ontouchstart', 'return;');
if(typeof el.ontouchstart == "function"){
return true;
}else {
return false
}
}
function scrolling(tabcontent_id) {
var ziel = $(tabcontent_id);
var top = ziel.offset().top;
var heightHeader = $('#header').outerHeight();
$('html,body').animate({
scrollTop: top - heightHeader
}, 800);
}
mejs.i18n.language('de');

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This 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.

View File

@@ -0,0 +1,32 @@
cookieBAR
=============
cookieBAR is a free & easy solution to the EU cookie law.
##### Why use cookieBAR?
There is a lot of mystery and fuss surrounding the new EU cookie legislation, but it's essentially really simple. Cookies are files used to track site activity and most websites use them. Site owners need to make the use of cookies very obvious to visitors.
Cookie bar makes it simple and clear to visitors that cookies are in use and tells them how to adjust browser settings if they are concerned.
##### TL;DR
Just place this somewhere in your website and forget it:
http://cdn.jsdelivr.net/cookie-bar/latest/cookiebar-latest.js
##### DEMO AND CONFIGURATION
Everyone wants to see a demo before downloading something, isn't it? You can see a demo on [cookie-bar.eu](http://cookie-bar.eu/). You can even use the configuration wizard to make the bar more compliant to your needs.
##### How it works?
cookieBAR is a drop-in and forget, pure vanilla javascript plugin, with no jQuery nor any other dependency needed. It shows up when needed and stay silent when not: if a website has a cookie or some localStorage data set then the bar is shown, otherwhise nothing happens.
Once user clicks `Allow Cookies` cookieBAR will set a cookie for that domain with a name `cookiebar` that will expire in 30 days. What this means is that the plugin will only show up once month (this duration is configurable).
If a user decides to click `Disallow Cookies`, cookieBAR will simply remove all cookies and localStorage data (and will show up again the first time a cookie is detected).
Having a `cookiebar` cookie makes it simple to developers to check the user decision before activating external scripts (such as Google Analytics, or anything else). See [http://cookie-bar.eu](http://cookie-bar.eu/) for more informations.

View File

@@ -0,0 +1,250 @@
#cookie-bar {
font-size: 13px;
}
#cookie-bar-prompt-content {
font-size: 13px;
max-height: 85vh;
}
#cookie-bar-browsers a {
width: 60px;
}
@media only screen and (max-device-width: 800px) {
#cookie-bar {
font-size: 12px;
}
#cookie-bar-prompt-content {
font-size: 11px;
max-height: 80vh;
}
#cookie-bar-browsers a {
width: 50px;
}
}
#cookie-bar {
background: #45484D;
background: -moz-linear-gradient(top, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(30,30,30,0.95)), color-stop(100%,rgba(0,0,0,0.95)));
background: -webkit-linear-gradient(top, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);
background: -o-linear-gradient(top, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);
background: -ms-linear-gradient(top, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);
background: linear-gradient(to bottom, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);
font-family: font-family: 'Open Sans', sans-serif;
font-size: 10pt !important;
left: 0;
line-height: 1.5;
margin: 0;
padding: 3px;
position: fixed;
width: 100%;
z-index: 9999;
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#cc45484d', endColorstr='#cc000000',GradientType=0 );
}
#cookie-bar-prompt {
background: #000;
background: rgba(0,0,0,0.4);
font-family: 'Open Sans', sans-serif;
font-size: 10pt !important;
height: 100%;
left: 0;
line-height: 1.5;
position: fixed;
top: 0;
width: 100%;
z-index: 9998;
}
#cookie-bar *,
#cookie-bar-prompt * {
line-height: 1.5;
}
#cookie-bar p {
font-size: 10pt !important;
float: left;
margin: 4px 0 0 20px;
padding: 0;
color: #FFF;
font-family: 'Open Sans', sans-serif;
}
#cookie-bar-prompt p {
font-family: 'Open Sans', sans-serif;
color: #FFF;
}
#cookie-bar-button {
background-color: #222;
border-bottom: 1px solid #222;
color: #FFF !important;
cursor: pointer;
display: inline-block;
float: right;
font-weight: normal;
line-height: 1;
margin-right: 20px;
margin-top: 2px;
padding: 5px 10px 6px;
position: relative;
text-decoration: none;
border: solid 1px #8dc63f;
}
#cookie-bar-button-no {
background-color: #D02828;
border-bottom: 1px solid #222;
border-radius: 5px;
color: #FFF!important;
cursor: pointer;
display: inline-block;
float: right;
font-weight: bold;
line-height: 1;
margin-right: 20px;
margin-top: 2px;
padding: 5px 10px 6px;
position: relative;
text-decoration: none;
text-shadow: 0 -1px 1px #222;
}
#cookie-bar-prompt a {
cursor: pointer;
}
#cookie-bar-prompt hr {
background: #FFF;
border: none;
height: 1px;
margin: 0.7em 0 1em;
opacity: 0.2;
}
#cookie-bar-prompt-content, #cookie-bar {
color: #FFF;
font-weight: 300;
}
#cookie-bar-prompt-content::-webkit-scrollbar-track {
border-radius: 10px;
background-color: #222;
background-color: rgba(255,255,255,0.05);
}
#cookie-bar-prompt-content::-webkit-scrollbar {
width: 15px;
}
#cookie-bar-prompt-content::-webkit-scrollbar-thumb {
box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
background-color: #EEE;
background-color: rgba(255,255,255,0.3);
border-radius: 10px;
}
#cookie-bar-prompt-content a, #cookie-bar a, #cookie-bar-prompt-content span {
color: #8dc63f;
text-decoration: none;
}
#cookie-bar-prompt-content a:hover, #cookie-bar a:hover {
color: #8dc63f;
text-decoration: underline;
}
#cookie-bar-prompt-close {
background: url(x.png) no-repeat;
display: block;
float: right;
height: 14px;
width: 14px;
}
#cookie-bar-prompt-logo {
background: url(logo.png) no-repeat;
display: block;
float: left;
height: 42px;
width: 190px;
}
#cookie-bar-prompt-close span, #cookie-bar-prompt-logo span {
display: none;
}
#cookie-bar-prompt-button {
cursor: pointer;
}
#cookie-bar-prompt-content {
background: #111;
border-radius: 7px;
box-shadow: 1px 2px 8px rgba(0,0,0,0.5);
color: #FFF;
margin: 0 auto;
max-width: 98%;
opacity: 0.97;
overflow: auto;
padding: 25px;
position: relative;
top: 5%;
width: 600px;
z-index: 9998;
}
#cookie-bar-thirdparty {
display: none;
}
#cookie-bar-tracking {
display: none;
}
#cookie-bar-scrolling {
display: none;
}
#cookie-bar-privacy-page {
display: none;
}
#cookie-bar-browsers a {
display: inline-block;
height: 53px;
margin: 0;
padding: 0;
position: relative;
}
#cookie-bar-browsers a span {
background: #FFF;
border-radius: 2px;
color: #000 !important;
display: none;
left: -10px;
opacity: 0.8;
padding: 3px 10px;
position: absolute;
text-align: center;
top: 60px;
width: 150px;
}
#cookie-bar-browsers .chrome {
background: url(browsers/chrome.png) no-repeat;
}
#cookie-bar-browsers .firefox {
background: url(browsers/firefox.png) no-repeat;
}
#cookie-bar-browsers .ie {
background: url(browsers/ie.png) no-repeat;
}
#cookie-bar-browsers .opera {
background: url(browsers/opera.png) no-repeat;
}
#cookie-bar-browsers .safari {
background: url(browsers/safari.png) no-repeat;
}
#cookie-bar-browsers a:hover span {
display: block;
}
.clear {
clear: both;
}

View File

@@ -0,0 +1 @@
#cookie-bar{font-size:13px}#cookie-bar-prompt-content{font-size:13px;max-height:85vh}#cookie-bar-browsers a{width:60px}@media only screen and (max-device-width:800px){#cookie-bar{font-size:12px}#cookie-bar-prompt-content{font-size:11px;max-height:80vh}#cookie-bar-browsers a{width:50px}}#cookie-bar{background:#45484d;background:-moz-linear-gradient(top,rgba(30,30,30,0.95) 0,rgba(0,0,0,0.95) 100%);background:-webkit-gradient(linear,left top,left bottom,color-stop(0,rgba(30,30,30,0.95)),color-stop(100%,rgba(0,0,0,0.95)));background:-webkit-linear-gradient(top,rgba(30,30,30,0.95) 0,rgba(0,0,0,0.95) 100%);background:-o-linear-gradient(top,rgba(30,30,30,0.95) 0,rgba(0,0,0,0.95) 100%);background:-ms-linear-gradient(top,rgba(30,30,30,0.95) 0,rgba(0,0,0,0.95) 100%);background:linear-gradient(to bottom,rgba(30,30,30,0.95) 0,rgba(0,0,0,0.95) 100%);font-family:font-family:'Open Sans',sans-serif;font-size:10pt !important;left:0;line-height:1.5;margin:0;padding:3px;position:fixed;width:100%;z-index:9999;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#cc45484d',endColorstr='#cc000000',GradientType=0)}#cookie-bar-prompt{background:#000;background:rgba(0,0,0,0.4);font-family:'Open Sans',sans-serif;font-size:10pt !important;height:100%;left:0;line-height:1.5;position:fixed;top:0;width:100%;z-index:9998}#cookie-bar *,#cookie-bar-prompt *{line-height:1.5}#cookie-bar p{font-size:10pt !important;float:left;margin:4px 0 0 20px;padding:0;color:#FFF;font-family:'Open Sans',sans-serif}#cookie-bar-prompt p{font-family:'Open Sans',sans-serif;color:#FFF}#cookie-bar-button{background-color:#222;border-bottom:1px solid #222;color:#FFF !important;cursor:pointer;display:inline-block;float:right;font-weight:normal;line-height:1;margin-right:20px;margin-top:2px;padding:5px 10px 6px;position:relative;text-decoration:none;border:solid 1px #8dc63f}#cookie-bar-button-no{background-color:#d02828;border-bottom:1px solid #222;border-radius:5px;color:#FFF !important;cursor:pointer;display:inline-block;float:right;font-weight:bold;line-height:1;margin-right:20px;margin-top:2px;padding:5px 10px 6px;position:relative;text-decoration:none;text-shadow:0 -1px 1px #222}#cookie-bar-prompt a{cursor:pointer}#cookie-bar-prompt hr{background:#FFF;border:0;height:1px;margin:.7em 0 1em;opacity:.2}#cookie-bar-prompt-content,#cookie-bar{color:#FFF;font-weight:300}#cookie-bar-prompt-content::-webkit-scrollbar-track{border-radius:10px;background-color:#222;background-color:rgba(255,255,255,0.05)}#cookie-bar-prompt-content::-webkit-scrollbar{width:15px}#cookie-bar-prompt-content::-webkit-scrollbar-thumb{box-shadow:inset 0 0 6px rgba(0,0,0,0.5);background-color:#EEE;background-color:rgba(255,255,255,0.3);border-radius:10px}#cookie-bar-prompt-content a,#cookie-bar a,#cookie-bar-prompt-content span{color:#8dc63f;text-decoration:none}#cookie-bar-prompt-content a:hover,#cookie-bar a:hover{color:#8dc63f;text-decoration:underline}#cookie-bar-prompt-close{background:url(x.png) no-repeat;display:block;float:right;height:14px;width:14px}#cookie-bar-prompt-logo{background:url(logo.png) no-repeat;display:block;float:left;height:42px;width:190px}#cookie-bar-prompt-close span,#cookie-bar-prompt-logo span{display:none}#cookie-bar-prompt-button{cursor:pointer}#cookie-bar-prompt-content{background:#111;border-radius:7px;box-shadow:1px 2px 8px rgba(0,0,0,0.5);color:#FFF;margin:0 auto;max-width:98%;opacity:.97;overflow:auto;padding:25px;position:relative;top:5%;width:600px;z-index:9998}#cookie-bar-thirdparty{display:none}#cookie-bar-tracking{display:none}#cookie-bar-scrolling{display:none}#cookie-bar-privacy-page{display:none}#cookie-bar-browsers a{display:inline-block;height:53px;margin:0;padding:0;position:relative}#cookie-bar-browsers a span{background:#FFF;border-radius:2px;color:#000 !important;display:none;left:-10px;opacity:.8;padding:3px 10px;position:absolute;text-align:center;top:60px;width:150px}#cookie-bar-browsers .chrome{background:url(browsers/chrome.png) no-repeat}#cookie-bar-browsers .firefox{background:url(browsers/firefox.png) no-repeat}#cookie-bar-browsers .ie{background:url(browsers/ie.png) no-repeat}#cookie-bar-browsers .opera{background:url(browsers/opera.png) no-repeat}#cookie-bar-browsers .safari{background:url(browsers/safari.png) no-repeat}#cookie-bar-browsers a:hover span{display:block}.clear{clear:both}

View File

@@ -0,0 +1,223 @@
#cookie-bar {
font-size: 13px;
}
#cookie-bar-prompt-content {
font-size: 13px;
max-height: 85vh;
}
#cookie-bar-browsers a {
width: 60px;
}
@media only screen and (max-device-width: 800px) {
#cookie-bar {
font-size: 12px;
}
#cookie-bar-prompt-content {
font-size: 11px;
max-height: 80vh;
}
#cookie-bar-browsers a {
width: 50px;
}
}
#cookie-bar {
background: #eeeeee;
font-family: "Open Sans",Helvetica,Arial,sans-serif;
font-size: 10pt;
left: 0;
line-height: 1.5;
margin: 0;
padding: 3px;
position: fixed;
width: 100%;
z-index: 9999;
}
#cookie-bar-prompt {
background: #000;
background: rgba(0,0,0,0.4);
font-family: "Open Sans",Helvetica,Arial,sans-serif;
font-size: 10pt;
height: 100%;
left: 0;
line-height: 1.5;
position: fixed;
top: 0;
width: 100%;
z-index: 9998;
}
#cookie-bar *,
#cookie-bar-prompt * {
margin: 0;
padding: 0;
line-height: 1.5;
}
#cookie-bar p {
float: left;
margin: 4px 0 0 20px;
padding: 0;
color: #999999;
font-family: sans-serif;
}
#cookie-bar-prompt p {
font-family: "Open Sans",Helvetica,Arial,sans-serif;
color: #FFF;
}
#cookie-bar-button {
background-color: #99c137;
color: #FFF !important;
cursor: pointer;
display: inline-block;
float: right;
font-weight: bold;
line-height: 1;
margin-right: 20px;
margin-top: 2px;
padding: 5px 10px 6px;
position: relative;
text-decoration: none;
}
#cookie-bar-button-no {
background-color: #D02828;
color: #FFF!important;
cursor: pointer;
display: inline-block;
float: right;
font-weight: bold;
line-height: 1;
margin-right: 20px;
margin-top: 2px;
padding: 5px 10px 6px;
position: relative;
text-decoration: none;
}
#cookie-bar-prompt a {
cursor: pointer;
}
#cookie-bar-prompt hr {
background: #FFF;
border: none;
height: 1px;
margin: 0.7em 0 1em;
opacity: 0.2;
}
#cookie-bar-prompt-content, #cookie-bar {
color: #FFF;
font-weight: 300;
}
#cookie-bar-prompt-content::-webkit-scrollbar-track {
background-color: #45484D;
}
#cookie-bar-prompt-content::-webkit-scrollbar {
width: 15px;
}
#cookie-bar-prompt-content::-webkit-scrollbar-thumb {
box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
background-color: #EEE;
background-color: rgba(255,255,255,0.3);
}
#cookie-bar-prompt-close {
background: url(x.png) no-repeat;
display: block;
float: right;
height: 14px;
width: 14px;
}
#cookie-bar-prompt-logo {
background: url(logo.png) no-repeat;
display: block;
float: left;
height: 42px;
width: 190px;
}
#cookie-bar-prompt-close span, #cookie-bar-prompt-logo span {
display: none;
}
#cookie-bar-prompt-button {
cursor: pointer;
}
#cookie-bar-prompt-content {
background: #45484D;
box-shadow: 2px 2px 4px rgba(0,0,0,0.5);
color: #FFF;
margin: 0 auto;
max-width: 98%;
overflow: auto;
padding: 25px;
position: relative;
top: 5%;
width: 600px;
z-index: 9998;
}
#cookie-bar-thirdparty {
display: none;
}
#cookie-bar-tracking {
display: none;
}
#cookie-bar-scrolling {
display: none;
}
#cookie-bar-privacy-page {
display: none;
}
#cookie-bar-browsers a {
display: inline-block;
height: 53px;
margin: 0;
padding: 0;
position: relative;
}
#cookie-bar-browsers a span {
background: #FFF;
border-radius: 2px;
color: #000 !important;
display: none;
left: -10px;
opacity: 0.8;
padding: 3px 10px;
position: absolute;
text-align: center;
top: 60px;
width: 150px;
}
#cookie-bar-browsers .chrome {
background: url(browsers/chrome.png) no-repeat;
}
#cookie-bar-browsers .firefox {
background: url(browsers/firefox.png) no-repeat;
}
#cookie-bar-browsers .ie {
background: url(browsers/ie.png) no-repeat;
}
#cookie-bar-browsers .opera {
background: url(browsers/opera.png) no-repeat;
}
#cookie-bar-browsers .safari {
background: url(browsers/safari.png) no-repeat;
}
#cookie-bar-browsers a:hover span {
display: block;
}
.clear {
clear: both;
}

View File

@@ -0,0 +1 @@
#cookie-bar{font-size:13px}#cookie-bar-prompt-content{font-size:13px;max-height:85vh}#cookie-bar-browsers a{width:60px}@media only screen and (max-device-width: 800px){#cookie-bar{font-size:12px}#cookie-bar-prompt-content{font-size:11px;max-height:80vh}#cookie-bar-browsers a{width:50px}}#cookie-bar{background:#45484D;font-family:Arial, Helvetica, sans-serif;font-size:10pt;left:0;line-height:1.5;margin:0;padding:3px;position:fixed;width:100%;z-index:9999}#cookie-bar-prompt{background:#000;background:rgba(0,0,0,0.4);font-family:Arial, Helvetica, sans-serif;font-size:10pt;height:100%;left:0;line-height:1.5;position:fixed;top:0;width:100%;z-index:9998}#cookie-bar *,#cookie-bar-prompt *{margin:0;padding:0;line-height:1.5}#cookie-bar p{float:left;margin:4px 0 0 20px;padding:0;color:#FFF;font-family:sans-serif}#cookie-bar-prompt p{font-family:Arial, Helvetica, sans-serif;color:#FFF}#cookie-bar-button{background-color:#1FAE16;color:#FFF !important;cursor:pointer;display:inline-block;float:right;font-weight:bold;line-height:1;margin-right:20px;margin-top:2px;padding:5px 10px 6px;position:relative;text-decoration:none}#cookie-bar-button-no{background-color:#D02828;color:#FFF !important;cursor:pointer;display:inline-block;float:right;font-weight:bold;line-height:1;margin-right:20px;margin-top:2px;padding:5px 10px 6px;position:relative;text-decoration:none}#cookie-bar-prompt a{cursor:pointer}#cookie-bar-prompt hr{background:#FFF;border:none;height:1px;margin:0.7em 0 1em;opacity:0.2}#cookie-bar-prompt-content,#cookie-bar{color:#FFF;font-weight:300}#cookie-bar-prompt-content::-webkit-scrollbar-track{background-color:#45484D}#cookie-bar-prompt-content::-webkit-scrollbar{width:15px}#cookie-bar-prompt-content::-webkit-scrollbar-thumb{box-shadow:inset 0 0 6px rgba(0,0,0,0.5);background-color:#EEE;background-color:rgba(255,255,255,0.3)}#cookie-bar-prompt-content a,#cookie-bar a,#cookie-bar-prompt-content span{color:#31A8F0;text-decoration:none}#cookie-bar-prompt-content a:hover,#cookie-bar a:hover{color:#31A8F0;text-decoration:underline}#cookie-bar-prompt-close{background:url(x.png) no-repeat;display:block;float:right;height:14px;width:14px}#cookie-bar-prompt-logo{background:url(logo.png) no-repeat;display:block;float:left;height:42px;width:190px}#cookie-bar-prompt-close span,#cookie-bar-prompt-logo span{display:none}#cookie-bar-prompt-button{cursor:pointer}#cookie-bar-prompt-content{background:#45484D;box-shadow:2px 2px 4px rgba(0,0,0,0.5);color:#FFF;margin:0 auto;max-width:98%;overflow:auto;padding:25px;position:relative;top:5%;width:600px;z-index:9998}#cookie-bar-thirdparty{display:none}#cookie-bar-tracking{display:none}#cookie-bar-scrolling{display:none}#cookie-bar-privacy-page{display:none}#cookie-bar-browsers a{display:inline-block;height:53px;margin:0;padding:0;position:relative}#cookie-bar-browsers a span{background:#FFF;border-radius:2px;color:#000 !important;display:none;left:-10px;opacity:0.8;padding:3px 10px;position:absolute;text-align:center;top:60px;width:150px}#cookie-bar-browsers .chrome{background:url(browsers/chrome.png) no-repeat}#cookie-bar-browsers .firefox{background:url(browsers/firefox.png) no-repeat}#cookie-bar-browsers .ie{background:url(browsers/ie.png) no-repeat}#cookie-bar-browsers .opera{background:url(browsers/opera.png) no-repeat}#cookie-bar-browsers .safari{background:url(browsers/safari.png) no-repeat}#cookie-bar-browsers a:hover span{display:block}.clear{clear:both}

View File

@@ -0,0 +1,478 @@
/*
Plugin Name: Cookie Bar
Plugin URL: http://cookie-bar.eu/
@author: Emanuele "ToX" Toscano
@description: Cookie Bar is a free & simple solution to the EU cookie law.
*/
/*
* Available languages array
*/
var CookieLanguages = [
'ca',
'cs',
'da',
'de',
'en',
'es',
'fr',
'hu',
'it',
'nl',
'pt',
'ro',
'sk'
];
var cookieLawStates = [
'AT',
'BE',
'BG',
'CY',
'CZ',
'DE',
'DK',
'EE',
'EL',
'ES',
'FI',
'FR',
'GB',
'HR',
'HU',
'IE',
'IT',
'LT',
'LU',
'LV',
'MT',
'NL',
'PL',
'PT',
'RO',
'SE',
'SI',
'SK'
];
/**
* Main function
*/
function setupCookieBar() {
var scriptPath = getScriptPath();
var cookieBar;
var button;
var buttonNo;
var prompt;
var promptBtn;
var promptClose;
var promptContent;
var promptNoConsent;
var cookiesListDiv;
var detailsLinkText;
var detailsLinkUrl;
var startup = false;
var shutup = false;
/**
* If cookies are disallowed, delete all the cookies at every refresh
* @param null
* @return null
*/
if (getCookie() == 'CookieDisallowed') {
removeCookies();
setCookie('cookiebar', 'CookieDisallowed');
}
/**
* Load plugin only if needed:
* show if the "always" parameter is set
* do nothing if cookiebar cookie is set
* show only for european users
* @param null
* @return null
*/
// If the user is in EU, then STARTUP
/*var checkEurope = new XMLHttpRequest();
checkEurope.open('GET', '//freegeoip.io/json/', true);
checkEurope.onreadystatechange = function() {
if (checkEurope.readyState === 4 && checkEurope.status === 200) {
clearTimeout(xmlHttpTimeout);
var country = JSON.parse(checkEurope.responseText).country_code;
if (cookieLawStates.indexOf(country) > -1) {
startup = true;
} else {
shutup = true;
}
}
};*/
startup = true;
/*
* Using an external service for geoip localization could be a long task
* If it takes more than 1.5 second, start normally
*/
/*var xmlHttpTimeout = setTimeout(ajaxTimeout, 1500);
function ajaxTimeout() {
console.log('cookieBAR - Timeout for ip geolocation');
checkEurope.abort();
startup = true;
}
checkEurope.send();*/
// If at least a cookie or localstorage is set, then STARTUP
if (document.cookie.length > 0 || window.localStorage.length > 0) {
var accepted = getCookie();
if (accepted === undefined) {
startup = true;
} else {
shutup = true;
}
}
// If cookieBAR should always be show, then STARTUP
if (getURLParameter('always')) {
startup = true;
}
if (startup === true && shutup === false) {
startCookieBar();
}
/**
* Load external files (css, language files etc.)
* @return null
*/
function startCookieBar() {
var userLang = detectLang();
// Load CSS file
var theme = '-grey';
if (getURLParameter('theme')) {
theme = '-' + getURLParameter('theme');
}
var path = scriptPath.replace(/[^\/]*$/, '');
var path = '/mysyde/common/cookie-bar';
var minified = (scriptPath.indexOf('.min') > -1) ? '.min' : '';
var stylesheet = document.createElement('link');
stylesheet.setAttribute('rel', 'stylesheet');
stylesheet.setAttribute('href', path + '/cookiebar' + theme + minified + '.css');
//document.head.appendChild(stylesheet);
// Load the correct language messages file and set some variables
var request = new XMLHttpRequest();
request.open('GET', path + '/lang/' + userLang + '.html', true);
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var element = document.createElement('div');
element.innerHTML = request.responseText;
document.getElementsByTagName('body')[0].appendChild(element);
cookieBar = document.getElementById('cookie-bar');
button = document.getElementById('cookie-bar-button');
buttonNo = document.getElementById('cookie-bar-button-no');
prompt = document.getElementById('cookie-bar-prompt');
promptBtn = document.getElementById('cookie-bar-prompt-button');
promptClose = document.getElementById('cookie-bar-prompt-close');
promptContent = document.getElementById('cookie-bar-prompt-content');
promptNoConsent = document.getElementById('cookie-bar-no-consent');
thirdparty = document.getElementById('cookie-bar-thirdparty');
tracking = document.getElementById('cookie-bar-tracking');
scrolling = document.getElementById('cookie-bar-scrolling');
privacyPage = document.getElementById('cookie-bar-privacy-page');
privacyLink = document.getElementById('cookie-bar-privacy-link');
if (!getURLParameter('showNoConsent')) {
promptNoConsent.style.display = 'none';
buttonNo.style.display = 'none';
}
if (getURLParameter('blocking')) {
fadeIn(prompt, 500);
promptClose.style.display = 'none';
}
if (getURLParameter('thirdparty')) {
thirdparty.style.display = 'block';
}
if (getURLParameter('tracking')) {
tracking.style.display = 'block';
}
if (getURLParameter('scrolling')) {
scrolling.style.display = 'inline-block';
}
if (getURLParameter('top')) {
cookieBar.style.top = 0;
setBodyMargin('top');
} else {
cookieBar.style.bottom = 0;
setBodyMargin('bottom');
}
//if (getURLParameter('privacyPage')) {
var url = global_privacy_url;
promptBtn.href = url;
privacyPage.style.display = 'inline-block';
//}
setEventListeners();
fadeIn(cookieBar, 250);
setBodyMargin();
}
};
request.send();
}
/**
* Get this javascript's path
* @return {String} this javascript's path
*/
function getScriptPath() {
var scripts = document.getElementsByTagName('script');
for (i = 0; i < scripts.length; i += 1) {
if (scripts[i].hasAttribute('src')) {
path = scripts[i].src;
if (path.indexOf('script') > -1) {
return path;
}
}
}
}
/**
* Get browser's language or, if available, the specified one
* @return {String} userLang - short language name
*/
function detectLang() {
var userLang = getURLParameter('forceLang');
if (userLang === false) {
userLang = navigator.language || navigator.userLanguage;
}
userLang = userLang.substr(0, 2);
if (CookieLanguages.indexOf(userLang) < 0) {
userLang = 'en';
}
return userLang;
}
/**
* Get a list of all cookies
* @param {HTMLElement} cookiesListDiv
* @return {void}
*/
function listCookies(cookiesListDiv) {
var cookies = [];
var i, x, y, ARRcookies = document.cookie.split(';');
for (i = 0; i < ARRcookies.length; i += 1) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf('='));
y = ARRcookies[i].substr(ARRcookies[i].indexOf('=') + 1);
x = x.replace(/^\s+|\s+$/g, '');
cookies.push(x);
}
cookiesListDiv.innerHTML = cookies.join(', ');
}
/**
* Get Cookie Bar's cookie if available
* @return {string} cookie value
*/
function getCookie() {
var cookieValue = document.cookie.match(/(;)?cookiebar=([^;]*);?/);
if (cookieValue == null) {
return undefined;
} else {
return decodeURI(cookieValue[2]);
}
}
/**
* Write cookieBar's cookie when user accepts cookies :)
* @param {string} name - cookie name
* @param {string} value - cookie value
* @return null
*/
function setCookie(name, value) {
var exdays = 30;
if (getURLParameter('remember')) {
exdays = getURLParameter('remember');
}
var exdate = new Date();
exdate.setDate(exdate.getDate() + parseInt(exdays));
var cValue = encodeURI(value) + ((exdays === null) ? '' : '; expires=' + exdate.toUTCString() + ';path=/');
document.cookie = name + '=' + cValue;
}
/**
* Remove all the cookies and empty localStorage when user refuses cookies
* @return null
*/
function removeCookies() {
// Clear cookies
document.cookie.split(';').forEach(function(c) {
document.cookie = c.replace(/^\ +/, '').replace(/\=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
});
// Clear localStorage
localStorage.clear();
}
/**
* FadeIn effect
* @param {HTMLElement} el - Element
* @param {number} speed - effect duration
* @return null
*/
function fadeIn(el, speed) {
var s = el.style;
s.opacity = 0;
s.display = 'block';
(function fade() {
(s.opacity -= -0.1) > 0.9 ? null : setTimeout(fade, (speed / 10));
})();
}
/**
* FadeOut effect
* @param {HTMLElement} el - Element
* @param {number} speed - effect duration
* @return null
*/
function fadeOut(el, speed) {
var s = el.style;
s.opacity = 1;
(function fade() {
(s.opacity -= 0.1) < 0.1 ? s.display = 'none' : setTimeout(fade, (speed / 10));
})();
}
/**
* Add a body tailored bottom (or top) margin so that CookieBar doesn't hide anything
* @param {String} where
* @return null
*/
function setBodyMargin(where) {
setTimeout(function () {
var height = document.getElementById('cookie-bar').clientHeight;
var bodyEl = document.getElementsByTagName('body')[0];
var bodyStyle = bodyEl.currentStyle || window.getComputedStyle(bodyEl);
switch (where) {
case 'top':
bodyEl.style.marginTop = (parseInt(bodyStyle.marginTop) + height) + 'px';
break;
case 'bottom':
bodyEl.style.marginBottom = (parseInt(bodyStyle.marginBottom) + height) + 'px';
break;
}
}, 300);
}
/**
* Clear the bottom (or top) margin when the user closes the CookieBar
* @return null
*/
function clearBodyMargin() {
var height = document.getElementById('cookie-bar').clientHeight;
if (getURLParameter('top')) {
var currentTop = parseInt(document.getElementsByTagName('body')[0].style.marginTop);
document.getElementsByTagName('body')[0].style.marginTop = currentTop - height + 'px';
} else {
var currentBottom = parseInt(document.getElementsByTagName('body')[0].style.marginBottom);
document.getElementsByTagName('body')[0].style.marginBottom = currentBottom -height + 'px';
}
}
/**
* Get ul parameter to look for
* @param {string} name - param name
* @return {String|Boolean} param value (false if parameter is not found)
*/
function getURLParameter(name) {
var set = scriptPath.split(name + '=');
if (set[1]) {
return set[1].split(/[&?]+/)[0];
} else {
return false;
}
}
/**
* Set button actions (event listeners)
* @return null
*/
function setEventListeners() {
button.addEventListener('click', function() {
setCookie('cookiebar', 'CookieAllowed');
clearBodyMargin();
fadeOut(prompt, 250);
fadeOut(cookieBar, 250);
if (getURLParameter('refreshPage')) {
window.location.reload();
}
});
buttonNo.addEventListener('click', function() {
var txt = promptNoConsent.textContent.trim();
var confirm = window.confirm(txt);
if (confirm === true) {
removeCookies();
setCookie('cookiebar', 'CookieDisallowed');
clearBodyMargin();
fadeOut(prompt, 250);
fadeOut(cookieBar, 250);
}
});
//promptBtn.outerHTML='';
promptContent.outerHTML='';
promptBtn.addEventListener('click', function() {
fadeIn(prompt, 250);
});
promptClose.addEventListener('click', function() {
fadeOut(prompt, 250);
});
if (getURLParameter('scrolling')) {
var scrollPos = document.body.getBoundingClientRect().top;
var scrolled = false;
window.addEventListener('scroll', function() {
if (scrolled === false) {
if (document.body.getBoundingClientRect().top - scrollPos > 250 || document.body.getBoundingClientRect().top - scrollPos < -250) {
setCookie('cookiebar', 'CookieAllowed');
clearBodyMargin();
fadeOut(prompt, 250);
fadeOut(cookieBar, 250);
scrolled = true;
if (getURLParameter('refreshPage')) {
window.location.reload();
}
}
}
});
}
}
}
// Load the script only if there is at least a cookie or a localStorage item
document.addEventListener('DOMContentLoaded', function() {
setupCookieBar();
});

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,226 @@
#cookie-bar {
font-size: 13px;
}
#cookie-bar-prompt-content {
font-size: 13px;
max-height: 85vh;
}
#cookie-bar-browsers a {
width: 60px;
}
@media only screen and (max-device-width: 800px) {
#cookie-bar {
font-size: 12px;
}
#cookie-bar-prompt-content {
font-size: 11px;
max-height: 80vh;
}
#cookie-bar-browsers a {
width: 50px;
}
}
#cookie-bar-prompt-content, #cookie-bar {
color: #000;
font-weight: bold;
font-family: Arial, Helvetica, sans-serif;
}
#cookie-bar {
background: #f5f5f5;
border-top: 4px solid #333;
left: 0;
line-height: 1.5;
margin: 0;
padding: 3px;
position: fixed;
width: 100%;
z-index: 9999;
}
#cookie-bar-prompt {
background: #000;
background: rgba(0,0,0,0.7);
height: 100%;
left: 0;
line-height: 1.5;
position: fixed;
top: 0;
width: 100%;
z-index: 9998;
}
#cookie-bar *,
#cookie-bar-prompt * {
margin: 0;
padding: 0;
line-height: 1.5;
}
#cookie-bar p {
float: left;
margin: 4px 0 0 20px;
padding: 0;
}
#cookie-bar-prompt p {
}
#cookie-bar-button {
background-color: #1FAE16;
color: #FFF !important;
cursor: pointer;
display: inline-block;
float: right;
font-weight: bold;
line-height: 1;
margin-right: 20px;
margin-top: 2px;
padding: 5px 10px 6px;
position: relative;
text-decoration: none;
}
#cookie-bar-button-no {
background-color: #D02828;
color: #FFF!important;
cursor: pointer;
display: inline-block;
float: right;
font-weight: bold;
line-height: 1;
margin-right: 20px;
margin-top: 2px;
padding: 5px 10px 6px;
position: relative;
text-decoration: none;
}
#cookie-bar-prompt a {
cursor: pointer;
}
#cookie-bar-prompt hr {
background: #FFF;
border: none;
height: 1px;
margin: 0.7em 0 1em;
}
#cookie-bar-prompt-content::-webkit-scrollbar-track {
background-color: #45484D;
}
#cookie-bar-prompt-content::-webkit-scrollbar {
width: 15px;
}
#cookie-bar-prompt-content::-webkit-scrollbar-thumb {
box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
background-color: #EEE;
background-color: rgba(255,255,255,0.3);
}
#cookie-bar-prompt-content a, #cookie-bar a, #cookie-bar-prompt-content span {
color: #9B1A1A;
text-decoration: none;
}
#cookie-bar-prompt-content a:hover, #cookie-bar a:hover {
color: #9B1A1A;
text-decoration: underline;
}
#cookie-bar-prompt-close {
background: url(x.png) no-repeat;
display: block;
float: right;
height: 14px;
width: 14px;
}
#cookie-bar-prompt-logo {
background: url(logo.png) no-repeat;
display: block;
float: left;
height: 42px;
width: 190px;
}
#cookie-bar-prompt-close span, #cookie-bar-prompt-logo span {
display: none;
}
#cookie-bar-prompt-button {
cursor: pointer;
}
#cookie-bar-prompt-content {
background: #aaa;
border: 2px solid #333;
margin: 0 auto;
max-width: 98%;
overflow: auto;
padding: 25px;
position: relative;
top: 5%;
width: 600px;
z-index: 9998;
}
#cookie-bar-thirdparty {
display: none;
}
#cookie-bar-tracking {
display: none;
}
#cookie-bar-scrolling {
display: none;
}
#cookie-bar-privacy-page {
display: none;
}
#cookie-bar-browsers a {
display: inline-block;
height: 53px;
margin: 0;
padding: 0;
position: relative;
}
#cookie-bar-browsers a span {
background: #555;
border-radius: 2px;
color: #000 !important;
display: none;
left: -10px;
opacity: 1;
padding: 3px 10px;
position: absolute;
text-align: center;
top: 60px;
width: 150px;
}
#cookie-bar-browsers .chrome {
background: url(browsers/chrome.png) no-repeat;
}
#cookie-bar-browsers .firefox {
background: url(browsers/firefox.png) no-repeat;
}
#cookie-bar-browsers .ie {
background: url(browsers/ie.png) no-repeat;
}
#cookie-bar-browsers .opera {
background: url(browsers/opera.png) no-repeat;
}
#cookie-bar-browsers .safari {
background: url(browsers/safari.png) no-repeat;
}
#cookie-bar-browsers a:hover span {
display: block;
}
.clear {
clear: both;
}

View File

@@ -0,0 +1 @@
#cookie-bar{font-size:13px}#cookie-bar-prompt-content{font-size:13px;max-height:85vh}#cookie-bar-browsers a{width:60px}@media only screen and (max-device-width: 800px){#cookie-bar{font-size:12px}#cookie-bar-prompt-content{font-size:11px;max-height:80vh}#cookie-bar-browsers a{width:50px}}#cookie-bar-prompt-content,#cookie-bar{color:#000;font-weight:bold;font-family:Arial, Helvetica, sans-serif}#cookie-bar{background:#f5f5f5;border-top:4px solid #333;left:0;line-height:1.5;margin:0;padding:3px;position:fixed;width:100%;z-index:9999}#cookie-bar-prompt{background:#000;background:rgba(0,0,0,0.7);height:100%;left:0;line-height:1.5;position:fixed;top:0;width:100%;z-index:9998}#cookie-bar *,#cookie-bar-prompt *{margin:0;padding:0;line-height:1.5}#cookie-bar p{float:left;margin:4px 0 0 20px;padding:0}#cookie-bar-button{background-color:#1FAE16;color:#FFF !important;cursor:pointer;display:inline-block;float:right;font-weight:bold;line-height:1;margin-right:20px;margin-top:2px;padding:5px 10px 6px;position:relative;text-decoration:none}#cookie-bar-button-no{background-color:#D02828;color:#FFF !important;cursor:pointer;display:inline-block;float:right;font-weight:bold;line-height:1;margin-right:20px;margin-top:2px;padding:5px 10px 6px;position:relative;text-decoration:none}#cookie-bar-prompt a{cursor:pointer}#cookie-bar-prompt hr{background:#FFF;border:none;height:1px;margin:0.7em 0 1em}#cookie-bar-prompt-content::-webkit-scrollbar-track{background-color:#45484D}#cookie-bar-prompt-content::-webkit-scrollbar{width:15px}#cookie-bar-prompt-content::-webkit-scrollbar-thumb{box-shadow:inset 0 0 6px rgba(0,0,0,0.5);background-color:#EEE;background-color:rgba(255,255,255,0.3)}#cookie-bar-prompt-content a,#cookie-bar a,#cookie-bar-prompt-content span{color:#9B1A1A;text-decoration:none}#cookie-bar-prompt-content a:hover,#cookie-bar a:hover{color:#9B1A1A;text-decoration:underline}#cookie-bar-prompt-close{background:url(x.png) no-repeat;display:block;float:right;height:14px;width:14px}#cookie-bar-prompt-logo{background:url(logo.png) no-repeat;display:block;float:left;height:42px;width:190px}#cookie-bar-prompt-close span,#cookie-bar-prompt-logo span{display:none}#cookie-bar-prompt-button{cursor:pointer}#cookie-bar-prompt-content{background:#aaa;border:2px solid #333;margin:0 auto;max-width:98%;overflow:auto;padding:25px;position:relative;top:5%;width:600px;z-index:9998}#cookie-bar-thirdparty{display:none}#cookie-bar-tracking{display:none}#cookie-bar-scrolling{display:none}#cookie-bar-privacy-page{display:none}#cookie-bar-browsers a{display:inline-block;height:53px;margin:0;padding:0;position:relative}#cookie-bar-browsers a span{background:#555;border-radius:2px;color:#000 !important;display:none;left:-10px;opacity:1;padding:3px 10px;position:absolute;text-align:center;top:60px;width:150px}#cookie-bar-browsers .chrome{background:url(browsers/chrome.png) no-repeat}#cookie-bar-browsers .firefox{background:url(browsers/firefox.png) no-repeat}#cookie-bar-browsers .ie{background:url(browsers/ie.png) no-repeat}#cookie-bar-browsers .opera{background:url(browsers/opera.png) no-repeat}#cookie-bar-browsers .safari{background:url(browsers/safari.png) no-repeat}#cookie-bar-browsers a:hover span{display:block}.clear{clear:both}

View File

@@ -0,0 +1,251 @@
#cookie-bar {
font-size: 13px;
}
#cookie-bar-prompt-content {
font-size: 13px;
max-height: 85vh;
}
#cookie-bar-browsers a {
width: 60px;
}
@media only screen and (max-device-width: 800px) {
#cookie-bar {
font-size: 12px;
}
#cookie-bar-prompt-content {
font-size: 11px;
max-height: 80vh;
}
#cookie-bar-browsers a {
width: 50px;
}
}
#cookie-bar {
background: #45484D;
background: -moz-linear-gradient(top, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(30,30,30,0.95)), color-stop(100%,rgba(0,0,0,0.95)));
background: -webkit-linear-gradient(top, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);
background: -o-linear-gradient(top, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);
background: -ms-linear-gradient(top, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);
background: linear-gradient(to bottom, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);
font-family: Arial, Helvetica, sans-serif;
font-size: 10pt !important;
left: 0;
line-height: 1.5;
margin: 0;
padding: 3px;
position: fixed;
width: 100%;
z-index: 9999;
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#cc45484d', endColorstr='#cc000000',GradientType=0 );
}
#cookie-bar-prompt {
background: #000;
background: rgba(0,0,0,0.4);
font-family: Arial, Helvetica, sans-serif;
font-size: 10pt !important;
height: 100%;
left: 0;
line-height: 1.5;
position: fixed;
top: 0;
width: 100%;
z-index: 9998;
}
#cookie-bar *,
#cookie-bar-prompt * {
line-height: 1.5;
}
#cookie-bar p {
font-size: 10pt !important;
float: left;
margin: 4px 0 0 20px;
padding: 0;
color: #FFF;
font-family: sans-serif;
}
#cookie-bar-prompt p {
font-family: Arial, Helvetica, sans-serif;
color: #FFF;
}
#cookie-bar-button {
background-color: #36BF2D;
border-bottom: 1px solid #222;
border-radius: 5px;
color: #FFF !important;
cursor: pointer;
display: inline-block;
float: right;
font-weight: bold;
line-height: 1;
margin-right: 20px;
margin-top: 2px;
padding: 5px 10px 6px;
position: relative;
text-decoration: none;
text-shadow: 0 -1px 1px #222;
}
#cookie-bar-button-no {
background-color: #D02828;
border-bottom: 1px solid #222;
border-radius: 5px;
color: #FFF!important;
cursor: pointer;
display: inline-block;
float: right;
font-weight: bold;
line-height: 1;
margin-right: 20px;
margin-top: 2px;
padding: 5px 10px 6px;
position: relative;
text-decoration: none;
text-shadow: 0 -1px 1px #222;
}
#cookie-bar-prompt a {
cursor: pointer;
}
#cookie-bar-prompt hr {
background: #FFF;
border: none;
height: 1px;
margin: 0.7em 0 1em;
opacity: 0.2;
}
#cookie-bar-prompt-content, #cookie-bar {
color: #FFF;
font-weight: 300;
}
#cookie-bar-prompt-content::-webkit-scrollbar-track {
border-radius: 10px;
background-color: #222;
background-color: rgba(255,255,255,0.05);
}
#cookie-bar-prompt-content::-webkit-scrollbar {
width: 15px;
}
#cookie-bar-prompt-content::-webkit-scrollbar-thumb {
box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
background-color: #EEE;
background-color: rgba(255,255,255,0.3);
border-radius: 10px;
}
#cookie-bar-prompt-content a, #cookie-bar a, #cookie-bar-prompt-content span {
color: #31A8F0;
text-decoration: none;
}
#cookie-bar-prompt-content a:hover, #cookie-bar a:hover {
color: #31A8F0;
text-decoration: underline;
}
#cookie-bar-prompt-close {
background: url(x.png) no-repeat;
display: block;
float: right;
height: 14px;
width: 14px;
}
#cookie-bar-prompt-logo {
background: url(logo.png) no-repeat;
display: block;
float: left;
height: 42px;
width: 190px;
}
#cookie-bar-prompt-close span, #cookie-bar-prompt-logo span {
display: none;
}
#cookie-bar-prompt-button {
cursor: pointer;
}
#cookie-bar-prompt-content {
background: #111;
border-radius: 7px;
box-shadow: 1px 2px 8px rgba(0,0,0,0.5);
color: #FFF;
margin: 0 auto;
max-width: 98%;
opacity: 0.97;
overflow: auto;
padding: 25px;
position: relative;
top: 5%;
width: 600px;
z-index: 9998;
}
#cookie-bar-thirdparty {
display: none;
}
#cookie-bar-tracking {
display: none;
}
#cookie-bar-scrolling {
display: none;
}
#cookie-bar-privacy-page {
display: none;
}
#cookie-bar-browsers a {
display: inline-block;
height: 53px;
margin: 0;
padding: 0;
position: relative;
}
#cookie-bar-browsers a span {
background: #FFF;
border-radius: 2px;
color: #000 !important;
display: none;
left: -10px;
opacity: 0.8;
padding: 3px 10px;
position: absolute;
text-align: center;
top: 60px;
width: 150px;
}
#cookie-bar-browsers .chrome {
background: url(browsers/chrome.png) no-repeat;
}
#cookie-bar-browsers .firefox {
background: url(browsers/firefox.png) no-repeat;
}
#cookie-bar-browsers .ie {
background: url(browsers/ie.png) no-repeat;
}
#cookie-bar-browsers .opera {
background: url(browsers/opera.png) no-repeat;
}
#cookie-bar-browsers .safari {
background: url(browsers/safari.png) no-repeat;
}
#cookie-bar-browsers a:hover span {
display: block;
}
.clear {
clear: both;
}

View File

@@ -0,0 +1 @@
#cookie-bar{font-size:13px}#cookie-bar-prompt-content{font-size:13px;max-height:85vh}#cookie-bar-browsers a{width:60px}@media only screen and (max-device-width: 800px){#cookie-bar{font-size:12px}#cookie-bar-prompt-content{font-size:11px;max-height:80vh}#cookie-bar-browsers a{width:50px}}#cookie-bar{background:#45484D;background:-moz-linear-gradient(top, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);background:-webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(30,30,30,0.95)), color-stop(100%,rgba(0,0,0,0.95)));background:-webkit-linear-gradient(top, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);background:-o-linear-gradient(top, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);background:-ms-linear-gradient(top, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);background:linear-gradient(to bottom, rgba(30,30,30,0.95) 0, rgba(0,0,0,0.95) 100%);font-family:Arial, Helvetica, sans-serif;font-size:10pt;left:0;line-height:1.5;margin:0;padding:3px;position:fixed;width:100%;z-index:9999;filter:progid:DXImageTransform.Microsoft.gradient( startColorstr='#cc45484d', endColorstr='#cc000000',GradientType=0 )}#cookie-bar-prompt{background:#000;background:rgba(0,0,0,0.4);font-family:Arial, Helvetica, sans-serif;font-size:10pt;height:100%;left:0;line-height:1.5;position:fixed;top:0;width:100%;z-index:9998}#cookie-bar *,#cookie-bar-prompt *{line-height:1.5}#cookie-bar p{float:left;margin:4px 0 0 20px;padding:0;color:#FFF;font-family:sans-serif}#cookie-bar-prompt p{font-family:Arial, Helvetica, sans-serif;color:#FFF}#cookie-bar-button{background-color:#36BF2D;border-bottom:1px solid #222;border-radius:5px;color:#FFF !important;cursor:pointer;display:inline-block;float:right;font-weight:bold;line-height:1;margin-right:20px;margin-top:2px;padding:5px 10px 6px;position:relative;text-decoration:none;text-shadow:0 -1px 1px #222}#cookie-bar-button-no{background-color:#D02828;border-bottom:1px solid #222;border-radius:5px;color:#FFF !important;cursor:pointer;display:inline-block;float:right;font-weight:bold;line-height:1;margin-right:20px;margin-top:2px;padding:5px 10px 6px;position:relative;text-decoration:none;text-shadow:0 -1px 1px #222}#cookie-bar-prompt a{cursor:pointer}#cookie-bar-prompt hr{background:#FFF;border:none;height:1px;margin:0.7em 0 1em;opacity:0.2}#cookie-bar-prompt-content,#cookie-bar{color:#FFF;font-weight:300}#cookie-bar-prompt-content::-webkit-scrollbar-track{border-radius:10px;background-color:#222;background-color:rgba(255,255,255,0.05)}#cookie-bar-prompt-content::-webkit-scrollbar{width:15px}#cookie-bar-prompt-content::-webkit-scrollbar-thumb{box-shadow:inset 0 0 6px rgba(0,0,0,0.5);background-color:#EEE;background-color:rgba(255,255,255,0.3);border-radius:10px}#cookie-bar-prompt-content a,#cookie-bar a,#cookie-bar-prompt-content span{color:#31A8F0;text-decoration:none}#cookie-bar-prompt-content a:hover,#cookie-bar a:hover{color:#31A8F0;text-decoration:underline}#cookie-bar-prompt-close{background:url(x.png) no-repeat;display:block;float:right;height:14px;width:14px}#cookie-bar-prompt-logo{background:url(logo.png) no-repeat;display:block;float:left;height:42px;width:190px}#cookie-bar-prompt-close span,#cookie-bar-prompt-logo span{display:none}#cookie-bar-prompt-button{cursor:pointer}#cookie-bar-prompt-content{background:#111;border-radius:7px;box-shadow:1px 2px 8px rgba(0,0,0,0.5);color:#FFF;margin:0 auto;max-width:98%;opacity:0.97;overflow:auto;padding:25px;position:relative;top:5%;width:600px;z-index:9998}#cookie-bar-thirdparty{display:none}#cookie-bar-tracking{display:none}#cookie-bar-scrolling{display:none}#cookie-bar-privacy-page{display:none}#cookie-bar-browsers a{display:inline-block;height:53px;margin:0;padding:0;position:relative}#cookie-bar-browsers a span{background:#FFF;border-radius:2px;color:#000 !important;display:none;left:-10px;opacity:0.8;padding:3px 10px;position:absolute;text-align:center;top:60px;width:150px}#cookie-bar-browsers .chrome{background:url(browsers/chrome.png) no-repeat}#cookie-bar-browsers .firefox{background:url(browsers/firefox.png) no-repeat}#cookie-bar-browsers .ie{background:url(browsers/ie.png) no-repeat}#cookie-bar-browsers .opera{background:url(browsers/opera.png) no-repeat}#cookie-bar-browsers .safari{background:url(browsers/safari.png) no-repeat}#cookie-bar-browsers a:hover span{display:block}.clear{clear:both}

View File

@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>cookieBAR</title>
<script type="text/javascript">
var expirationDate = new Date();
expirationDate.setDate(128);
document.cookie = "dummy=1; expires="+expirationDate.toUTCString()+"; path=/";
</script>
</head>
<body>
<h1>Demo</h1>
<script src="../cookiebar-latest.js?"></script>
</body>
</html>

View File

@@ -0,0 +1,48 @@
<div id="cookie-bar-prompt" style="display:none">
<div id="cookie-bar-prompt-content">
<a rel='nofollow' id="cookie-bar-prompt-logo" href="#"><span>Galetes</span></a>
<a rel='nofollow' id="cookie-bar-prompt-close"><span>tancar</span></a>
<div class="clear"></div>
<p>Aquest lloc web fa servir galetes per millorar la experiència i proporcionar funcionalitats adicionals. Cap d'aquesta informació pot ser utilitzada per identificar-lo o contactar-lo de cap manera.<br>
<i id='cookie-bar-thirdparty'>
<br>Aquest lloc web fa servir galetes de tercers, consulta els detalls a la política de privacitat.<br>
</i>
<i id='cookie-bar-tracking'>
<br>Aquest lloc web fa servir galetes de seguiment, consulta els detalls a la política de privacitat.<br>
</i>
<i id='cookie-bar-privacy-page'>
<br>Per saber més sobre còm aquest lloc fa servir les galetes, si us plau llegiu la nostra <a rel='nofollow' id='cookie-bar-privacy-link' href=''>POLÍTICA DE PRIVACITAT</a>.<br><br></i>
<br>Si premeu <span>Permetre les galetes</span>, <span id='cookie-bar-scrolling'>o desplaçant-se a través de la pàgina</span> esteu donant el vostre consentiment a emmagatzemar petites quantitats d'informació en el vostre navegador.
<i id='cookie-bar-no-consent'>
<br>
<br>Si premeu <span>No permetre les galetes</span> esteu rebutjant que s'emmagatzemi informació d'aquest lloc i posiblement eliminant aquelles galetes ja existents (alguns apartats del lloc podrien deixar de funcionar correctament).</i><br>
<br>Per saber-ne més sobre les galetes, visiteu la <a rel='nofollow' target='_blank' href='https://ca.wikipedia.org/wiki/Galeta_(inform%C3%A0tica)'>Vikipèdia</a>.
<hr>
Per desactivar completament les galetes per qualsevol lloc que visiteu, premeu la icona corresponent al vostre navegador i seguiu les instruccions:
<br>
<br>
<div id='cookie-bar-browsers'>
<!-- Thanks Peequi for the icons http://ampeross.deviantart.com/art/Peequi-part-1-290622606 -->
<a rel='nofollow' class='chrome' target='_blank' href='https://support.google.com/accounts/answer/61416?hl=ca'><span>Chrome</span></a>
<a rel='nofollow' class='firefox' target='_blank' href='https://support.mozilla.org/ca-ES/kb/enable-and-disable-cookies-website-preferences'><span>Firefox</span></a>
<a rel='nofollow' class='ie' target='_blank' href='http://windows.microsoft.com/ca-es/internet-explorer/delete-manage-cookies#ie=ie-11'><span>Internet Explorer</span></a>
<a rel='nofollow' class='opera' target='_blank' href='http://help.opera.com/Windows/10.00/es/cookies.html'><span>Opera</span></a>
<a rel='nofollow' class='safari' target='_blank' href='https://support.apple.com/kb/PH17191?viewlocale=es_ES'><span>Safari</span></a>
</div>
<br>
</div>
</div>
<div id="cookie-bar" style="display:none">
<p>Aquest lloc web fa servir galetes per millorar la experiència i proporcionar funcionalitats adicionals.
<a rel='nofollow' id="cookie-bar-prompt-button" data-alt="Privacy policy">Detalls</a>
</p>
<a rel='nofollow' id="cookie-bar-button-no">No permetre les galetes</a>
<a rel='nofollow' id="cookie-bar-button">Permetre les galetes</a>
</div>

View File

@@ -0,0 +1,48 @@
<div id="cookie-bar-prompt" style="display:none">
<div id="cookie-bar-prompt-content">
<a rel='nofollow' id="cookie-bar-prompt-logo" href="http://cookie-bar.eu"><span>cookie bar</span></a>
<a rel='nofollow' id="cookie-bar-prompt-close"><span>zavřít</span></a>
<div class="clear"></div>
<p>Tato webová stránka používá cookies ke zlepšení prohlížení webu a poskytování dalších funkcí. Tyto údaje nebudou použity k identifikaci nebo kontaktování.<br>
<i id='cookie-bar-thirdparty'>
<br>Tato webová stránka používá cookies třetích stran, viz podrobnosti v politice ochrany osobních údajů.<br>
</i>
<i id='cookie-bar-tracking'>
<br>Tato webová stránka používá sledovací cookies, viz podrobnosti v politice ochrany osobních údajů.<br>
</i>
<i id='cookie-bar-privacy-page'>
<br>Pokud se chcete dozvědět více o tom, jak tento web používá cookies a localStorage, přečtěte si naše <a rel='nofollow' id='cookie-bar-privacy-link' href=''>ZÁSADY OCHRANY OSOBNÍCH ÚDAJŮ</a>.<br><br></i>
<br>Kliknutím na tlačítko <span>Povolit cookies</span> dáváte souhlas této webové stránce uložit malé kousky dat na vašem zařízení.
<i id='cookie-bar-no-consent'>
<br>
<br>Kliknutím na tlačítko <span>Zakázat cookies</span> <span id="cookie-bar-scrolling"> nebo prohlížením stránky, </span> popřete svůj souhlas s ukládáním cookies a dat localStorage pro tuto webovou stránku, případně smažete již uložené soubory cookie (některé části webu mohou přestat fungovat správně).</i><br>
<br>Pokud se chcete dozvědět více o cookies navštivte <a rel='nofollow' target='_blank' href='http://ec.europa.eu/ipg/basics/legal/cookies/index_en.htm'>http://ec.europa.eu/ipg/basics/legal/cookies/index_en.htm</a>.
<hr>
Chcete-li zakázat všechny soubory cookie prostřednictvím prohlížeče, klikněte na příslušnou ikonu a postupujte podle pokynů:
<br>
<br>
<div id='cookie-bar-browsers'>
<!-- Thanks Peequi for the icons http://ampeross.deviantart.com/art/Peequi-part-1-290622606 -->
<a rel='nofollow' class='chrome' target='_blank' href='https://support.google.com/accounts/answer/61416?hl=en'><span>Chrome</span></a>
<a rel='nofollow' class='firefox' target='_blank' href='https://support.mozilla.org/en-GB/kb/enable-and-disable-cookies-website-preferences'><span>Firefox</span></a>
<a rel='nofollow' class='ie' target='_blank' href='http://windows.microsoft.com/en-gb/internet-explorer/delete-manage-cookies#ie=ie-11'><span>Internet Explorer</span></a>
<a rel='nofollow' class='opera' target='_blank' href='http://help.opera.com/Windows/10.00/en/cookies.html'><span>Opera</span></a>
<a rel='nofollow' class='safari' target='_blank' href='https://support.apple.com/kb/PH17191?viewlocale=en_GB'><span>Safari</span></a>
</div>
<br>
</div>
</div>
<div id="cookie-bar" style="display:none">
<p>Tato webová stránka používá cookies ke zlepšení prohlížení webu a poskytování dalších funkcí.
<a rel='nofollow' id="cookie-bar-prompt-button" data-alt="Zásady ochrany osobných údajov">Detaily</a>
</p>
<a rel='nofollow' id="cookie-bar-button-no">Zakázat cookies</a>
<a rel='nofollow' id="cookie-bar-button">Povolit cookies</a>
</div>

View File

@@ -0,0 +1,48 @@
<div id="cookie-bar-prompt" style="display:none">
<div id="cookie-bar-prompt-content">
<a rel='nofollow' id="cookie-bar-prompt-logo" href="http://cookie-bar.eu"><span>cookie bar</span></a>
<a rel='nofollow' id="cookie-bar-prompt-close"><span>luk</span></a>
<div class="clear"></div>
<p>Dette website bruger cookies til at forbedre brugeroplevelse og funktionalitet. Data vil ikke blive brugt til at identificere eller kontakte dig.<br>
<i id='cookie-bar-thirdparty'>
<br>Dette website bruger 3. parts cookies, se detaljer i privatlivspolitikken.<br>
</i>
<i id='cookie-bar-tracking'>
<br>Dette website bruger tracking cookies, se detaljer i privatlivspolitikken<br>
</i>
<i id='cookie-bar-privacy-page'>
<br>For at læse mere om dette websites brug af cookies og localStorage, læs venligst vores <a rel='nofollow' id='cookie-bar-privacy-link' href=''>Privatlivspolitik</a>.<br><br></i>
<br>Ved at klikke <span>Tillad cookies</span> giver du tilladelse til at dette website må gemme små stykke data på din enhed.
<i id='cookie-bar-no-consent'>
<br>
<br>Ved at klikke <span>Tillad ikke cookies</span>, <span id='cookie-bar-scrolling'>eller ved at scrolle på denne side,</span> nægter du tilladelse til at der må gemmes data på din enhed, eventuelt slette allerede gemte cookies. (dele af websitet kan stoppe med at fungere efter hensigten.)</i><br>
<br>For at læse mere om cookies og localStorage, besøg <a rel='nofollow' target='_blank' href='http://ico.org.uk/for_organisations/privacy_and_electronic_communications/the_guide/cookies'>Informationskommisærens Konto</a>.
<hr>
For at deaktivere alle cookies i browseren, klik på det tilhørende ikon og fælg instruktionerne
<br>
<br>
<div id='cookie-bar-browsers'>
<!-- Thanks Peequi for the icons http://ampeross.deviantart.com/art/Peequi-part-1-290622606 -->
<a rel='nofollow' class='chrome' target='_blank' href='https://support.google.com/accounts/answer/61416?hl=en'><span>Chrome</span></a>
<a rel='nofollow' class='firefox' target='_blank' href='https://support.mozilla.org/en-GB/kb/enable-and-disable-cookies-website-preferences'><span>Firefox</span></a>
<a rel='nofollow' class='ie' target='_blank' href='http://windows.microsoft.com/en-gb/internet-explorer/delete-manage-cookies#ie=ie-11'><span>Internet Explorer</span></a>
<a rel='nofollow' class='opera' target='_blank' href='http://help.opera.com/Windows/10.00/en/cookies.html'><span>Opera</span></a>
<a rel='nofollow' class='safari' target='_blank' href='https://support.apple.com/kb/PH17191?viewlocale=en_GB'><span>Safari</span></a>
</div>
<br>
</div>
</div>
<div id="cookie-bar" style="display:none">
<p>Dette website bruger cookies til at forbedre brugeroplevelsen og til at tilføre ekstra funktionalitet.
<a rel='nofollow' id="cookie-bar-prompt-button" data-alt="Privacy policy">Detaljer</a>
</p>
<a rel='nofollow' id="cookie-bar-button-no">Tillad ikke cookies</a>
<a rel='nofollow' id="cookie-bar-button">Tillad cookies</a>
</div>

View File

@@ -0,0 +1,49 @@
<div id="cookie-bar-prompt" style="display:none">
<div id="cookie-bar-prompt-content">
<a rel='nofollow' id="cookie-bar-prompt-logo" href="http://cookie-bar.eu"><span>cookie bar</span></a>
<a rel='nofollow' id="cookie-bar-prompt-close"><span>close</span></a>
<div class="clear"></div>
<p>Diese Internetseite verwendet Cookies, um die Nutzererfahrung zu verbessern und den Benutzern bestimmte Dienste und Funktionen bereitzustellen.
Es werden keine der so gesammelten Daten genutzt, um Sie zu identifizieren oder zu kontaktieren.<br>
<i id='cookie-bar-thirdparty'>
<br>Diese Internetseite macht Gebrauch von Cookies von Dritten, siehe dazu weitere Details in der Datenschutzrichtlinie.<br>
</i>
<i id='cookie-bar-tracking'>
<br>Diese Internetseite macht Gebrauch von Tracking Cookies, siehe dazu weitere Details in der Datenschutzrichtlinie.<br>
</i>
<i id='cookie-bar-privacy-page'>
<br>Lesen Sie bitte unsere <a rel='nofollow' id='cookie-bar-privacy-link' href=''>Datenschutzrichtlinie</a>, um mehr darüber zu erfahren, wie diese Internetseite Cookies und lokalen Speicher nutzt.<br><br></i>
<br>Durch das Klicken von <span>Cookies erlauben</span>, <span id='cookie-bar-scrolling'>oder indem Sie durch die Seite scrollen,</span> geben Sie dieser Internetseite die Erlaubnis, Informationen in Form von Cookies auf Ihrem Gerät zu speichern.
<i id='cookie-bar-no-consent'>
<br>
<br>Durch das Klicken von <span>Cookies verbieten</span> verweigern Sie Ihre Zustimmung, Cookies oder lokalen Speicher zu nutzen. Weiterhin werden alle Cookies und lokal gespeicherte Daten gelöscht und Teile der Internetseite könnten aufhören, ordnungsgemäß zu funktionieren.</i><br>
<br>Besuchen Sie die Internetseite des <a rel='nofollow' target='_blank' href='http://www.bfdi.bund.de/DE/Home/home_node.html'>Bundesbeauftragten für den Datenschutz und die Informationsfreiheit</a>, um mehr über Cookies und lokalen Speicher zu erfahren.
<hr>
Klicken Sie auf das Icon Ihres Browsers und folgen Sie den Anleitungen, um Cookies im gesamten Browser zu deaktivieren oder zu verwalten:
<br>
<br>
<div id='cookie-bar-browsers'>
<!-- Thanks Peequi for the icons http://ampeross.deviantart.com/art/Peequi-part-1-290622606 -->
<a rel='nofollow' class='chrome' target='_blank' href='https://support.google.com/accounts/answer/61416?hl=en'><span>Chrome</span></a>
<a rel='nofollow' class='firefox' target='_blank' href='https://support.mozilla.org/en-GB/kb/enable-and-disable-cookies-website-preferences'><span>Firefox</span></a>
<a rel='nofollow' class='ie' target='_blank' href='http://windows.microsoft.com/en-gb/internet-explorer/delete-manage-cookies#ie=ie-11'><span>Internet Explorer</span></a>
<a rel='nofollow' class='opera' target='_blank' href='http://help.opera.com/Windows/10.00/en/cookies.html'><span>Opera</span></a>
<a rel='nofollow' class='safari' target='_blank' href='https://support.apple.com/kb/PH17191?viewlocale=en_GB'><span>Safari</span></a>
</div>
<br>
</div>
</div>
<div id="cookie-bar" style="display:none">
<p>Diese Webseite verwendet Cookies, um bestimmte Funktionen zu ermöglichen und das Angebot zu verbessern. Indem Sie hier fortfahren, stimmen Sie der Nutzung von Cookies zu.
<a rel='nofollow' id="cookie-bar-prompt-button" data-alt="Privacy policy">Mehr Informationen</a>
</p>
<a rel='nofollow' id="cookie-bar-button-no">Cookies verbieten</a>
<a rel='nofollow' id="cookie-bar-button">Cookies erlauben</a>
</div>

View File

@@ -0,0 +1,48 @@
<div id="cookie-bar-prompt" style="display:none">
<div id="cookie-bar-prompt-content">
<a rel='nofollow' id="cookie-bar-prompt-logo" href="http://cookie-bar.eu"><span>cookie bar</span></a>
<a rel='nofollow' id="cookie-bar-prompt-close"><span>close</span></a>
<div class="clear"></div>
<p>This website makes use of cookies to enhance browsing experience and provide additional functionality. None of this data can or will be used to identify or contact you.<br>
<i id='cookie-bar-thirdparty'>
<br>This website makes use of third party cookies, see the details in the privacy policy.<br>
</i>
<i id='cookie-bar-tracking'>
<br>This website makes use of tracking cookies, see the details in the privacy policy.<br>
</i>
<i id='cookie-bar-privacy-page'>
<br>To learn more about how this website uses cookies or localStorage, please read our <a rel='nofollow' id='cookie-bar-privacy-link' href=''>PRIVACY POLICY</a>.<br><br></i>
<br>By clicking <span>Allow cookies</span> you give your permission to this website to store small bits of data on your device.
<i id='cookie-bar-no-consent'>
<br>
<br>By clicking <span>Disallow cookies</span>, <span id='cookie-bar-scrolling'>or by scrolling the page,</span> you deny your consent to store any cookies and localStorage data for this website, eventually deleting already stored cookies (some parts of the site may stop working properly).</i><br>
<br>To learn more about cookies and localStorage, visit <a rel='nofollow' target='_blank' href='http://ico.org.uk/for_organisations/privacy_and_electronic_communications/the_guide/cookies'>Information Commissioner's Office</a>.
<hr>
To disable all cookies through the browser, click on the corresponding icon and follow the instructions:
<br>
<br>
<div id='cookie-bar-browsers'>
<!-- Thanks Peequi for the icons http://ampeross.deviantart.com/art/Peequi-part-1-290622606 -->
<a rel='nofollow' class='chrome' target='_blank' href='https://support.google.com/accounts/answer/61416?hl=en'><span>Chrome</span></a>
<a rel='nofollow' class='firefox' target='_blank' href='https://support.mozilla.org/en-GB/kb/enable-and-disable-cookies-website-preferences'><span>Firefox</span></a>
<a rel='nofollow' class='ie' target='_blank' href='http://windows.microsoft.com/en-gb/internet-explorer/delete-manage-cookies#ie=ie-11'><span>Internet Explorer</span></a>
<a rel='nofollow' class='opera' target='_blank' href='http://help.opera.com/Windows/10.00/en/cookies.html'><span>Opera</span></a>
<a rel='nofollow' class='safari' target='_blank' href='https://support.apple.com/kb/PH17191?viewlocale=en_GB'><span>Safari</span></a>
</div>
<br>
</div>
</div>
<div id="cookie-bar" style="display:none">
<p>This website makes use of cookies to enhance browsing experience and provide additional functionality.
<a rel='nofollow' id="cookie-bar-prompt-button" data-alt="Privacy policy">Details</a>
</p>
<a rel='nofollow' id="cookie-bar-button-no">Disallow cookies</a>
<a rel='nofollow' id="cookie-bar-button">Allow cookies</a>
</div>

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