Engadidos novos modulos

This commit is contained in:
Laegnur 2024-04-04 15:12:59 +02:00
parent 02db83f5ba
commit b25e0b12c6
47 changed files with 10957 additions and 7 deletions

View file

@ -93,8 +93,7 @@ ErrorDocument 404 /index.php
<IfModule mod_headers.c>
# prevent site from being loaded in an iframe on another site
# you will need to remove this one if you want to allow external iframes
# Header always append X-Frame-Options SAMEORIGIN
Header always set X-Frame-Options SAMEORIGIN
Header always append X-Frame-Options SAMEORIGIN
# To prevent cross site scripting (IE8+ proprietary)
Header set X-XSS-Protection "1; mode=block"
@ -391,7 +390,7 @@ DirectoryIndex index.php index.html index.htm
RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/modules/.*\.(php|inc|tpl|module|info\.json)$ [NC,OR]
# Block access to any software identifying txt, markdown or textile files
RewriteCond %{REQUEST_URI} (^|/)(COPYRIGHT|INSTALL|README|LICENSE|htaccess)\.(txt|md|textile)$ [NC,OR]
RewriteCond %{REQUEST_URI} (^|/)(COPYRIGHT|INSTALL|README|htaccess)\.(txt|md|textile)$ [NC,OR]
# Block potential arbitrary backup files within site directories for things like config
RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/(config[^/]*/?|[^/]+\.php.*)$ [NC,OR]
@ -449,7 +448,7 @@ DirectoryIndex index.php index.html index.htm
RewriteCond %{REQUEST_FILENAME} !(favicon\.ico|robots\.txt)
# -----------------------------------------------------------------------------------------------
# 18. Optionally (O) prevent PW from attempting to serve images or anything in /site/assets/.
# 18. Optionally (O) prevent PW from serving some file types, or anything in /site/assets/.
# Both of these lines are optional, but can help to reduce server load. However, they
# are not compatible with the $config->pagefileSecure option (if enabled) and they
# may produce an Apache 404 rather than your regular 404. You may uncomment the two lines
@ -459,7 +458,7 @@ DirectoryIndex index.php index.html index.htm
# section #2 above that makes ProcessWire the 404 handler.
# -----------------------------------------------------------------------------------------------
# RewriteCond %{REQUEST_URI} !\.(jpg|jpeg|gif|png|ico|webp|svg)$ [NC]
# RewriteCond %{REQUEST_URI} !\.(jpg|jpeg|gif|png|ico|webp|svg|js|css)$ [NC]
# RewriteCond %{REQUEST_FILENAME} !(^|/)site/assets/
# -----------------------------------------------------------------------------------------------
@ -480,4 +479,3 @@ DirectoryIndex index.php index.html index.htm
#################################################################################################
# END PROCESSWIRE HTACCESS DIRECTIVES
#################################################################################################

View file

@ -0,0 +1,298 @@
<?php
/**
* ProcessWire Video Fieldtype
* by Adrian Jones
*
* Fieldtype for uploading video files and creating poster images.
*
* Copyright (C) 2020 by Adrian Jones
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
*/
class FieldtypeVideo extends FieldtypeFile implements Module, ConfigurableModule {
public static function getModuleInfo() {
return array(
'title' => __('Video', __FILE__),
'summary' => __('Fieldtype for uploading video files and creating poster images.', __FILE__),
'version' => '0.2.1',
'author' => 'Adrian Jones',
'href' => 'https://processwire.com/talk/topic/4580-video-fieldtype/',
'installs' => 'InputfieldVideo',
'icon' => 'file-video-o'
);
}
protected static $configDefaults = array(
'player_code' => '
<video width="{width}" height="{height}" poster="{poster}" controls="controls" preload="none">
<source type="video/mp4" src="{url}" />
<track kind="subtitles" src="{subtitles}" srclang="en" />
</video>
'
);
protected $data = array();
/**
* Given a raw value (value as stored in DB), return the value as it would appear in a Page object
*
* @param Page $page
* @param Field $field
* @param string|int|array $value
* @return string|int|array|object $value
*
*/
public function ___wakeupValue(Page $page, Field $field, $value) {
if($value instanceof Pagefiles) return $value;
$pagefiles = $this->getBlankValue($page, $field);
if(empty($value)) return $pagefiles;
if(!is_array($value) || array_key_exists('data', $value)) $value = array($value);
foreach($value as $v) {
if(empty($v['data'])) continue;
$pagefile = $this->getBlankPagefile($pagefiles, $v['data']);
$pagefile->description = $v['description'];
if(isset($v['modified'])) $pagefile->modified = $v['modified'];
// $v['created'] was blank, so setting to modified to ensure video is "published"
// this might be a bit of a hack so should revisit later
if(isset($v['created'])) $pagefile->created = $v['modified'];
if(isset($v['tags'])) $pagefile->tags = $v['tags'];
if(isset($v['poster'])) $pagefile->poster = $v['poster'];
if(isset($v['subtitles'])) $pagefile->subtitles = $v['subtitles'];
$pagefile->setTrackChanges(true);
$pagefiles->add($pagefile);
}
$pagefiles->resetTrackChanges(true);
return $pagefiles;
}
/**
* Given an 'awake' value, as set by wakeupValue, convert the value back to a basic type for storage in DB.
*
* @param Page $page
* @param Field $field
* @param string|int|array|object $value
* @return string|int
*
*/
public function ___sleepValue(Page $page, Field $field, $value) {
$sleepValue = array();
if(!$value instanceof Pagefiles) return $sleepValue;
foreach($value as $pagefile) {
$item = array(
'data' => $pagefile->basename,
'description' => $pagefile->description,
'poster' => $pagefile->poster,
'subtitles' => $pagefile->subtitles,
);
if($field->fileSchema & self::fileSchemaDate) {
$item['modified'] = date('Y-m-d H:i:s', $pagefile->modified);
$item['created'] = date('Y-m-d H:i:s', $pagefile->created);
}
if($field->fileSchema & self::fileSchemaTags) {
$item['tags'] = $pagefile->tags;
}
$sleepValue[] = $item;
}
return $sleepValue;
}
public function getBlankValue(Page $page, Field $field) {
$pageimages = new Pageimages($page);
$pageimages->setTrackChanges(true);
return $pageimages;
}
protected function getBlankPagefile(Pagefiles $pagefiles, $filename) {
return new Pageimage($pagefiles, $filename);
}
/**
* Perform output formatting on the value delivered to the API
*
* Entity encode the file's description field.
*
* If the maxFiles setting is 1, then we format the value to dereference as single Pagefile rather than a PagefilesArray
*
* This method is only used when $page->outputFormatting is true.
*
*/
public function ___formatValue(Page $page, Field $field, $value) {
if(!$value instanceof Pagefiles) return $value;
foreach($value as $k => $v) {
if($v->formatted()) continue;
$v->description = htmlspecialchars($v->description, ENT_QUOTES, "UTF-8");
$v->tags = htmlspecialchars($v->tags, ENT_QUOTES, "UTF-8");
$v->poster = pathinfo($v->url, PATHINFO_DIRNAME) . '/' . $v->poster;
$subtitles_file = str_replace('mp4', 'vtt', $v->url);
if(file_exists($this->wire('config')->paths->root . $subtitles_file)) {
$file_as_array = file($this->wire('config')->paths->root . $subtitles_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$v->transcript = '';
foreach($file_as_array as $f) {
// Find lines containing "-->"
$start_time = false;
if(preg_match("/^(\d{2}:\d{2}:[\d\.]+) --> \d{2}:\d{2}:[\d\.]+$/", $f, $match)) {
$start_time = explode('-->', $f);
$start_time = $start_time[0];
}
// It's a line of the file that doesn't include a timestamp, so it's caption text. Ignore header of file which includes the word 'WEBVTT'
if(!$start_time && (!strpos($f, 'WEBVTT')) ) {
$v->transcript .= ' ' . $f . ' ';
}
}
}
$posterPath = $this->page->filesManager()->path() . basename($v->poster);
if(file_exists($posterPath)) {
list($width, $height) = getimagesize($posterPath);
}
else {
$width = 480;
$height = 320;
}
$search = array('{url}', '{poster}', '{width}', '{height}', '{description}', '{subtitles}');
$replace = array($v->url, $v->poster, $width, $height, $v->description, $subtitles_file);
$play_code = str_replace($search, $replace, $this->player_code);
$v->play = $play_code;
$v->formatted = true;
}
if($field->maxFiles == 1) {
if(count($value)) $value = $value->first();
else $value = null;
}
return $value;
}
public function getDatabaseSchema(Field $field) {
$schema = parent::getDatabaseSchema($field);
$schema['data'] = 'varchar(255) NOT NULL';
$schema['description'] = "text NOT NULL";
$schema['poster'] = 'varchar(255) NOT NULL';
$schema['subtitles'] = 'text NOT NULL';
$schema['modified'] = "datetime";
$schema['created'] = "datetime";
$schema['keys']['description'] = 'FULLTEXT KEY description (description)';
$schema['keys']['poster'] = 'index (poster)';
$schema['keys']['modified'] = 'index (modified)';
$schema['keys']['created'] = 'index (created)';
$tagsAction = null; // null=no change; 1=add tags, 0=remove tags
$schemaTags = 'varchar(255) NOT NULL';
$schemaTagsIndex = 'FULLTEXT KEY tags (tags)';
if($field->useTags && !($field->fileSchema & self::fileSchemaTags)) $tagsAction = 'add';
else if(!$field->useTags && ($field->fileSchema & self::fileSchemaTags)) $tagsAction = 'remove';
if($tagsAction === 'add') {
// add tags field
try {
$this->db->query("ALTER TABLE `{$field->table}` ADD tags $schemaTags");
$this->db->query("ALTER TABLE `{$field->table}` ADD $schemaTagsIndex");
$field->fileSchema = $field->fileSchema | self::fileSchemaTags;
$field->save();
$this->message("Added tags to DB schema for '{$field->name}'");
} catch(Exception $e) {
$this->error("Error adding tags to '{$field->name}' schema");
}
} else if($tagsAction === 'remove') {
// remove tags field
try {
$this->db->query("ALTER TABLE `{$field->table}` DROP INDEX tags");
$this->db->query("ALTER TABLE `{$field->table}` DROP tags");
$field->fileSchema = $field->fileSchema & ~self::fileSchemaTags;
$field->save();
$this->message("Dropped tags from DB schema for '{$field->name}'");
} catch(Exception $e) {
$this->error("Error dropping tags from '{$field->name}' schema");
}
}
if($field->fileSchema & self::fileSchemaTags) {
$schema['tags'] = $schemaTags;
$schema['keys']['tags'] = $schemaTagsIndex;
}
return $schema;
}
public function getInputfield(Page $page, Field $field) {
// even though we don't want this input field, call it anyway
parent::getInputfield($page, $field);
$inputfield = $this->wire('modules')->get("InputfieldVideo");
$inputfield->class = $this->className();
$this->setupHooks($page, $field, $inputfield);
return $inputfield;
}
protected function getDefaultFileExtensions() {
return "mp4";
}
/**
* Get any inputfields used for configuration of this Fieldtype.
*
* This is in addition to any configuration fields supplied by the parent Inputfield.
*
* @param Field $field
* @return InputfieldWrapper
*
*/
public function getModuleConfigInputfields(array $data) {
foreach(self::$configDefaults as $key => $value) {
if(!isset($data[$key]) || $data[$key]=='' || $data[$key]=='~') $data[$key] = $value;
}
$inputfields = new InputfieldWrapper();
$f = $this->wire('modules')->get("InputfieldTextarea");
$f->attr('name', 'player_code');
$f->attr('value', $data["player_code"]);
$f->label = __('Player code');
$f->notes = __('Use {width}, {height}, {poster}, {url}, {subtitles} as required within the code.');
$inputfields->add($f);
return $inputfields;
}
public function ___install() {
// save default config data on install
$this->wire('modules')->saveModuleConfigData($this, self::$configDefaults);
}
}

View file

@ -0,0 +1,343 @@
<?php
/**
* ProcessWire Video Inputfieldtype
* by Adrian Jones
*
* Copyright (C) 2020 by Adrian Jones
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
*/
//use \Char0n\FFMpegPHP\Adapters\FFMpegMovie as ffmpeg_movie;
class InputfieldVideo extends InputfieldFile {
public static function getModuleInfo() {
return array(
'title' => __('Video Inputfield', __FILE__),
'summary' => __('Inputfield for uploading video files and creating poster images.', __FILE__),
'version' => '0.2.1',
'author' => 'Adrian Jones',
'href' => 'https://processwire.com/talk/topic/4580-video-fieldtype/',
'icon' => 'file-video-o',
'requires' => array("FieldtypeVideo")
);
}
public function init() {
parent::init();
$this->set('extensions', 'mp4');
$this->set('copyToImageField', 0);
$this->set('numPosterImages', 1);
$this->set('adminThumbs', false);
$this->set('imageField', '');
$this->set('maxWidth', '');
$this->set('maxHeight', '');
$this->set('adminThumbHeight', 100);
$this->set('itemClass', 'InputfieldFile InputfieldImage InputfieldVideo ui-widget');
$this->wire('modules')->get("JqueryFancybox");
}
public function ___render() {
// version number
$moduleInfo = $this->getModuleInfo();
$v = $moduleInfo['version'];
// add styles and scripts
$this->wire('config')->scripts->add($this->wire('config')->urls->siteModules . '/FieldtypeVideo/image-picker/image-picker.min.js?v=' . $v);
$this->wire('config')->styles->add($this->wire('config')->urls->siteModules . '/FieldtypeVideo/image-picker/image-picker.css?v=' . $v);
$this->wire('config')->scripts->add($this->wire('config')->urls->InputfieldFile . "InputfieldFile.js");
$this->wire('config')->styles->add($this->wire('config')->urls->InputfieldFile . "InputfieldFile.css");
return parent::___render();
}
/**
* Create poster image(s)
*
*/
protected function ___fileAdded(Pagefile $pagefile) {
/*if(pathinfo($pagefile->filename, PATHINFO_EXTENSION) == 'mp4') {
$this->loadPhpFfmpeg();
$img = htmlspecialchars(str_replace('.mp4', '.jpg', $pagefile->filename));
$media = new ffmpeg_movie ($pagefile->filename);
$frame_count = $media->getFrameCount();
$frame_number = 0;
$frames = array();
$fraction = (1/$this->numPosterImages);
$frame_number = $frame_number + $fraction;
for ($frame_number = 1; $frame_number <= $this->numPosterImages; $frame_number++) {
$frames[] = round($frame_count * $frame_number / 10);
}
$i=1;
foreach($frames as $frame) {
$img = $this->appendFilename(htmlspecialchars(str_replace('.mp4', '.jpg', $pagefile->filename)), '-'.$i);
if(!file_exists($img)) {
$selected_frame = $media->getFrame($frame);
$gd_image = $selected_frame->toGDImage();
if($gd_image) {
imagejpeg($gd_image, $img, 83);
imagedestroy($gd_image);
//make_thumb($imgfull, $img,100);
}
}
$i++;
}
}*/
return parent::___fileAdded($pagefile);
}
protected function ___renderItem($pagefile, $id, $n) {
$this->loadPhpFfmpeg();
$video = $pagefile;
$duration = '';
//$media = new ffmpeg_movie ($video->filename);
//$duration = gmdate("H:i:s", intval($media->getDuration()));
$displayName = $this->getDisplayBasename($pagefile);
$deleteLabel = $this->labels['delete'];
$out =
"<p class='InputfieldFileInfo InputfieldItemHeader ui-state-default ui-widget-header'>" .
wireIconMarkupFile($pagefile->basename, "fa-fw HideIfEmpty") . '&nbsp;' .
"<a class='InputfieldFileName' title='$pagefile->basename' target='_blank' href='{$pagefile->url}'>$displayName</a> " .
"<span class='InputfieldFileStats'>&bull; " . str_replace(' ', '&nbsp;', $pagefile->filesizeStr) . " &bull; " . $duration . "</span>
<label class='InputfieldFileDelete'>" .
"<input type='checkbox' name='delete_$id' value='1' title='$deleteLabel' />" .
"<i class='fa fa-fw fa-trash'></i>" .
"</label>";
$out .="\n\t\t\n\t\t<p class='InputfieldFileData ui-widget ui-widget-content'>" . ($this->numPosterImages > 1 ? "Select the image you want to use for the video poster / cover" : "") .
"\n\t\t" . ($this->wire('user')->isSuperuser() ? 'In templates, you can access ' . ($this->numPosterImages > 1 ? "the selected" : "this") . ' poster image ('.pathinfo(str_replace('mp4', 'jpg', $pagefile->filename),PATHINFO_BASENAME).') using: <code>$page->'.$this->name.'->'.($this->maxFiles == 1 ? '' : 'eq('.$n.')->').'poster</code>' : '') . '<br /><br />';
if($this->numPosterImages > 1) $out .= '<select id="poster_'.$id.'" name="poster_'.$id.'" class="required image-picker show-labels show-html">';
for ($i = 1; $i <= $this->numPosterImages; $i++) {
$poster_path = $this->appendFilename(str_replace('mp4', 'jpg', $video->filename), '-'.$i);
$poster_url = $this->appendFilename(str_replace('mp4', 'jpg', $video->url), '-'.$i);
$thumb_path = $this->appendFilename($poster_path, '-thumb');
$thumb_url = $this->appendFilename($poster_url, '-thumb');
list($width, $height, $type, $attr) = getimagesize($poster_path);
if($this->adminThumbs && $height > $this->adminThumbHeight && !file_exists($thumb_path)) {
// create a variation for display with this inputfield
$this->make_thumb($poster_path, $thumb_path, $this->adminThumbHeight);
}
if($this->copyToImageField == 1 && $this->imageField != '') { //if checked and images field supplied in field's Input tab settings, add this image to the defined images field
$original_image = $this->appendFilename(str_replace('mp4', 'jpg', $video->filename), '-'.$i);
$image_field_version = $this->appendFilename($this->appendFilename(str_replace('mp4', 'jpg', $video->filename), '-'.$i), '-imagefield');
copy($original_image, $image_field_version);
$current_page = wire('pages')->get((int) $_GET['id']);
$current_page->{$this->imageField}->add($image_field_version);
$current_page->save();
}
if($this->numPosterImages > 1) {
$out .= "<option data-img-src='".(($this->adminThumbs && ($height > $this->adminThumbHeight)) ? $thumb_url : $poster_url)."' id='poster_$id' value='".pathinfo($poster_path,PATHINFO_BASENAME)."'". ($pagefile->poster == pathinfo($poster_path,PATHINFO_BASENAME) ? "selected" : "") . "></option>";
}
else{
$out .= "<input type='hidden' name='poster_$id' id='poster_$id' value='".pathinfo($poster_path,PATHINFO_BASENAME)."' />
<img class='image_picker_image' src='".(($this->adminThumbs && ($height > $this->adminThumbHeight)) ? $thumb_url : $poster_url)."' alt='{$pagefile->basename}' />";
}
}
$out .= "</select><script>$('select.image-picker').imagepicker()</script><style>.InputfieldImage img:hover {cursor:pointer !important;}</style>";
$out .= "" .
"\n\t\t\t" . $this->renderItemDescriptionField($pagefile, $id, $n) .
"\n\t\t<br /><label class='InputfieldFileDescription'><span class='detail'>Subtitles</span>" .
"\n\t\t" . ($this->wire('user')->isSuperuser() ? '<br /><br />In templates, you can access this subtitles file ('.pathinfo(str_replace('mp4', 'vtt', $pagefile->filename),PATHINFO_BASENAME).') using: <code>$page->'.$this->name.'->'.($this->maxFiles == 1 ? '' : 'eq('.$n.')->').'subtitles</code>' : '') .
'<br />In templates you can access a formatted transcript (converted from subtitles entered in VTT format), by using: <code>$page->'.$this->name.'->'.($this->maxFiles == 1 ? '' : 'eq('.$n.')->').'transcript</code>' .
"\n\t\t<br /><br /><textarea rows='10' name='subtitles_$id' />{$pagefile->subtitles}</textarea>" .
"\n\t\t\t<input class='InputfieldFileSort' type='text' name='sort_$id' value='$n' />" .
"\n\t\t</p>";
return $out;
}
/**
* Get a basename for the file, possibly shortened, suitable for display in InputfieldFileList
*
* @param Pagefile $pagefile
* @param int $maxLength
* @return string
*
*/
public function getDisplayBasename(Pagefile $pagefile, $maxLength = 25) {
$displayName = $pagefile->basename;
if($this->noShortName) return $displayName;
if(strlen($displayName) > $maxLength) {
$ext = ".$pagefile->ext";
$maxLength -= (strlen($ext) + 1);
$displayName = basename($displayName, $ext);
$displayName = substr($displayName, 0, $maxLength);
$displayName .= "&hellip;" . ltrim($ext, '.');
}
return $displayName;
}
protected function ___processInputFile(WireInputData $input, Pagefile $pagefile, $n) {
$id = $this->name . '_' . $pagefile->hash;
$changed = false;
foreach(array('description', 'tags', 'poster', 'subtitles') as $key) {
if(isset($input[$key . '_' . $id])) {
$value = trim($input[$key . '_' . $id]);
if($value != $pagefile->$key) {
$pagefile->$key = $value;
$changed = true;
}
}
}
// write subtitles to a file that can be used by video player - currently only supporting vtt. Should make format optional, as well as add multi-language files
if($pagefile->subtitles != '') file_put_contents(str_replace('mp4', 'vtt', $pagefile->filename) , $pagefile->subtitles);
if(isset($input['delete_' . $id])) {
$this->processInputDeleteFile($pagefile);
$changed = true;
}
$key = "sort_$id";
$val = (int) $input->$key;
if($val !== NULL) {
$pagefile->sort = $val;
if($n !== $val) $changed = true;
}
return $changed;
}
private function loadPhpFfmpeg() {
require_once(__DIR__ . '/ffmpeg-php/Frame.php');
require_once(__DIR__ . '/ffmpeg-php/Movie.php');
require_once(__DIR__ . '/ffmpeg-php/Adapters/FFMpegFrame.php');
require_once(__DIR__ . '/ffmpeg-php/Adapters/FFMpegMovie.php');
require_once(__DIR__ . '/ffmpeg-php/OutputProviders/OutputProvider.php');
require_once(__DIR__ . '/ffmpeg-php/OutputProviders/AbstractProvider.php');
require_once(__DIR__ . '/ffmpeg-php/OutputProviders/FFMpegProvider.php');
}
public function ___getConfigInputfields() {
$inputfields = parent::___getConfigInputfields();
$field = $this->wire('modules')->get('InputfieldCheckbox');
$field->attr('name', 'adminThumbs');
$field->attr('value', 1);
$field->attr('checked', $this->adminThumbs ? 'checked' : '');
$field->label = $this->_('Display thumbnails in page editor?');
$field->description = $this->_('Thumbnails take up less space and make it easier to sort multiple images. If unchecked, the full (original) size image will be shown in the page editor.'); // Display thumbnails description
$inputfields->add($field);
$field = $this->wire('modules')->get("InputfieldText");
$field->attr('name', 'numPosterImages');
$field->attr('value', $this->numPosterImages);
$field->label = $this->_("Number of poster images to generate");
$field->description = $this->_('Images will be captured from throughout the video. This determines how many will be created. The user can choose which one is available to templates via $page->'.$this->name.'->poster');
$field->notes = $this->_("It is not recommended to make more than 10 poster images.");
$inputfields->add($field);
$field = $this->wire('modules')->get('InputfieldCheckbox');
$field->attr('name', 'copyToImageField');
$field->attr('value', 0);
$field->attr('checked', $this->copyToImageField ? 'checked' : '');
$field->label = $this->_('Copy poster image to dedicated image field?');
$field->description = $this->_('This will create a copy of the poster images in an image field of your choice. NB This is not necessary for accessing the image.');
$inputfields->add($field);
$field = $this->wire('modules')->get("InputfieldSelect");
$field->attr('name', 'imageField');
$field->attr('value', $this->imageField);
$field->required = true;
$field->showIf="copyToImageField=1";
$field->requiredIf="copyToImageField=1";
$field->label = $this->_("Field that you want to have the poster image copied into");
$field->addOption('');
foreach(wire('fields') as $fieldoption) {
if($fieldoption->type == "FieldtypeImage") $field->addOption($fieldoption->name);
}
if(isset($data['videoImagesField'])) $f->value = $data['videoImagesField'];
$inputfields->add($field);
$fieldset = $this->wire('modules')->get('InputfieldFieldset');
$fieldset->label = $this->_("Max Image Dimensions");
$fieldset->collapsed = $this->maxWidth || $this->maxHeight ? Inputfield::collapsedNo : Inputfield::collapsedYes;
$fieldset->description = $this->_("Optionally enter the max width and/or height of uploaded images. If specified, images will be resized at upload time when they exceed either the max width or height. The resize is performed at upload time, and thus does not affect any images in the system, or images added via the API."); // Max image dimensions description
$field = $this->wire('modules')->get("InputfieldInteger");
$field->attr('name', 'maxWidth');
$field->attr('value', $this->maxWidth ? (int) $this->maxWidth : '');
$field->label = $this->_("Max width for uploaded images");
$field->description = $this->_("Enter the value in number of pixels or leave blank for no max.");
$fieldset->add($field);
$field = $this->wire('modules')->get("InputfieldInteger");
$field->attr('name', 'maxHeight');
$field->attr('value', $this->maxHeight ? (int) $this->maxHeight : '');
$field->label = $this->_("Max height for uploaded images");
$field->description = $this->_("Enter the value in number of pixels or leave blank for no max.");
$fieldset->add($field);
$inputfields->add($fieldset);
return $inputfields;
}
public function make_thumb($src, $dest, $desired_height) {
/* read the source image */
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired width" of this thumbnail, relative to the desired height */
$desired_width = floor($width * ($desired_height / $height));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
/* create the physical thumbnail image to its destination */
imagejpeg($virtual_image, $dest, 83);
}
public function appendFilename($file, $suffix) {
$path_parts = pathinfo($file);
return $path_parts['dirname'] . '/' . $path_parts['filename'] . $suffix . '.' . $path_parts['extension'];
}
}

View file

@ -0,0 +1,339 @@
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,62 @@
# FieldtypeVideo
Processwire field type for storing video files and automatically creating poster images
### This new video fieldtype extends FieldtypeFile.
* Video is available via: $page->video_field->url
* Module automatically creates a poster image of the video on upload and makes this available via: $page->video_field->poster
* Shows the duration of the video on the title bar, next to the filesize
* Stores SRT files for subtitles accessed via: $page->video_field->subtitles
* Formats a transcript from the subtitles, accessed via: $page->video_field->transcript
The video can be automatically rendered on the frontend with the `play()` method via the `<video>` tag. The exact settings used can be set in the module settings like this:
```
<video src='{$page->video_field->eq(1)->url}' poster='{$page->video_field->eq(1)->poster}' width='720' height='408' ><track kind='subtitles' src='{$page->video_field->eq(1)->subtitles}' srclang='en' /></video>
```
### Usage
Basic usage only requires setting up a field with this new video fieldtype. Simply upload a video and if desired enter subtitles in SRT format.
#### Additional settings
You can additionally set a few different options in the field's Input tab:
* Number of poster images to generate - if you change from the default of 1, the editing user will be able to select which image they want to use for the poster image
* Copy poster image to dedicated image field - not necessary but gives you more options of interacting with the poster image(s)
* Field that you want poster images copied into - only relevant if the option above is checked
### Requirements
The module requires ffmpeg and ffmpeg-php, although I can make the latter optional fairly easily. I don't have any requirement checking implemented yet, so if you don't have these, you'll get php errors.
### Possible future enhancements
* Multi language versions of subtitles
* Support for uploading multiple formats of the same video (mp4, webm, etc) and/or automated video format conversion
* Integrate mediaelementjs into the module so users can enter shortcodes in RTE fields to display videos where they want
### Discussion
http://processwire.com/talk/topic/4580-video-fieldtype/
## License
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.
(See included LICENSE file for full license text.)

View file

@ -0,0 +1,38 @@
<?php
namespace Char0n\FFMpegPHP\Adapters;
use Char0n\FFMpegPHP\AnimatedGif;
use Char0n\FFMpegPHP\Frame;
/**
* Serves as a compatibility adapter for old ffmpeg-php extension.
*/
class FFMpegAnimatedGif
{
/**
* @var AnimatedGif
*/
protected $adaptee;
public function __construct($outFilePath, $width, $height, $frameRate, $loopCount)
{
$this->adaptee = new AnimatedGif($outFilePath, $width, $height, $frameRate, $loopCount);
}
public function addFrame(FFMpegFrame $frame)
{
$this->adaptee->addFrame(new Frame($frame->toGDImage(), $frame->getPTS()));
return $this->adaptee->save();
}
public function __clone()
{
$this->adaptee = clone $this->adaptee;
}
public function __destruct()
{
$this->adaptee = null;
}
}

View file

@ -0,0 +1,66 @@
<?php
namespace Char0n\FFMpegPHP\Adapters;
use Char0n\FFMpegPHP\Frame;
/**
* Serves as a compatibility adapter for old ffmpeg-php extension.
*/
class FFMpegFrame
{
/**
* @var Frame
*/
protected $adaptee;
public function __construct($gdImage, $pts = 0.0)
{
$this->adaptee = new Frame($gdImage, $pts);
}
public function getWidth()
{
return $this->adaptee->getWidth();
}
public function getHeight()
{
return $this->adaptee->getHeight();
}
public function getPTS()
{
return $this->adaptee->getPTS();
}
public function getPresentationTimestamp()
{
return $this->adaptee->getPresentationTimestamp();
}
public function resize($width, $height, $cropTop = 0, $cropBottom = 0, $cropLeft = 0, $cropRight = 0)
{
$this->adaptee->resize($width, $height, $cropTop, $cropBottom, $cropLeft, $cropRight);
}
public function crop($cropTop, $cropBottom = 0, $cropLeft = 0, $cropRight = 0)
{
$this->adaptee->crop($cropTop, $cropBottom, $cropLeft, $cropRight);
}
public function toGDImage()
{
return $this->adaptee->toGDImage();
}
public function __clone()
{
$this->adaptee = clone $this->adaptee;
}
public function __destruct()
{
$this->adaptee = null;
}
}

View file

@ -0,0 +1,186 @@
<?php
namespace Char0n\FFMpegPHP\Adapters;
use Char0n\FFMpegPHP\Movie;
use Char0n\FFMpegPHP\OutputProviders\FFMpegProvider;
/**
* Serves as a compatibility adapter for old ffmpeg-php extension.
*/
class FFMpegMovie
{
/**
* @var Movie
*/
protected $adaptee;
public function __construct($moviePath, $persistent = false)
{
$this->adaptee = new Movie($moviePath, new FFMpegProvider('ffmpeg', $persistent));
}
public function getDuration()
{
return $this->adaptee->getDuration();
}
public function getFrameCount()
{
return $this->adaptee->getFrameCount();
}
public function getFrameRate()
{
return $this->adaptee->getFrameRate();
}
public function getFilename()
{
return $this->adaptee->getFilename();
}
public function getComment()
{
return $this->adaptee->getComment();
}
public function getTitle()
{
return $this->adaptee->getTitle();
}
public function getArtist()
{
return $this->adaptee->getArtist();
}
public function getAuthor()
{
return $this->adaptee->getAuthor();
}
public function getCopyright()
{
return $this->adaptee->getCopyright();
}
public function getGenre()
{
return $this->adaptee->getGenre();
}
public function getTrackNumber()
{
return $this->adaptee->getTrackNumber();
}
public function getYear()
{
return $this->adaptee->getYear();
}
public function getFrameHeight()
{
return $this->adaptee->getFrameHeight();
}
public function getFrameWidth()
{
return $this->adaptee->getFrameWidth();
}
public function getPixelFormat()
{
return $this->adaptee->getPixelFormat();
}
public function getPixelAspectRatio()
{
return $this->adaptee->getPixelAspectRatio();
}
public function getBitRate()
{
return $this->adaptee->getBitRate();
}
public function getVideoBitRate()
{
return $this->adaptee->getVideoBitRate();
}
public function getAudioBitRate()
{
return $this->adaptee->getAudioBitRate();
}
public function getAudioSampleRate()
{
return $this->adaptee->getAudioSampleRate();
}
public function getFrameNumber()
{
return $this->adaptee->getFrameNumber();
}
public function getVideoCodec()
{
return $this->adaptee->getVideoCodec();
}
public function getAudioCodec()
{
return $this->adaptee->getAudioCodec();
}
public function getAudioChannels()
{
return $this->adaptee->getAudioChannels();
}
public function hasAudio()
{
return $this->adaptee->hasAudio();
}
public function hasVideo()
{
return $this->adaptee->hasVideo();
}
public function getFrame($framenumber = null)
{
$toReturn = null;
$frame = $this->adaptee->getFrame($framenumber);
if ($frame != null) {
$toReturn = new FFMpegFrame($frame->toGDImage(), $frame->getPTS());
$frame = null;
}
return $toReturn;
}
public function getNextKeyFrame()
{
$toReturn = null;
$frame = $this->adaptee->getNextKeyFrame();
if ($frame != null) {
$toReturn = new FFMpegFrame($frame->toGDImage(), $frame->getPTS());
$frame = null;
}
return $toReturn;
}
public function __clone()
{
$this->adaptee = clone $this->adaptee;
}
public function __destruct()
{
$this->adaptee = null;
}
}

View file

@ -0,0 +1,317 @@
<?php
namespace Char0n\FFMpegPHP;
/**
* AnimatedGif represents an animated gif object.
*
* This class in implemented in rather un-orthodox way.
* Reason is that ffmpeg doesn't provide satisfactory
* quality and compression of animated gifs.
*
* Code fragments used from: GIFEncoder Version 2.0 by László Zsidi
*/
class AnimatedGif
{
/**
* Location in the filesystem where the animated gif will be written.
*
* @var string
*/
protected $outFilePath;
/**
* Width of the animated gif.
*
* @var int
*/
protected $width;
/**
* Height of the animated gif.
*
* @var int
*/
protected $height;
/**
* Frame rate of the animated gif in frames per second.
*
* @var int
*/
protected $frameRate;
/**
* Number of times to loop the animation. Put a zero here to loop forever or omit this parameter to disable looping.
*
* @var int
*/
protected $loopCount;
/**
* Binary data of gif files to create animation.
*
* @var array
*/
protected $frames;
/**
* Gif binary data of animation.
*
* @var string
*/
protected $gifData;
/**
* Counter of first animation.
*
* @var mixed
*/
protected $counter;
/**
* Create a new AnimatedGif object.
*
* @param string $outFilePath Location in the filesystem where the animated gif will be written.
* @param int $width Width of the animated gif.
* @param int $height Height of the animated gif.
* @param int $frameRate Frame rate of the animated gif in frames per second.
* @param int $loopCount Number of times to loop the animation. Put a zero here to loop forever or omit this
* parameter to disable looping.
*/
public function __construct($outFilePath, $width, $height, $frameRate, $loopCount)
{
$this->outFilePath = $outFilePath;
$this->width = $width;
$this->height = $height;
$this->frameRate = $frameRate;
$this->loopCount = ($loopCount < -1) ? 0 : $loopCount;
$this->frames = [];
$this->counter = -1;
}
/**
* Add a frame to the end of the animated gif.
*
* @param Frame $frame Frame to add.
*/
public function addFrame(Frame $frame)
{
$tmpFrame = clone $frame;
$tmpFrame->resize($this->width, $this->height);
ob_start();
imagegif($tmpFrame->toGDImage());
$this->frames[] = ob_get_clean();
$tmpFrame = null;
}
/**
* Adding header to the animation.
*
* @return void
*/
protected function addGifHeader()
{
if (ord($this->frames[0][10]) & 0x80) {
$cMap = 3 * (2 << (ord($this->frames[0][10]) & 0x07));
$this->gifData = 'GIF89a';
$this->gifData .= substr($this->frames[0], 6, 7);
$this->gifData .= substr($this->frames[0], 13, $cMap);
$this->gifData .= "!\377\13NETSCAPE2.0\3\1".$this->getGifWord($this->loopCount)."\0";
}
}
/**
* Adding frame binary data to the animation.
*
* @param int $i Index of frame from AnimatedGif::frame array.
* @param int $d Delay (5 seconds = 500 delay units).
*
* @return void
*/
protected function addFrameData($i, $d)
{
$dis = 2;
$col = 0;
$localsString = 13 + 3 * (2 << (ord($this->frames[$i][10]) & 0x07));
$localsEnd = strlen($this->frames[$i]) - $localsString - 1;
$localsTmp = substr($this->frames[$i], $localsString, $localsEnd);
$globalLength = 2 << (ord($this->frames[0][10]) & 0x07);
$localsLength = 2 << (ord($this->frames[$i][10]) & 0x07);
$globalRbg = substr($this->frames[0], 13, 3 * (2 << (ord($this->frames[0][10]) & 0x07)));
$localsRgb = substr($this->frames[$i], 13, 3 * (2 << (ord($this->frames[$i][10]) & 0x07)));
$localsExt = "!\xF9\x04".chr(($dis << 2) + 0).chr(($d >> 0) & 0xFF).chr(($d >> 8) & 0xFF)."\x0\x0";
$localsImg = null;
if ($col > -1 && ord($this->frames[$i][10]) & 0x80) {
for ($j = 0; $j < (2 << (ord($this->frames[$i][10]) & 0x07)); $j++) {
if (ord($localsRgb[3 * $j + 0]) === (($col >> 16) & 0xFF)
&& ord($localsRgb[3 * $j + 1]) === (($col >> 8) & 0xFF)
&& ord($localsRgb[3 * $j + 2]) === (($col >> 0) & 0xFF)
) {
$localsExt = "!\xF9\x04".chr(($dis << 2) + 1).chr(($d >> 0) & 0xFF).chr(($d >> 8) & 0xFF).chr(
$j
)."\x0";
break;
}
}
}
switch ($localsTmp[0]) {
case '!':
$localsImg = substr($localsTmp, 8, 10);
$localsTmp = substr($localsTmp, 18);
break;
case ',':
$localsImg = substr($localsTmp, 0, 10);
$localsTmp = substr($localsTmp, 10);
break;
}
if ($this->counter > -1 && ord($this->frames[$i][10]) & 0x80) {
if ($globalLength === $localsLength) {
if ($this->gifBlockCompare($globalRbg, $localsRgb, $globalLength)) {
$this->gifData .= ($localsExt.$localsImg.$localsTmp);
} else {
$byte = ord($localsImg[9]);
$byte |= 0x80;
$byte &= 0xF8;
$byte |= (ord($this->frames[0][10]) & 0x07);
$localsImg[9] = chr($byte);
$this->gifData .= ($localsExt.$localsImg.$localsRgb.$localsTmp);
}
} else {
$byte = ord($localsImg[9]);
$byte |= 0x80;
$byte &= 0xF8;
$byte |= (ord($this->frames[$i][10]) & 0x07);
$localsImg[9] = chr($byte);
$this->gifData .= ($localsExt.$localsImg.$localsRgb.$localsTmp);
}
} else {
$this->gifData .= ($localsExt.$localsImg.$localsTmp);
}
$this->counter = 1;
}
/**
* Adding footer to the animation.
*
* @return void
*/
protected function addGifFooter()
{
$this->gifData .= ';';
}
/**
* Gif integer wrapper.
*
* @param int $int
*
* @return string
*/
protected function getGifWord($int)
{
return (chr($int & 0xFF).chr(($int >> 8) & 0xFF));
}
/**
* Gif compare block.
*
* @param string $globalBlock
* @param string $localBlock
* @param int $len
*
* @return bool
*/
protected function gifBlockCompare($globalBlock, $localBlock, $len)
{
for ($i = 0; $i < $len; $i++) {
if ($globalBlock[3 * $i + 0] !== $localBlock[3 * $i + 0] ||
$globalBlock[3 * $i + 1] !== $localBlock[3 * $i + 1] ||
$globalBlock[3 * $i + 2] !== $localBlock[3 * $i + 2]
) {
return false;
}
}
return true;
}
/**
* Saving animated gif to remote file.
*
* @return boolean
*/
public function save()
{
// No images to process
if (0 === count($this->frames)) {
return false;
}
return (boolean)file_put_contents($this->outFilePath, $this->getAnimation(), LOCK_EX);
}
/**
* Getting animation binary data.
*
* @return string|boolean
*/
public function getAnimation()
{
// No images to process.
if (0 === count($this->frames)) {
return false;
}
// Process images as animation.
$this->addGifHeader();
for ($i = 0, $frameCount = count($this->frames); $i < $frameCount; $i++) {
$this->addFrameData($i, 1 / $this->frameRate * 100);
}
$this->addGifFooter();
return $this->gifData;
}
/**
* String representation of an AnimatedGif.
*
* @return array The string representation of the object or null.
*/
public function __serialize()
{
return [
$this->outFilePath,
$this->width,
$this->height,
$this->frameRate,
$this->loopCount,
$this->gifData,
$this->frames,
$this->counter,
];
}
/**
* Constructs the AnimatedGif.
*
* @param array $serialized The string representation of the object.
*
* @return void
*/
public function __unserialize($serialized)
{
list(
$this->outFilePath,
$this->width,
$this->height,
$this->frameRate,
$this->loopCount,
$this->gifData,
$this->frames,
$this->counter
) = $serialized;
}
}

View file

@ -0,0 +1,229 @@
<?php
namespace Char0n\FFMpegPHP;
/**
* Represents one frame from the movie.
*/
class Frame
{
protected static $EX_CODE_NO_VALID_RESOURCE = 334563;
/**
* GdImage binary data.
*
* @var string
*/
protected $gdImageData;
/**
* Presentation time stamp.
*
* @var float
*/
protected $pts;
/**
* Frame width in pixels.
*
* @var int
*/
protected $width;
/**
* Frame height in pixels.
*
* @var int
*/
protected $height;
/**
* Create a Frame object from a GD image.
*
* @param resource $gdImage Image resource of type gd.
* @param float $pts Frame presentation timestamp.
*
* @throws \UnexpectedValueException
*/
public function __construct($gdImage, $pts = 0.0)
{
if ((!(is_resource($gdImage) && 'gd' === get_resource_type($gdImage))) && !($gdImage instanceof \GdImage)) {
throw new \UnexpectedValueException(
'Param given by constructor is not valid gd resource',
self::$EX_CODE_NO_VALID_RESOURCE
);
}
$this->gdImageData = $this->gdImageToBinaryData($gdImage);
$this->width = imagesx($gdImage);
$this->height = imagesy($gdImage);
$this->pts = $pts;
}
/**
* Transforms gdImage resource to binary data.
*
* @param resource $gdImage
* @return string
*/
protected function gdImageToBinaryData($gdImage)
{
ob_start();
imagejpeg($gdImage, null, 100);
return ob_get_clean();
}
/**
* Return the presentation time stamp of the frame.
*
* @return float
*/
public function getPresentationTimestamp()
{
return $this->getPTS();
}
/**
* Return the presentation time stamp of the frame; alias $frame->getPresentationTimestamp().
*
* @return float
*/
public function getPTS()
{
return $this->pts;
}
/**
* Crop the frame.
*
* NOTE: Crop values must be even numbers.
*
* @param int $cropTop Rows of pixels removed from the top of the frame.
* @param int $cropBottom Rows of pixels removed from the bottom of the frame.
* @param int $cropLeft Rows of pixels removed from the left of the frame.
* @param int $cropRight Rows of pixels removed from the right of the frame.
*
* @return void
*/
public function crop($cropTop, $cropBottom = 0, $cropLeft = 0, $cropRight = 0)
{
$this->resize($this->getWidth(), $this->getHeight(), $cropTop, $cropBottom, $cropLeft, $cropRight);
}
/**
* Resize and optionally crop the frame. (Cropping is built into ffmpeg resizing so I'm providing it here for
* completeness.)
*
* NOTE: Cropping is always applied to the frame before it is resized. Crop values must be even numbers.
*
* @param int $width New width of the frame (must be an even number).
* @param int $height New height of the frame (must be an even number).
* @param int $cropTop Rows of pixels removed from the top of the frame.
* @param int $cropBottom Rows of pixels removed from the bottom of the frame.
* @param int $cropLeft Rows of pixels removed from the left of the frame.
* @param int $cropRight Rows of pixels removed from the right of the frame.
*
* @return void
*/
public function resize($width, $height, $cropTop = 0, $cropBottom = 0, $cropLeft = 0, $cropRight = 0)
{
$widthCrop = ($cropLeft + $cropRight);
$heightCrop = ($cropTop + $cropBottom);
$width -= $widthCrop;
$height -= $heightCrop;
$resizedImage = imagecreatetruecolor($width, $height);
$gdImage = $this->toGDImage();
imagecopyresampled(
$resizedImage,
$gdImage,
0,
0,
$cropLeft,
$cropTop,
$width,
$height,
$this->getWidth() - $widthCrop,
$this->getHeight() - $heightCrop
);
imageconvolution(
$resizedImage,
[
[-1, -1, -1],
[-1, 24, -1],
[-1, -1, -1],
],
16,
0
);
$this->gdImageData = $this->gdImageToBinaryData($resizedImage);
$this->width = imagesx($resizedImage);
$this->height = imagesy($resizedImage);
imagedestroy($gdImage);
imagedestroy($resizedImage);
}
/**
* Returns a truecolor GD image of the frame.
*
* @return resource Resource of type gd.
*/
public function toGDImage()
{
return imagecreatefromstring($this->gdImageData);
}
/**
* Return the width of the frame.
*
* @return int
*/
public function getWidth()
{
return $this->width;
}
/**
* Return the height of the frame.
*
* @return int
*/
public function getHeight()
{
return $this->height;
}
/**
* Return string representation of a Frame.
*
* @return array The string representation of the object or null.
*/
public function __serialize()
{
return [
$this->gdImageData,
$this->pts,
$this->width,
$this->height,
];
}
/**
* Constructs the Frame from serialized data.
*
* @param array $serialized The string representation of Frame instance.
*
* @return void
*/
public function __unserialize($serialized)
{
list(
$this->gdImageData,
$this->pts,
$this->width,
$this->height
) = $serialized;
}
}

View file

@ -0,0 +1,916 @@
<?php
namespace Char0n\FFMpegPHP;
use Char0n\FFMpegPHP\OutputProviders\FFMpegProvider;
use Char0n\FFMpegPHP\OutputProviders\OutputProvider;
/**
* Represents a movie file.
*/
class Movie
{
protected static $REGEX_DURATION = '/Duration: (\d{2}):(\d{2}):(\d{2})(\.(\d+))?/';
protected static $REGEX_FRAME_RATE = '/([0-9\.]+\sfps,\s)?([0-9\.]+)\stb(?:r|n)/';
protected static $REGEX_COMMENT = '/comment\s*(:|=)\s*(.+)/i';
protected static $REGEX_TITLE = '/title\s*(:|=)\s*(.+)/i';
protected static $REGEX_ARTIST = '/(artist|author)\s*(:|=)\s*(.+)/i';
protected static $REGEX_COPYRIGHT = '/copyright\s*(:|=)\s*(.+)/i';
protected static $REGEX_GENRE = '/genre\s*(:|=)\s*(.+)/i';
protected static $REGEX_TRACK_NUMBER = '/track\s*(:|=)\s*(.+)/i';
protected static $REGEX_YEAR = '/year\s*(:|=)\s*(.+)/i';
protected static $REGEX_FRAME_WH = '/Video:.+?([1-9]\d*)x([1-9]\d*)/';
protected static $REGEX_PIXEL_FORMAT = '/Video: [^,]+, ([^,]+)/';
protected static $REGEX_PIXEL_ASPECT_RATIO = '/Video:.+DAR (\d+):(\d+)\]/';
protected static $REGEX_BITRATE = '/bitrate: (\d+) kb\/s/';
protected static $REGEX_VIDEO_BITRATE = '/Video:.+?(\d+) kb\/s/';
protected static $REGEX_AUDIO_BITRATE = '/Audio:.+?(\d+) kb\/s/';
protected static $REGEX_AUDIO_SAMPLE_RATE = '/Audio:.+?(\d+) Hz/';
protected static $REGEX_VIDEO_CODEC = '/Video:\s([^,]+),/';
protected static $REGEX_AUDIO_CODEC = '/Audio:\s([^,]+),/';
protected static $REGEX_AUDIO_CHANNELS = '/Audio:\s[^,]+,[^,]+,([^,]+)/';
protected static $REGEX_HAS_AUDIO = '/Stream.+Audio/';
protected static $REGEX_HAS_VIDEO = '/Stream.+Video/';
protected static $REGEX_ROTATION = '/rotate\s*[:=]\s*(-?[0-9]+)/';
protected static $REGEX_ERRORS = '/.*(Error|Permission denied|could not seek to position|Invalid pixel
format|Unknown encoder|could not find codec|does not contain any stream).*/i';
/**
* Path to `ffmpeg` binary.
*
* @var string
*/
protected $ffmpegBinary;
/**
* Output provider instance.
*
* @var OutputProvider
*/
protected $provider;
/**
* Movie file path
*
* @var string
*/
protected $movieFile;
/**
* Output providers output as string.
*
* @var string
*/
protected $output;
/**
* Movie duration in seconds.
*
* @var float
*/
protected $duration;
/**
* Current frame index
*
* @var int
*/
protected $frameCount;
/**
* Movie frame rate.
*
* @var float
*/
protected $frameRate;
/**
* Comment ID3 field.
*
* @var string
*/
protected $comment;
/**
* Title ID3 field.
*
* @var string
*/
protected $title;
/**
* Author ID3 field.
*
* @var string
*/
protected $artist;
/**
* Copyright ID3 field.
*
* @var string
*/
protected $copyright;
/**
* Genre ID3 field.
*
* @var string
*/
protected $genre;
/**
* Track ID3 field.
*
* @var int
*/
protected $trackNumber;
/**
* Year ID3 field.
*
* @var int
*/
protected $year;
/**
* Movie frame height.
*
* @var int
*/
protected $frameHeight;
/**
* Movie frame width.
*
* @var int
*/
protected $frameWidth;
/**
* Movie pixel format.
*
* @var string
*/
protected $pixelFormat;
/**
* Movie pixel aspect ratio.
*
* @var float
*/
protected $pixelAspectRatio;
/**
* Movie bit rate combined with audio bit rate.
*
* @var int
*/
protected $bitRate;
/**
* Movie video stream bit rate.
*
* @var int
*/
protected $videoBitRate;
/**
* Movie audio stream bit rate.
*
* @var int
*/
protected $audioBitRate;
/**
* Audio sample rate.
*
* @var int
*/
protected $audioSampleRate;
/**
* Current frame number.
*
* @var int
*/
protected $frameNumber;
/**
* Movie video codec.
*
* @var string
*/
protected $videoCodec;
/**
* Movie audio codec.
*
* @var string
*/
protected $audioCodec;
/**
* Movie audio channels.
*
* @var int
*/
protected $audioChannels;
/**
* Movie rotation.
*
* @var int
*/
protected $rotation;
/**
* Open a video or audio file and return it as an Movie object.
* If ffmpeg and ffprobe are both installed on host system, ffmpeg
* gets priority in extracting info from the movie file. However
* to override this default behaviour use any implementation of OutputProviderInterface
* as the second constructor argument while instantiating
*
*
* @param string $moviePath Full path to the movie file.
* @param OutputProvider $outputProvider Provides parsable output.
* @param string $ffmpegBinary `ffmpeg` executable, if $outputProvider not specified.
*
* @throws \Exception
*/
public function __construct($moviePath, OutputProvider $outputProvider = null, $ffmpegBinary = 'ffmpeg')
{
$this->movieFile = $moviePath;
$this->frameNumber = 0;
$this->ffmpegBinary = $ffmpegBinary;
if ($outputProvider === null) {
$outputProvider = new FFMpegProvider($ffmpegBinary);
}
$this->setProvider($outputProvider);
}
/**
* Setting output provider implementation.
*
* @param OutputProvider $outputProvider
*
* @return $this
*/
public function setProvider(OutputProvider $outputProvider)
{
$this->provider = $outputProvider;
$this->provider->setMovieFile($this->movieFile);
$this->output = $this->provider->getOutput();
return $this;
}
/**
* Getting current output provider implementation.
*
* @return OutputProvider
*/
public function getProvider()
{
return $this->provider;
}
/**
* Return the duration of a movie or audio file in seconds.
*
* @return float Movie duration in seconds.
*/
public function getDuration()
{
if ($this->duration === null) {
$match = [];
preg_match(self::$REGEX_DURATION, $this->output, $match);
if (array_key_exists(1, $match) && array_key_exists(2, $match) && array_key_exists(3, $match)) {
$hours = (int)$match[1];
$minutes = (int)$match[2];
$seconds = (int)$match[3];
$fractions = (float)(array_key_exists(5, $match) ? '0.'.$match[5] : 0.0);
$this->duration = (($hours * 3600) + ($minutes * 60) + $seconds + $fractions);
} else {
$this->duration = 0.0;
}
return $this->duration;
}
return $this->duration;
}
/**
* Return the number of frames in a movie or audio file.
*
* @return int
*/
public function getFrameCount()
{
if ($this->frameCount === null) {
$this->frameCount = (int)($this->getDuration() * $this->getFrameRate());
}
return $this->frameCount;
}
/**
* Return the frame rate of a movie in fps.
*
* @return float
*/
public function getFrameRate()
{
if ($this->frameRate === null) {
$match = [];
preg_match(self::$REGEX_FRAME_RATE, $this->output, $match);
$this->frameRate = (float)(array_key_exists(1, $match) ? $match[1] : 0.0);
}
return $this->frameRate;
}
/**
* Return the path and name of the movie file or audio file.
*
* @return string
*/
public function getFilename()
{
return $this->movieFile;
}
/**
* Return the comment field from the movie or audio file.
*
* @return string
*/
public function getComment()
{
if ($this->comment === null) {
$match = [];
preg_match(self::$REGEX_COMMENT, $this->output, $match);
$this->comment = array_key_exists(2, $match) ? trim($match[2]) : '';
}
return $this->comment;
}
/**
* Return the title field from the movie or audio file.
*
* @return string
*/
public function getTitle()
{
if ($this->title === null) {
$match = [];
preg_match(self::$REGEX_TITLE, $this->output, $match);
$this->title = array_key_exists(2, $match) ? trim($match[2]) : '';
}
return $this->title;
}
/**
* Return the author field from the movie or the artist ID3 field from an mp3 file; alias $movie->getArtist()
*
* @return string
*/
public function getArtist()
{
if ($this->artist === null) {
$match = [];
preg_match(self::$REGEX_ARTIST, $this->output, $match);
$this->artist = array_key_exists(3, $match) ? trim($match[3]) : '';
}
return $this->artist;
}
/**
* Return the author field from the movie or the artist ID3 field from an mp3 file.
*
* @return string
*/
public function getAuthor()
{
return $this->getArtist();
}
/**
* Return the copyright field from the movie or audio file.
*
* @return string
*/
public function getCopyright()
{
if ($this->copyright === null) {
$match = [];
preg_match(self::$REGEX_COPYRIGHT, $this->output, $match);
$this->copyright = array_key_exists(2, $match) ? trim($match[2]) : '';
}
return $this->copyright;
}
/**
* Return the genre ID3 field from an mp3 file.
*
* @return string
*/
public function getGenre()
{
if ($this->genre === null) {
$match = [];
preg_match(self::$REGEX_GENRE, $this->output, $match);
$this->genre = array_key_exists(2, $match) ? trim($match[2]) : '';
}
return $this->genre;
}
/**
* Return the track ID3 field from an mp3 file.
*
* @return int
*/
public function getTrackNumber()
{
if ($this->trackNumber === null) {
$match = [];
preg_match(self::$REGEX_TRACK_NUMBER, $this->output, $match);
$this->trackNumber = (int)(array_key_exists(2, $match) ? $match[2] : 0);
}
return $this->trackNumber;
}
/**
* Return the year ID3 field from an mp3 file.
*
* @return int
*/
public function getYear()
{
if ($this->year === null) {
$match = [];
preg_match(self::$REGEX_YEAR, $this->output, $match);
$this->year = (int)(array_key_exists(2, $match) ? $match[2] : 0);
}
return $this->year;
}
/**
* Return the height of the movie in pixels.
*
* @return int
*/
public function getFrameHeight()
{
if (null === $this->frameHeight) {
$match = [];
preg_match(self::$REGEX_FRAME_WH, $this->output, $match);
if (array_key_exists(1, $match) && array_key_exists(2, $match)) {
$this->frameWidth = (int)$match[1];
$this->frameHeight = (int)$match[2];
} else {
$this->frameWidth = 0;
$this->frameHeight = 0;
}
}
return $this->frameHeight;
}
/**
* Return the width of the movie in pixels.
*
* @return int
*/
public function getFrameWidth()
{
if ($this->frameWidth === null) {
$this->getFrameHeight();
}
return $this->frameWidth;
}
/**
* Return the pixel format of the movie.
*
* @return string
*/
public function getPixelFormat()
{
if ($this->pixelFormat === null) {
$match = [];
preg_match(self::$REGEX_PIXEL_FORMAT, $this->output, $match);
$this->pixelFormat = array_key_exists(1, $match) ? trim($match[1]) : '';
}
return $this->pixelFormat;
}
/**
* Return the pixel aspect ratio of the movie.
*
* @return float
*/
public function getPixelAspectRatio()
{
if ($this->pixelAspectRatio === null) {
$match = [];
preg_match(self::$REGEX_PIXEL_ASPECT_RATIO, $this->output, $match);
$this->pixelAspectRatio = (array_key_exists(1, $match) && array_key_exists(
2,
$match
)) ? ($match[1] / $match[2]) : 0;
}
return $this->pixelAspectRatio;
}
/**
* Return the rotation angle of the movie.
*
* @return int
*/
public function getRotation()
{
if ($this->rotation === null) {
$match = array();
preg_match(self::$REGEX_ROTATION, $this->output, $match);
$this->rotation = (array_key_exists(1, $match)) ? intval(trim($match[1])) : 0;
}
return $this->rotation;
}
/**
* Return the bit rate of the movie or audio file in bits per second.
*
* @return int
*/
public function getBitRate()
{
if ($this->bitRate === null) {
$match = [];
preg_match(self::$REGEX_BITRATE, $this->output, $match);
$this->bitRate = (int)(array_key_exists(1, $match) ? ($match[1] * 1000) : 0);
}
return $this->bitRate;
}
/**
* Return the bit rate of the video in bits per second.
*
* NOTE: This only works for files with constant bit rate.
*
* @return int
*/
public function getVideoBitRate()
{
if ($this->videoBitRate === null) {
$match = [];
preg_match(self::$REGEX_VIDEO_BITRATE, $this->output, $match);
$this->videoBitRate = (int)(array_key_exists(1, $match) ? ($match[1] * 1000) : 0);
}
return $this->videoBitRate;
}
/**
* Return the audio bit rate of the media file in bits per second.
*
* @return int
*/
public function getAudioBitRate()
{
if ($this->audioBitRate === null) {
$match = [];
preg_match(self::$REGEX_AUDIO_BITRATE, $this->output, $match);
$this->audioBitRate = (int)(array_key_exists(1, $match) ? ($match[1] * 1000) : 0);
}
return $this->audioBitRate;
}
/**
* Return the audio sample rate of the media file in bits per second.
*
* @return int
*/
public function getAudioSampleRate()
{
if ($this->audioSampleRate === null) {
$match = [];
preg_match(self::$REGEX_AUDIO_SAMPLE_RATE, $this->output, $match);
$this->audioSampleRate = (int)(array_key_exists(1, $match) ? $match[1] : 0);
}
return $this->audioSampleRate;
}
/**
* Return the current frame index.
*
* @return int
*/
public function getFrameNumber()
{
return (0 === $this->frameNumber) ? 1 : $this->frameNumber;
}
/**
* Return the name of the video codec used to encode this movie.
*
* @return string
*/
public function getVideoCodec()
{
if ($this->videoCodec === null) {
$match = [];
preg_match(self::$REGEX_VIDEO_CODEC, $this->output, $match);
$this->videoCodec = array_key_exists(1, $match) ? trim($match[1]) : '';
}
return $this->videoCodec;
}
/**
* Return the name of the audio codec used to encode this movie.
*
* @return string
*/
public function getAudioCodec()
{
if ($this->audioCodec === null) {
$match = [];
preg_match(self::$REGEX_AUDIO_CODEC, $this->output, $match);
$this->audioCodec = array_key_exists(1, $match) ? trim($match[1]) : '';
}
return $this->audioCodec;
}
/**
* Return the number of audio channels in this movie.
*
* @return int
*/
public function getAudioChannels()
{
if ($this->audioChannels === null) {
$match = [];
preg_match(self::$REGEX_AUDIO_CHANNELS, $this->output, $match);
if (array_key_exists(1, $match)) {
switch (trim($match[1])) {
case 'mono':
$this->audioChannels = 1;
break;
case 'stereo':
$this->audioChannels = 2;
break;
case '5.1':
$this->audioChannels = 6;
break;
case '5:1':
$this->audioChannels = 6;
break;
default:
$this->audioChannels = (int)$match[1];
}
} else {
$this->audioChannels = 0;
}
}
return $this->audioChannels;
}
/**
* Return boolean value indicating whether the movie has an audio stream.
*
* @return boolean
*/
public function hasAudio()
{
return (boolean)preg_match(self::$REGEX_HAS_AUDIO, $this->output);
}
/**
* Return boolean value indicating whether the movie has a video stream.
*
* @return boolean
*/
public function hasVideo()
{
return (boolean)preg_match(self::$REGEX_HAS_VIDEO, $this->output);
}
/**
* Returns a frame from the movie as an Frame object. Returns false if the frame was not found.
*
* @param int $frameNumber Frame from the movie to return. If no frame number is specified,
* returns the next frame of the movie.
* @param int $width
* @param int $height
* @param int $quality
*
* @return Frame|boolean
*/
public function getFrame($frameNumber = null, $width = null, $height = null, $quality = null)
{
$framePos = ($frameNumber === null) ? $this->frameNumber : (((int)$frameNumber) - 1);
// Frame position out of range
if (!is_numeric($framePos) || $framePos < 0 || $framePos > $this->getFrameCount()) {
return false;
}
$frameTime = round(($framePos / $this->getFrameCount()) * $this->getDuration(), 4);
$frame = $this->getFrameAtTime($frameTime, $width, $height, $quality);
// Increment internal frame number
if ($frameNumber === null) {
++$this->frameNumber;
}
return $frame;
}
/**
* Returns a frame from the movie as a Frame object. Returns false if the frame was not found.
*
* @param float $seconds
* @param int $width
* @param int $height
* @param int $quality
* @param string $frameFilePath
* @param array $output
*
* @throws \RuntimeException
*
* @return Frame|boolean
*/
public function getFrameAtTime(
$seconds = null,
$width = null,
$height = null,
$quality = null,
$frameFilePath = null,
&$output = null
) {
// set frame position for frame extraction
$frameTime = ($seconds === null) ? 0 : $seconds;
// time out of range
if (!is_numeric($frameTime) || $frameTime < 0 || $frameTime > $this->getDuration()) {
throw new \RuntimeException(
'Frame time is not in range '.$frameTime.'/'.$this->getDuration().' '.$this->getFilename()
);
}
$image_size = '';
if (is_numeric($height) && is_numeric($width)) {
$image_size = ' -s '.$width.'x'.$height;
}
$qualityCommand = '';
if (is_numeric($quality)) {
$qualityCommand = ' -qscale '.$quality;
}
$deleteTmp = false;
if ($frameFilePath === null) {
$frameFilePath = sys_get_temp_dir().DIRECTORY_SEPARATOR.uniqid('frame', true).'.jpg';
$deleteTmp = true;
}
$output = [];
// Fast and accurate way to seek. First quick-seek before input up to
// a point just before the frame, and then accurately seek after input
// to the exact point.
// See: http://ffmpeg.org/trac/ffmpeg/wiki/Seeking%20with%20FFmpeg
if ($frameTime > 30) {
$seek1 = $frameTime - 30;
$seek2 = 30;
} else {
$seek1 = 0;
$seek2 = $frameTime;
}
exec(
implode(
' ',
[
$this->ffmpegBinary,
'-ss '.$seek1,
'-i '.escapeshellarg($this->movieFile),
'-f image2',
'-ss '.$seek2,
'-vframes 1',
$image_size,
$qualityCommand,
escapeshellarg($frameFilePath),
'2>&1',
]
),
$output,
$retVar
);
/** @noinspection ReferenceMismatchInspection */
$stringOutput = implode(PHP_EOL, $output);
// Cannot write frame to the data storage
if (!file_exists($frameFilePath)) {
// Find error in output
preg_match(self::$REGEX_ERRORS, $stringOutput, $errors);
if ($errors) {
throw new \RuntimeException($errors[0]);
}
// Default file not found error
throw new \RuntimeException('TMP image not found/written '.$frameFilePath);
}
// Create gdimage and delete temporary image
$imageSize = getimagesize($frameFilePath);
switch ($imageSize[2]) {
case IMAGETYPE_GIF:
$gdImage = imagecreatefromgif($frameFilePath);
break;
case IMAGETYPE_PNG:
$gdImage = imagecreatefrompng($frameFilePath);
break;
default:
$gdImage = imagecreatefromjpeg($frameFilePath);
}
if ($deleteTmp && is_writable($frameFilePath)) {
unlink($frameFilePath);
}
$frame = new Frame($gdImage, $frameTime);
imagedestroy($gdImage);
return $frame;
}
/**
* Returns the next key frame from the movie as an Frame object. Returns false if the frame was not found.
*
* @return Frame|boolean
*/
public function getNextKeyFrame()
{
return $this->getFrame();
}
public function __clone()
{
$this->provider = clone $this->provider;
}
/**
* String representation of a Movie.
*
* @return array Rhe string representation of the object or null.
*/
public function __serialize()
{
return [
$this->ffmpegBinary,
$this->movieFile,
$this->output,
$this->frameNumber,
$this->provider,
];
}
/**
* Constructs the Movie from serialized data.
*
* @param array $serialized The string representation of Movie instance.
*
* @return void
*/
public function __unserialize($serialized)
{
list(
$this->ffmpegBinary,
$this->movieFile,
$this->output,
$this->frameNumber,
$this->provider
) = $serialized;
}
}

View file

@ -0,0 +1,73 @@
<?php
namespace Char0n\FFMpegPHP\OutputProviders;
/**
* AbstractProvider parent of all output providers.
*/
abstract class AbstractProvider implements OutputProvider
{
protected static $EX_CODE_FILE_NOT_FOUND = 334561;
protected static $persistentBuffer = array();
/**
* Binary that returns info about movie file
*
* @var string
*/
protected $binary;
/**
* Movie File path
*
* @var string
*/
protected $movieFile;
/**
* Persistent functionality on/off
*
* @var boolean
*/
protected $persistent;
/**
* Base constructor for every provider
*
* @param string $binary Binary that returns info about movie file
* @param boolean $persistent Persistent functionality on/off
*/
public function __construct($binary, $persistent)
{
$this->binary = $binary;
$this->persistent = $persistent;
}
/**
* Setting movie file path
*
* @param string $movieFile
*/
public function setMovieFile($movieFile)
{
$this->movieFile = $movieFile;
}
public function __serialize()
{
return [
$this->binary,
$this->movieFile,
$this->persistent
];
}
public function __unserialize($serialized)
{
list(
$this->binary,
$this->movieFile,
$this->persistent
) = $serialized;
}
}

View file

@ -0,0 +1,59 @@
<?php
namespace Char0n\FFMpegPHP\OutputProviders;
/**
* FFmpegOutputProvider ffmpeg provider implementation.
*/
class FFMpegProvider extends AbstractProvider
{
protected static $EX_CODE_NO_FFMPEG = 334560;
/**
* Constructor
*
* @param string $ffmpegBinary Path to ffmpeg executable.
* @param boolean $persistent Persistent functionality on/off.
*/
public function __construct($ffmpegBinary = 'ffmpeg', $persistent = false)
{
parent::__construct($ffmpegBinary, $persistent);
}
/**
* Getting parsable output from ffmpeg binary.
*
* @return string
*/
public function getOutput()
{
// Persistent opening
if (true === $this->persistent
&& array_key_exists(get_class($this).$this->binary.$this->movieFile, self::$persistentBuffer)
) {
return self::$persistentBuffer[get_class($this).$this->binary.$this->movieFile];
}
// File doesn't exist
if (@file_get_contents($this->movieFile, false, null, 0, 0) === false) {
throw new \UnexpectedValueException('Movie file not found', self::$EX_CODE_FILE_NOT_FOUND);
}
// Get information about file from ffmpeg
$output = [];
exec($this->binary.' -i '.escapeshellarg($this->movieFile).' 2>&1', $output, $retVar);
$output = implode(PHP_EOL, $output);
// ffmpeg installed
if (!preg_match('/FFmpeg version/i', $output)) {
throw new \RuntimeException('FFmpeg is not installed on host server', self::$EX_CODE_NO_FFMPEG);
}
// Storing persistent opening
if (true === $this->persistent) {
self::$persistentBuffer[get_class($this).$this->binary.$this->movieFile] = $output;
}
return $output;
}
}

View file

@ -0,0 +1,59 @@
<?php
namespace Char0n\FFMpegPHP\OutputProviders;
/**
* FFProbeProvider ffprobe provider implementation.
*/
class FFProbeProvider extends AbstractProvider
{
protected static $EX_CODE_NO_FFPROBE = 334563;
/**
* Constructor
*
* @param string $ffprobeBinary path to ffprobe executable.
* @param boolean $persistent persistent functionality on/off.
*/
public function __construct($ffprobeBinary = 'ffprobe', $persistent = false)
{
parent::__construct($ffprobeBinary, $persistent);
}
/**
* Getting parsable output from ffprobe binary.
*
* @return string
*/
public function getOutput()
{
// Persistent opening
if (true === $this->persistent
&& array_key_exists(get_class($this).$this->binary.$this->movieFile, self::$persistentBuffer)
) {
return self::$persistentBuffer[get_class($this).$this->binary.$this->movieFile];
}
// File doesn't exist
if (@file_get_contents($this->movieFile, false, null, 0, 0) === false) {
throw new \UnexpectedValueException('Movie file not found', self::$EX_CODE_FILE_NOT_FOUND);
}
// Get information about file from ffprobe
$output = [];
exec($this->binary.' '.escapeshellarg($this->movieFile).' 2>&1', $output, $retVar);
$output = implode(PHP_EOL, $output);
// ffprobe installed
if (!preg_match('/FFprobe version/i', $output)) {
throw new \RuntimeException('FFprobe is not installed on host server', self::$EX_CODE_NO_FFPROBE);
}
// Storing persistent opening
if (true === $this->persistent) {
self::$persistentBuffer[get_class($this).$this->binary.$this->movieFile] = $output;
}
return $output;
}
}

View file

@ -0,0 +1,23 @@
<?php
namespace Char0n\FFMpegPHP\OutputProviders;
/**
* OutputProvider interface of all output providers.
*/
interface OutputProvider
{
/**
* Setting movie file path.
*
* @param string $movieFile
*/
public function setMovieFile($movieFile);
/**
* Getting parsable output.
*
* @return string
*/
public function getOutput();
}

View file

@ -0,0 +1,57 @@
<?php
namespace Char0n\FFMpegPHP\OutputProviders;
/**
* StringOutputProvider ffmpeg provider implementation.
*/
class StringProvider extends AbstractProvider
{
protected $output;
/**
* This class is handy for testing purposes.
*
* @param string $ffmpegBinary Path to ffmpeg executable.
* @param boolean $persistent Persistent functionality on/off.
*/
public function __construct($ffmpegBinary = 'ffmpeg', $persistent = false)
{
$this->output = '';
parent::__construct($ffmpegBinary, $persistent);
}
/**
* Getting parsable output from ffmpeg binary.
*
* @return string
*/
public function getOutput()
{
// Persistent opening
$bufferKey = get_class($this).$this->binary.$this->movieFile;
if (true === $this->persistent
&& array_key_exists($bufferKey, self::$persistentBuffer)
) {
return self::$persistentBuffer[$bufferKey];
}
return $this->output;
}
/**
* Setting parsable output.
*
* @param string $output
*/
public function setOutput($output)
{
$this->output = $output;
// Storing persistent opening
if (true === $this->persistent) {
self::$persistentBuffer[get_class($this).$this->binary.$this->movieFile] = $output;
}
}
}

View file

@ -0,0 +1,3 @@
ul .image_picker_selector img {
height: 200px;
}

View file

@ -0,0 +1,36 @@
/* line 6, source/sass/image-picker.scss */
ul.thumbnails.image_picker_selector {
overflow: auto;
list-style-image: none;
list-style-position: outside;
list-style-type: none;
padding: 0px;
margin: 0px; }
/* line 15, source/sass/image-picker.scss */
ul.thumbnails.image_picker_selector ul {
overflow: auto;
list-style-image: none;
list-style-position: outside;
list-style-type: none;
padding: 0px;
margin: 0px; }
/* line 25, source/sass/image-picker.scss */
ul.thumbnails.image_picker_selector li.group_title {
float: none; }
/* line 30, source/sass/image-picker.scss */
ul.thumbnails.image_picker_selector li {
margin: 0px 12px 12px 0px;
float: left; }
/* line 35, source/sass/image-picker.scss */
ul.thumbnails.image_picker_selector li .thumbnail {
padding: 6px;
border: 1px solid #DDD;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none; }
/* line 42, source/sass/image-picker.scss */
ul.thumbnails.image_picker_selector li .thumbnail img {
-webkit-user-drag: none; }
/* line 48, source/sass/image-picker.scss */
ul.thumbnails.image_picker_selector li .thumbnail.selected {
background: #08C; }

View file

@ -0,0 +1,350 @@
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// Generated by CoffeeScript 2.0.1
(function () {
// Image Picker source
// by Rodrigo Vera
var ImagePicker,
ImagePickerOption,
both_array_are_equal,
sanitized_options,
indexOf = [].indexOf;
jQuery.fn.extend({
imagepicker: function imagepicker() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return this.each(function () {
var select;
select = jQuery(this);
if (select.data("picker")) {
select.data("picker").destroy();
}
select.data("picker", new ImagePicker(this, sanitized_options(opts)));
if (opts.initialized != null) {
return opts.initialized.call(select.data("picker"));
}
});
}
});
sanitized_options = function sanitized_options(opts) {
var default_options;
default_options = {
hide_select: true,
show_label: false,
initialized: void 0,
changed: void 0,
clicked: void 0,
selected: void 0,
limit: void 0,
limit_reached: void 0,
font_awesome: false
};
return jQuery.extend(default_options, opts);
};
both_array_are_equal = function both_array_are_equal(a, b) {
var i, j, len, x;
if (!a || !b || a.length !== b.length) {
return false;
}
a = a.slice(0);
b = b.slice(0);
a.sort();
b.sort();
for (i = j = 0, len = a.length; j < len; i = ++j) {
x = a[i];
if (b[i] !== x) {
return false;
}
}
return true;
};
ImagePicker = function () {
function ImagePicker(select_element) {
var opts1 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, ImagePicker);
this.sync_picker_with_select = this.sync_picker_with_select.bind(this);
this.opts = opts1;
this.select = jQuery(select_element);
this.multiple = this.select.attr("multiple") === "multiple";
if (this.select.data("limit") != null) {
this.opts.limit = parseInt(this.select.data("limit"));
}
this.build_and_append_picker();
}
_createClass(ImagePicker, [{
key: "destroy",
value: function destroy() {
var j, len, option, ref;
ref = this.picker_options;
for (j = 0, len = ref.length; j < len; j++) {
option = ref[j];
option.destroy();
}
this.picker.remove();
this.select.off("change", this.sync_picker_with_select);
this.select.removeData("picker");
return this.select.show();
}
}, {
key: "build_and_append_picker",
value: function build_and_append_picker() {
if (this.opts.hide_select) {
this.select.hide();
}
this.select.on("change", this.sync_picker_with_select);
if (this.picker != null) {
this.picker.remove();
}
this.create_picker();
this.select.after(this.picker);
return this.sync_picker_with_select();
}
}, {
key: "sync_picker_with_select",
value: function sync_picker_with_select() {
var j, len, option, ref, results;
ref = this.picker_options;
results = [];
for (j = 0, len = ref.length; j < len; j++) {
option = ref[j];
if (option.is_selected()) {
results.push(option.mark_as_selected());
} else {
results.push(option.unmark_as_selected());
}
}
return results;
}
}, {
key: "create_picker",
value: function create_picker() {
this.picker = jQuery("<ul class='thumbnails image_picker_selector'></ul>");
this.picker_options = [];
this.recursively_parse_option_groups(this.select, this.picker);
return this.picker;
}
}, {
key: "recursively_parse_option_groups",
value: function recursively_parse_option_groups(scoped_dom, target_container) {
var container, j, k, len, len1, option, option_group, ref, ref1, results;
ref = scoped_dom.children("optgroup");
for (j = 0, len = ref.length; j < len; j++) {
option_group = ref[j];
option_group = jQuery(option_group);
container = jQuery("<ul></ul>");
container.append(jQuery("<li class='group_title'>" + option_group.attr("label") + "</li>"));
target_container.append(jQuery("<li class='group'>").append(container));
this.recursively_parse_option_groups(option_group, container);
}
ref1 = function () {
var l, len1, ref1, results1;
ref1 = scoped_dom.children("option");
results1 = [];
for (l = 0, len1 = ref1.length; l < len1; l++) {
option = ref1[l];
results1.push(new ImagePickerOption(option, this, this.opts));
}
return results1;
}.call(this);
results = [];
for (k = 0, len1 = ref1.length; k < len1; k++) {
option = ref1[k];
this.picker_options.push(option);
if (!option.has_image()) {
continue;
}
results.push(target_container.append(option.node));
}
return results;
}
}, {
key: "has_implicit_blanks",
value: function has_implicit_blanks() {
var option;
return function () {
var j, len, ref, results;
ref = this.picker_options;
results = [];
for (j = 0, len = ref.length; j < len; j++) {
option = ref[j];
if (option.is_blank() && !option.has_image()) {
results.push(option);
}
}
return results;
}.call(this).length > 0;
}
}, {
key: "selected_values",
value: function selected_values() {
if (this.multiple) {
return this.select.val() || [];
} else {
return [this.select.val()];
}
}
}, {
key: "toggle",
value: function toggle(imagepicker_option, original_event) {
var new_values, old_values, selected_value;
old_values = this.selected_values();
selected_value = imagepicker_option.value().toString();
if (this.multiple) {
if (indexOf.call(this.selected_values(), selected_value) >= 0) {
new_values = this.selected_values();
new_values.splice(jQuery.inArray(selected_value, old_values), 1);
this.select.val([]);
this.select.val(new_values);
} else {
if (this.opts.limit != null && this.selected_values().length >= this.opts.limit) {
if (this.opts.limit_reached != null) {
this.opts.limit_reached.call(this.select);
}
} else {
this.select.val(this.selected_values().concat(selected_value));
}
}
} else {
if (this.has_implicit_blanks() && imagepicker_option.is_selected()) {
this.select.val("");
} else {
this.select.val(selected_value);
}
}
if (!both_array_are_equal(old_values, this.selected_values())) {
this.select.change();
if (this.opts.changed != null) {
return this.opts.changed.call(this.select, old_values, this.selected_values(), original_event);
}
}
}
}]);
return ImagePicker;
}();
ImagePickerOption = function () {
function ImagePickerOption(option_element, picker) {
var opts1 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
_classCallCheck(this, ImagePickerOption);
this.clicked = this.clicked.bind(this);
this.picker = picker;
this.opts = opts1;
this.option = jQuery(option_element);
this.create_node();
}
_createClass(ImagePickerOption, [{
key: "destroy",
value: function destroy() {
return this.node.find(".thumbnail").off("click", this.clicked);
}
}, {
key: "has_image",
value: function has_image() {
return this.option.data("img-src") != null;
}
}, {
key: "is_blank",
value: function is_blank() {
return !(this.value() != null && this.value() !== "");
}
}, {
key: "is_selected",
value: function is_selected() {
var select_value;
select_value = this.picker.select.val();
if (this.picker.multiple) {
return jQuery.inArray(this.value(), select_value) >= 0;
} else {
return this.value() === select_value;
}
}
}, {
key: "mark_as_selected",
value: function mark_as_selected() {
return this.node.find(".thumbnail").addClass("selected");
}
}, {
key: "unmark_as_selected",
value: function unmark_as_selected() {
return this.node.find(".thumbnail").removeClass("selected");
}
}, {
key: "value",
value: function value() {
return this.option.val();
}
}, {
key: "label",
value: function label() {
if (this.option.data("img-label")) {
return this.option.data("img-label");
} else {
return this.option.text();
}
}
}, {
key: "clicked",
value: function clicked(event) {
this.picker.toggle(this, event);
if (this.opts.clicked != null) {
this.opts.clicked.call(this.picker.select, this, event);
}
if (this.opts.selected != null && this.is_selected()) {
return this.opts.selected.call(this.picker.select, this, event);
}
}
}, {
key: "create_node",
value: function create_node() {
var image, imgAlt, imgClass, thumbnail;
this.node = jQuery("<li/>");
// font-awesome support
if (this.option.data("font_awesome")) {
image = jQuery("<i>");
image.attr("class", "fa-fw " + this.option.data("img-src"));
} else {
image = jQuery("<img class='image_picker_image'/>");
image.attr("src", this.option.data("img-src"));
}
thumbnail = jQuery("<div class='thumbnail'>");
// Add custom class
imgClass = this.option.data("img-class");
if (imgClass) {
this.node.addClass(imgClass);
image.addClass(imgClass);
thumbnail.addClass(imgClass);
}
// Add image alt
imgAlt = this.option.data("img-alt");
if (imgAlt) {
image.attr('alt', imgAlt);
}
thumbnail.on("click", this.clicked);
thumbnail.append(image);
if (this.opts.show_label) {
thumbnail.append(jQuery("<p/>").html(this.label()));
}
this.node.append(thumbnail);
return this.node;
}
}]);
return ImagePickerOption;
}();
}).call(undefined);

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,331 @@
<?php
class MarkupGoogleRecaptcha extends WireData implements Module, ConfigurableModule {
static function getModuleInfo() {
return [
'title' => 'Markup Google reCAPTCHA',
'summary' => 'Google reCAPTCHA for ProcessWire',
'version' => '2.0.0',
'author' => 'flydev',
'href' => 'https://processwire.com/talk/topic/13738-markup-google-recaptcha/',
'icon' => 'puzzle-piece',
'autoload'=> false,
'singular'=> false
];
}
const SITE_RECAPTCHA_API_URL = "https://www.google.com/recaptcha/api.js";
const SITE_VERIFY_URL = "https://www.google.com/recaptcha/api/siteverify";
protected static $defaultSettings = [
'site_key' => '',
'secret_key' => '',
'data_theme' => '0',
'data_type' => '0',
'data_size' => '0',
'data_index' => '0',
'data_recaptcha_type' => 'recaptchav2'
];
public function __construct()
{
$this->setArray(self::$defaultSettings);
}
public function render($form = null, $lang = "")
{
if(!$form instanceof InputfieldForm)
{
$out = $this->buildGoogleDiv($lang);
return $out;
}
else
{
$inputfield = $this->modules->get("InputfieldMarkup");
$inputfield->value = $this->buildGoogleDiv($lang);
return $form->add($inputfield);
}
}
protected function buildGoogleDiv($lang = "")
{
$reCaptchaClass = "g-recaptcha";
$reCaptchaID = $reCaptchaClass . "-" . uniqid();
$attributes = array(
'id' => $reCaptchaID,
'class' => $reCaptchaClass,
'data-id' => $reCaptchaID,
'data-hl' => $lang,
'data-sitekey' => $this->site_key,
'data-theme' => ($this->data_theme) ? 'dark' : 'light',
'data-type' => ($this->data_type) ? 'audio' : 'image',
'data-size' => ($this->data_size) ? 'compact' : 'normal',
'data-index' => ($this->data_index) ? $this->data_index : '0',
);
if($this->data_recaptcha_type == 'invisible') {
$attributes['data-size'] = 'invisible';
$attributes['data-badge'] = ($this->data_badge) ? $this->data_badge : 'bottomright';
}
$div = '<div '.join(' ', array_map(function($key) use ($attributes)
{
if(is_bool($attributes[$key]))
return $attributes[$key] ? $key : '';
return $key.'="'.$attributes[$key].'"';
}, array_keys($attributes))).' ></div>';
/*if(isset($this->data_recaptcha_type) && $this->data_recaptcha_type == 'invisible') {
$div .= "
<script>
var renderInvisibleCallback = function() {
for (var i = 0; i < document.forms.length; ++i) {
var form = document.forms[i];
var div = form.querySelector('.g-recaptcha');
if (null === div){
continue;
}
(function(f){
var divId = grecaptcha.render(div,{
'sitekey': '" . $attributes['data-sitekey'] . "',
'size': '" . $attributes['data-size'] . "',
'badge' : '" . $attributes['data-badge'] . "',
'callback' : function (recaptchaToken) {
HTMLFormElement.prototype.submit.call(f);
}
});
f.onsubmit = function (e){
e.preventDefault();
grecaptcha.execute(divId);
};
})(form);
}
};
</script>";
}*/
return $div;
}
public function getScript()
{
$params = '';
if(isset($this->data_recaptcha_type) && $this->data_recaptcha_type == 'invisible') {
$params = '?onload=renderInvisibleCallback&render=explicit';
$return = "
<script>
var renderInvisibleCallback = function() {
for (var i = 0; i < document.forms.length; ++i) {
var form = document.forms[i];
var div = form.querySelector('.g-recaptcha');
if (null === div){
continue;
}
(function(f){
var divId = grecaptcha.render(div, {
'sitekey': div.getAttribute('data-sitekey'),
'size': div.getAttribute('data-size'),
'badge' : div.getAttribute('data-badge'),
'callback' : function (recaptchaToken) {
HTMLFormElement.prototype.submit.call(f);
}
});
f.onsubmit = function (e){
e.preventDefault();
grecaptcha.execute(divId);
};
})(form);
}
};
</script>";
$return .= "<script src='".self::SITE_RECAPTCHA_API_URL."$params' async defer></script>";
}
elseif(isset($this->data_recaptcha_type) && $this->data_recaptcha_type == 'recaptchav2') {
$return = "<script src='".self::SITE_RECAPTCHA_API_URL."' async defer></script>";
}
return $return;
}
public function getScriptMulti() {
$return = "<script type='text/javascript'>
var onloadReCaptchaCallback = function(){
jQuery('.g-recaptcha').each(function() {
var _this = jQuery(this);
var recaptchaID = _this.data('id'),
hl = _this.data('hl'),
sitekey = _this.data('sitekey'),
theme = _this.data('theme'),
type = _this.data('type'),
size = _this.data('size'),
index = _this.data('index');
if(recaptchaID !== undefined) {
var recaptchaWidget = grecaptcha.render(recaptchaID, {
'hl' : hl,
'sitekey' : sitekey,
'theme' : theme,
'type' : type,
'size' : size,
'index' : index
});
grecaptcha.getResponse(recaptchaWidget);
// grecaptcha.reset(recaptchaWidget);
}
});
};
</script>";
$return .= "<script src='".self::SITE_RECAPTCHA_API_URL."?onload=onloadReCaptchaCallback&render=explicit' async defer></script>";
return $return;
}
public function verifyResponse()
{
if (!wire('input')->post['g-recaptcha-response'])
return false;
$data = [
'remoteip' => $_SERVER["REMOTE_ADDR"],
'secret' => $this->secret_key,
'response' => wire('input')->post['g-recaptcha-response']
];
$http = new WireHttp();
$query = http_build_query($data);
$response = $http->get(self::SITE_VERIFY_URL."?{$query}");
$response = json_decode($response, true);
return ($response['success'] === true) ? true : false;
}
public static function getModuleConfigInputfields(array $data)
{
$wrap = new InputfieldWrapper();
/*
* api settings
*/
$form = wire('modules')->get('InputfieldFieldset');
$form->label = __('Google reCAPTCHA API Settings');
$form->notes = __('You can obtain the above information by creating an API key at [http://www.google.com/recaptcha/admin](http://www.google.com/recaptcha/admin)');
$form->collapsed = Inputfield::collapsedYes;
$inputfields = [
'site_key' => __('Site key'),
'secret_key' => __('Secret key')
];
foreach($inputfields as $name => $label) {
$f = wire('modules')->get('InputfieldText');
$f->attr('name', $name);
$f->label = $label;
$f->required = true;
$f->columnWidth = 50;
if(isset($data[$name])) $f->attr('value', $data[$name]);
$form->add($f);
}
$wrap->add($form);
/*
* mode
*/
$form = wire('modules')->get('InputfieldFieldset');
$form->label = __('Widget Mode');
$f = wire('modules')->get("InputfieldRadios");
$options = array('recaptchav2' => 'reCaptcha V2', 'invisible' => 'Invisible');
$f->name = 'data_recaptcha_type';
$f->label = __("Type of reCaptcha");
$f->description = __("Choose the type of reCaptcha.");
$f->addOptions($options);
isset($data['data_recaptcha_type']) ? $f->attr('value', $data['data_recaptcha_type']) : $f->attr('value', 'recaptchav2');
$f->columnWidth = 100;
$form->add($f);
$wrap->add($form);
/*
* recapatcha invisible settings
*/
$form = wire('modules')->get('InputfieldFieldset');
$form->label = __('Invisible Widget Settings');
$form->showIf = "data_recaptcha_type=invisible";
$f = wire('modules')->get("InputfieldSelect");
$options = array('bottomright' => 'bottomright', 'bottomleft' => 'bottomleft' , 'inline' => 'inline');
$f->name = 'data_badge';
$f->label = __("Badge");
$f->description = __("Reposition the reCAPTCHA badge. 'inline' allows you to control the CSS.");
$f->addOptions($options);
if(isset($data['data_badge'])) $f->attr('value', $data['data_badge']);
$f->columnWidth = 100;
$form->add($f);
$wrap->add($form);
/*
* recapatcha v2 settings
*/
$form = wire('modules')->get('InputfieldFieldset');
$form->label = __('reCapatcha V2 Widget Settings');
$form->showIf = "data_recaptcha_type=recaptchav2";
$inputfields = [
'data_theme' => ['label' => __("Use dark theme"), 'description' => __('The color theme of the widget. Default: light') ],
'data_size' => ['label' => __('Use compact widget'), 'description' => __('The size of the widget. Default: normal') ]
];
foreach($inputfields as $name => $value) {
$f = wire('modules')->get("InputfieldCheckbox");
$f->name = $name;
$f->label = $value['label'];
$f->description = $value['description'];
$f->value = 0;
$f->attr('checked', empty($data[$name]) ? '' : 'checked');
$f->columnWidth = 50;
$form->add($f);
}
$wrap->add($form);
/*
* global settings
*/
$form = wire('modules')->get('InputfieldFieldset');
$form->label = __('Global Widget Settings');
$inputfields = [
'data_type' => ['label' => __('Use audio type'), 'description' => __('The type of CAPTCHA to serve. Default: image') ],
'data_index' => ['name' => 'data_index', 'label' => __('Tabindex '), 'description' => __('The tabindex of the widget and challenge. Default: 0') ]
];
$f = wire('modules')->get('InputfieldText');
$f->name = $inputfields['data_index']['name'];
$f->label = $inputfields['data_index']['label'];
$f->description = $inputfields['data_index']['description'];
$f->value = (isset($data['data_index'])) ? $data['data_index'] : '0';
$f->columnWidth = 50;
$form->add($f);
$f = wire('modules')->get("InputfieldCheckbox");
$f->name = 'data_type';
$f->label = $inputfields['data_type']['label'];
$f->description = $inputfields['data_type']['description'];
$f->attr('checked', empty($data['data_type']) ? '' : 'checked');
$f->columnWidth = 50;
$form->add($f);
$wrap->add($form);
return $wrap;
}
}

View file

@ -0,0 +1,84 @@
# MarkupGoogleRecaptcha
Google reCAPTCHA for ProcessWire.
This module simply adds reCAPTCHA to your form.
# How To Install
1. Download the [zip file](https://github.com/flydev-fr/MarkupGoogleRecaptcha/archive/master.zip) at Github or clone directly the repo into your `site/modules`
2. If you dowloaded the `zip file`, extract it in your `sites/modules` directory
3. Goto the modules admin page, click on refresh and install it.
# API
You must create an API key prior to use this module. Goto [https://www.google.com/recaptcha/admin](https://www.google.com/recaptcha/admin) to create your own. Next, add the API keys information to the module's settings.
![module settings](http://i.imgur.com/wVeEvTn.png)
# Usage
1. Call the module : `$captcha = $modules->get("MarkupGoogleRecaptcha");`
2. Call `$captcha->getScript();` somewhere to get the javascript used by reCAPTCHA
3. Render reCAPTCHA in a standard HTML `<form></form>` by calling `$captcha->render()`
or
Render reCAPTCHA in an `InputfieldForm` by passing as argument your form to the render function: `$captcha->render($form)`
4. Call `verifyResponse()` to get the result. It return `TRUE` if the challenge was successfull.
# Example
### We make a form using ProcessWire's API and inject the reCaptcha :
```php
$out = '';
$captcha = $modules->get("MarkupGoogleRecaptcha");
// if submitted, check response
if ($captcha->verifyResponse() === true)
{
$out .= "Hi " . $input->post["name"] . ", thanks for submitting the form!";
}
else
{
$form = $modules->get("InputfieldForm");
$form->action = $page->url;
$form->method = "post";
$form->attr("id+name", "form");
$field = $this->modules->get('InputfieldText');
$field->name = "name";
$field->placeholder = "name";
$form->add($field);
// CAPTCHA - our form as argument, the function will add an InputfieldMarkup to our form
$captcha->render($form);
// add a submit button
$submit = $this->modules->get("InputfieldSubmit");
$submit->name = "submit";
$submit->value = 'Submit';
$form->add($submit);
$out .= $form->render();
$out .= $captcha->getScript();
}
echo $out;
```
### A plain HTML form :
```php
$captcha = $modules->get("MarkupGoogleRecaptcha");
// if submitted check response
if ($captcha->verifyResponse() === true)
{
$out .= "Hi " . $input->post["name"] . ", thanks for submitting the form!";
}
else
{
$out .= "<form method='post' action='{$page->url}'>\n"
. "\t<input type='text' name='name'>\n"
. $captcha->render() // render reCaptcha
. "\t<input type='submit'>\n"
. "</form>\n";
$out .= $captcha->getScript();
}
echo $out;
```

View file

@ -0,0 +1,13 @@
{
"presets": ["@babel/preset-env"],
"env": {
"production": {
"presets": [
"@babel/preset-env",
{
"useBuiltIns": "usage"
},
"minify"]
}
}
}

View file

@ -0,0 +1,2 @@
$ cat .gitattributes
*.module linguist-language=PHP

View file

@ -0,0 +1,31 @@
name: Build and conditionally comit changes
on:
push:
branches:
- master
jobs:
install-build-commit:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout code
uses: actions/checkout@v4.1.1
- name: Set up Node.js
uses: actions/setup-node@v4.0.2
with:
node-version: "18"
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: commit changes
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "CI build run [skip ci]"

4
site/modules/PrivacyWire/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
node_modules/
vendor/
.idea/
js/*.css

View file

@ -0,0 +1,233 @@
# Changelog of PrivacyWire
## 1.1.6
- add default type `text/javascript` if no `data-type` is defined. https://github.com/webworkerJoshua/privacywire/issues/33
## 1.1.5
- Trigger CustomEvents when banner and options are opened/closed by @teppokoivula in https://github.com/webworkerJoshua/privacywire/pull/32
- Updated dependencies to use current rollup version and require at least node v18 for development
## 1.1.4 & 1.1.3
- Made the textareas type flexible by @the-ge in https://github.com/webworkerJoshua/privacywire/pull/27
- Context free formatter by @MarcoKalin in https://github.com/webworkerJoshua/privacywire/pull/28
- Support regular YouTube URL variation with www prefix by @teppokoivula in https://github.com/webworkerJoshua/privacywire/pull/30
- bumped version number again, as there was a mismatch with the git tag
## 1.1.2
- Added: Config option to activate / deactivate PrivacyWire
## 1.1.1
- Merged PR #19 and #22
- Changed: Switched `innerText` to `textContent` for accuracy in `updateAllowedElementScript()`
- Changed: form layout and fields definitions syntax
- Updated dependencies
## 1.1.0
- Added: Config option and feature to detect bots (per User-agent) and hide the banner to them
## 1.0.11
- Fixed: Bug, when multiple page()->render() methods are called. Now PrivacyWire only loads on the main call of page()->render()
## 1.0.10
- Added: Config option to replace the original consent blueprint template (located in site/modules/PrivacyWire/PrivacyWireConsentBlueprint.php) with an alternative consent blueprint
## 1.0.9
- Changed: Reduced priority of Page::render hook to allow easier override of settings
## 1.0.8
- Added: Add class to body "has-privacywire-window-opened" while PrivacyWire windows are visible
## 1.0.7
- Added: Function to re-handle external button trigger via `window.PrivacyWire.reHandleExternalButtons()`
## 1.0.6
- Fixed: Legacy IE11 Bug with Array.from Polyfill (Also for not-inline mode)
## 1.0.5
- Fixed: Legacy Support for IE11 with Array.from Polyfill
## 1.0.4
- Fixed: removed console.log() debugger from DNT-method
## 1.0.3
- Changed: Order of Buttons in Options window
## 1.0.2
- Changed: Removed ProCache Output method as there is no real improvement over enabling JS minification in the ProCache settings.
- Changed: Load modern ES6 version of JavaScript via `<script type="module" ...>` and legacy version of Javascript via `<script nomodule ...>` to support both modern and legacy browsers with the best possible result.
- Fixed: The Imprint and Privacy links markup is now equal between banner and option view.
- Fixed: After upgrading from 0.4.5 (and below) to 1.0 (and up) require new consent from the user, as syntax has changed.
## 1.0.1b (beta)
- Changed: Return value of PrivacyWire methods for better extensibility
- Added: method `getPrivacyWireCore` which returns the path and url to the PrivacyWire Core JS file
- Added: more comments to explain how you can bundle the PrivacyWire Core JS with your other scripts
## 1.0.0a (alpha)
**Major Refactoring**. Rewritten both the JS and PHP parts.
- Added: Config option for output mode (regular script tag, ProCache script tag, inline script)
- Added: Config option to choose elements which require consent by class `require-consent` instead of data-attribute (better performance). **WARNING**: Enabling this needs adding the css class `require-consent` to every element (also script tags!) you want to be processed by PrivacyWire
- Added: Config option to choose ES6 JavaScript instead of a _Babel_ transpiled version (Faster and smaller but no Internet Explorer support)
- Changed: Module methods refactored. Hookable methods changed. Take a look into [PrivacyWire.module](PrivacyWire.module) to see the difference
- Added: Possibility to manually refresh detection of elements (e.g. after loading content via AJAX). Just call `window.PrivacyWire.refresh();` after adding new content to the DOM which could require consent
- Changed: Split markup from Banner and Consent Blueprint in two different files for better separation of concerns and easier hook management.
## 0.4.5
- Added: JS function to manually trigger the update of DOM elements: `window.updatePrivacyWireElements`
## 0.4.4
- Added methods: getInlineJavaScriptTag & getPathToCssFile
- Added: CSS file instead of SCSS for improved manual rendering options
## 0.4.3
- Fixed: Textformatter support for TextformatterVideoEmbed now also works for YouTube no-cookie mode
## 0.4.2
- Fixed: Bug during cloning allowed script elements after giving consent
## 0.4.1
- Changed: Optimized "priw_updateAllowedElement"
## 0.4.0
- Fixed: Bug during cloning allowed elements after giving consent
## 0.3.9
- Added: Textformatter support for TextformatterVideoEmbed (Thank you @teppokoivula !)
## 0.3.8
- Fixed: Bug with ask consent window when cookies get accepted via the main banner
## 0.3.7
- Added: Config options to show alternative headline and text elements within the options banner
## 0.3.6
- Added: Config option to prevent automatic rendering.
- Added: New methods renderHeadContent() and renderBodyContent().
## 0.3.4
- Fixed: sanitize alternative banner template path to ignore leading slash
## 0.3.3
- Added: Config option to replace the original banner template (located in site/modules/PrivacyWire/PrivacyWireBanner.php) with an alternative banner template
- Added: hookable method to get JS file
- Added: hookable method to get inline JS
- Added: hookable method to get (alternative) banner template file
- Changed: Optimized CSS (even smaller - 458 bytes instead of 554 bytes)
- Changed: Re-arranged the config options to provide better structure
## 0.3.2
- Fixed: Bug with "Accept all" Button to load elements
- Added: Config option to choose the banner header tag between `<header>` and `<div>`
## 0.3.1
- Added: Config option within Textformatter to choose open and close tag
## 0.3.0
- Added Feature: When the user hasn't given consent to a specific cookie category, show an alternative element with asking for consent. To enable this feature, add following data-attribute to the element ` data-ask-consent="1"`. In the module configuration you can choose, what text should be in that window. Example: ` <iframe src="" data-src="https://www.example.com/" data-category="marketing" data-ask-consent="1" frameborder="0" height="400" width="400"></iframe>`
## 0.2.7
- Fixed: Updates more attributes of elements (srcset, height, width) - important for responsive images or iFrames
## 0.2.6
- Added: Config option to show an "Accept All" instead of "Toggle" Button within the "Choose Cookies" window.
## 0.2.5
- Fixed: Changing version number now works as expected
## 0.2.4
- Fixed: Typo in consent of external_media
## 0.2.3
- Added: Config option for message timeout
## 0.2.2
- Added: Config option to output unstyled (no css) PrivacyWire
## 0.2.1
- Added: New cookie category "functional"
## 0.2.0
- Changed: Major rewrite of PrivacyWire.js -> now around half the size (main reason was babel with usage of js classes (ES6))
- Added: New possibility to add a custom js function name which is triggered after saving options
## 0.1.2
- Added: Config option for using ProCache minification or not
## 0.1.1
- Fixed: Error during uninstall
## 0.1.0
- Changed: Script detection now uses the data-category attribute instead of type="optin" (W3C validation)
## 0.0.7
- Fixed: Multi-lang privacy & imprint link
## 0.0.6
- Fixed: CSS-Debugging for hiding unused buttons, added ProCache support for the JavaScript tag
## 0.0.5
- Added: Multi-language support included completely (also in TextFormatter).
- Added: Possibility to async load other assets (e.g. `<img type="optin" data-category="marketing" data-src="https://via.placeholder.com/300x300">`)
## 0.0.4
- Added: Possibility to add an imprint link to the banner
## 0.0.3
- Added: Multi-language support for module config (still in development)
## 0.0.2
- First release
## 0.0.1
- Early development state (ALPHA)

View file

@ -0,0 +1,5 @@
# Future Features within PrivacyWire
## Detection of consent-required elements via css-class `require-consent` instead of `data-category="..."`
To allow a more flexible way to detect elements which require consent, the css class `require-consent` is necessary. With this enabled, PrivacyWire also detects dynamically added elements without re-initiating.
A little background: To receive a list of elements via data-attributes it is required to use `document.querySelectorAll('[data-category]')` which returns a static NodeList. When we use `document.getElementsByClassName("require-consent")` instead we have access to a **live** HTMLCollection.

View file

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

View file

@ -0,0 +1,204 @@
<?php namespace ProcessWire;
/**
* PrivacyWire
* This module adds management options for GDPR-relevant elements (loading maps, videos etc. only after accepting
* external media) and cookies.
*
* @author blaueQuelle
*
* ProcessWire 3.x
* Copyright (C) 2011 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://www.processwire.com
* http://www.ryancramer.com
*
*/
class PrivacyWire extends WireData implements Module, ConfigurableModule
{
var $modulePath;
var $moduleUrl;
var $headContent = "";
var $bodyContent = "";
var $lang;
public static function getModuleInfo()
{
return [
'title' => "PrivacyWire",
'summary' => "This module adds management options for GDPR-relevant elements (loading maps, videos etc. only after accepting external media) and cookies.",
'author' => "blaueQuelle",
'href' => "https://github.com/blaueQuelle/privacywire",
'version' => "1.1.6",
'autoload' => true,
'singular' => true,
'requires' => ["PHP>=7.2", "ProcessWire>=3.0.110"],
'installs' => ["TextformatterPrivacyWire"],
'icon' => 'eye-slash'
];
}
public function ready()
{
if (
$this->wire('page')->template == 'admin' || // exclude admin pages
$this->wire('page')->template == 'form-builder' || // exclude from form-builder iframe
! $this->is_active // exclude, if PrivacyWire is NOT active
) {
return;
}
// 1. - 5. within initiatePrivacyWire method
$this->wire('page')->addHookBefore('render', $this, 'initiatePrivacyWire');
// 6. Render everything!
/*
* Hint: If you want to render everything manually, make sure to insert the PrivacyWireConfig (step 2), PrivacyWireCore (step 3), Banner Markup (step 4) and if you want to display the ask-for-consent windows also the consent blueprint (step 5) somewhere in your template.
* The banner markup and consent window blueprint can be loaded anywhere, for example at the end of the body tag.
*/
if (!$this->render_manually) {
$this->wire('page')->addHookAfter('render', $this, 'render', ['priority' => 101]);
}
}
public function initiatePrivacyWire(HookEvent $event)
{
$this->modulePath = $this->wire('config')->paths->$this;
$this->moduleUrl = $this->wire('config')->urls->$this;
$this->lang = ($this->wire('languages') && !$this->wire('user')->language->isDefault()) ? '__' . $this->wire('user')->language->id : '';
// 1. Add some styling via inline CSS (if wanted, configured via backend)
if ($this->add_basic_css_styling) {
$this->headContent .= $this->renderPrivacyWireStyles();
}
// 2. Insert PrivacyWire Configuration Object as inline JS (hookable method if you want to override something)
$this->headContent .= $this->renderPrivacyWireConfigAsInlineJs();
// 3. Insert JS File (hookable method) - either modern ES6 version or legacy version with IE support.
// Output modes: a) regular script tag b) ProCache script tag c) inline script
$this->headContent .= $this->renderPrivacyWireCoreJs();
// 4. Insert PrivacyWire Banner Markup
$this->bodyContent .= $this->renderPrivacyWireBannerTemplate();
// 5. Insert PrivacyWire Blueprint for Consent Window Markup
$this->bodyContent .= $this->renderPrivacyWireConsentBlueprint();
// 6. (within ready method)
}
public function render(HookEvent $event)
{
$event->return = str_replace("</head>", "{$this->headContent}</head>", $event->return);
$event->return = str_replace("</body>", "{$this->bodyContent}</body>", $event->return);
}
public function ___renderPrivacyWireStyles()
{
$file = $this->getPrivacyWireStyles();
return "<style>" . file_get_contents($file->path) . "</style>";
}
public function ___renderPrivacyWireConfigAsInlineJs()
{
return "<script>var PrivacyWireSettings={$this->getPrivacyWireConfigObject()};</script>";
}
public function ___renderPrivacyWireCoreJs()
{
if ($this->output_mode === "inline") {
$output = "<script type='module'>" . file_get_contents($this->modulePath . "js/PrivacyWire.js") . "</script>";
$output .= "<script nomodule type='text/javascript'>" . file_get_contents($this->modulePath . "js/ie_polyfill.js") . "</script>";
$output .= "<script nomodule type='text/javascript'>" . file_get_contents($this->modulePath . "js/PrivacyWire_legacy.js") . "</script>";
return $output;
}
$output = "<script type='module' src='" . $this->moduleUrl . "js/PrivacyWire.js" . "'></script>";
$output .= "<script nomodule type='text/javascript' src='" . $this->moduleUrl . "js/ie_polyfill.js" . "'></script>";
$output .= "<script nomodule type='text/javascript' src='" . $this->moduleUrl . "js/PrivacyWire_legacy.js" . "'></script>";
return $output;
}
public function ___renderPrivacyWireBannerTemplate()
{
return $this->renderTemplate('PrivacyWireBanner.php', $this->alternate_banner_template);
}
public function ___renderPrivacyWireConsentBlueprint()
{
return $this->renderTemplate('PrivacyWireConsentBlueprint.php', $this->alternate_inline_consent_template);
}
protected function renderTemplate($filename, $alternatePath = '')
{
$filePath = $this->wire('config')->paths->$this . $filename;
$alternatePath = ltrim($alternatePath, '/');
if (
!empty($alternatePath) &&
file_exists($this->wire('config')->paths->root . $alternatePath)) {
$filePath = $this->wire('config')->paths->root . $alternatePath;
}
return wireRenderFile($filePath, ['module' => $this]);
}
/**
* Get the PrivacyWire stylesheet as Object with path and url
* @return \StdClass $file with $file->path and $file->url
*/
public function ___getPrivacyWireStyles(): \StdClass
{
$file = new \StdClass;
$file->name = "css/PrivacyWire.css";
$file->path = $this->modulePath . $file->name;
$file->url = $this->moduleUrl . $file->name;
return $file;
}
/**
* @param bool $legacy
* @return \StdClass $file with $file->path and $file->url
* @deprecated since version 1.0.2
* Get the PrivacyWire Core file as Object with path and url
*/
public function ___getPrivacyWireCore(bool $legacy = false): \StdClass
{
$file = new \StdClass;
$file->name = "js/PrivacyWire" . ($legacy ? '_legacy' : '') . ".js";
$file->path = $this->modulePath . $file->name;
$file->url = $this->moduleUrl . $file->name;
return $file;
}
/**
* Get the current PrivacyWire config options and output them as JSON Object
* @return string JSON Object of PrivacyWire config options
*/
public function ___getPrivacyWireConfigObject(): string
{
$privacyWireSettings = new \StdClass;
$privacyWireSettings->version = $this->version;
$privacyWireSettings->dnt = ($this->respectDNT) ? "1" : "0";
$privacyWireSettings->bots = ($this->checkForBots) ? "1" : "0";
$privacyWireSettings->customFunction = ($this->wire('sanitizer')->text($this->trigger_custom_js_function)) ?? "";
$privacyWireSettings->messageTimeout = ($this->messageTimeout && intval($this->messageTimeout) > 1) ? intval($this->messageTimeout) : 1500;
$privacyWireSettings->consentByClass = ($this->detect_consents_by_class) ? "1" : "0";
$privacyWireSettings->cookieGroups = [
'necessary' => $this->get("cookies_necessary_label{$this->lang}|cookies_necessary_label"),
'functional' => $this->get("cookies_functional_label{$this->lang}|cookies_functional_label"),
'statistics' => $this->get("cookies_statistics_label{$this->lang}|cookies_statistics_label"),
'marketing' => $this->get("cookies_marketing_label{$this->lang}|cookies_marketing_label"),
'external_media' => $this->get("cookies_external_media_label{$this->lang}|cookies_external_media_label"),
];
return json_encode($privacyWireSettings);
}
}

View file

@ -0,0 +1,111 @@
<?php namespace ProcessWire;
/**
* @var PrivacyWire $module Instance of the PrivacyWire
*/
$showAllButton = (in_array("all", $module->cookie_groups));
$showNecessaryButton = (in_array("necessary", $module->cookie_groups));
$showAllInsteadToggle = $module->content_banner_button_all_instead_toggle;
$showFunctionalButton = (in_array("functional", $module->cookie_groups));
$showStatisticsButton = (in_array("statistics", $module->cookie_groups));
$showMarketingButton = (in_array("marketing", $module->cookie_groups));
$showExternalMediaButton = (in_array("external_media", $module->cookie_groups));
$showChooseButton = (
$showFunctionalButton ||
$showStatisticsButton ||
$showMarketingButton ||
$showExternalMediaButton
);
// Detailed Text for options banner
if ($module->content_banner_details_show == true) {
$optionsTitle = $module->get("content_banner_details_title{$module->lang}|content_banner_details_title");
$optionsText = $module->get("content_banner_details_text{$module->lang}|content_banner_details_text");
} else {
$optionsTitle = $module->get("content_banner_title{$module->lang}|content_banner_title");
$optionsText = $module->get("content_banner_text{$module->lang}|content_banner_text");
}
$privacyPage = (!empty($module->get("content_banner_privacy_link{$module->lang}|content_banner_privacy_link"))) ? $module->get("content_banner_privacy_link{$module->lang}|content_banner_privacy_link") : null;
$imprintPage = (!empty($module->get("content_banner_imprint_link{$module->lang}|content_banner_imprint_link"))) ? $module->get("content_banner_imprint_link{$module->lang}|content_banner_imprint_link") : null;
?>
<div class="privacywire-wrapper" id="privacywire-wrapper">
<div class="privacywire-page-wrapper">
<div class="privacywire privacywire-banner">
<?php if (!empty($module->content_banner_title)) {
echo "<{$module->banner_header_tag} class='privacywire-header'>{$module->get("content_banner_title{$module->lang}|content_banner_title")}</{$module->banner_header_tag}>";
}?>
<div class="privacywire-body">
<div class="privacywire-text"><?php echo $module->get("content_banner_text{$module->lang}|content_banner_text"); ?></div>
<div class="privacywire-buttons">
<button class="allow-all" <?php echo (!$showAllButton) ? "hidden" : ""; ?>><?php echo $module->get("content_banner_button_allow_all{$module->lang}|content_banner_button_allow_all"); ?></button>
<button class="allow-necessary" <?php echo (!$showNecessaryButton) ? "hidden" : ""; ?>><?php echo $module->get("content_banner_button_allow_necessary{$module->lang}|content_banner_button_allow_necessary"); ?></button>
<button class="choose" <?php echo (!$showChooseButton) ? "hidden" : ""; ?>><?php echo $module->get("content_banner_button_choose{$module->lang}|content_banner_button_choose"); ?></button>
</div>
<?php if (!empty($privacyPage) || !empty($imprintPage)): ?>
<div class="privacywire-page-links">
<?php if (!empty($privacyPage)): ?>
<a class="privacywire-page-link" href="<?php echo $privacyPage; ?>"
title="<?php echo $module->get("content_banner_privacy_title{$module->lang}|content_banner_privacy_title"); ?>"><?php echo $module->get("content_banner_privacy_title{$module->lang}|content_banner_privacy_title"); ?></a>
<?php endif; ?>
<?php if (!empty($imprintPage)): ?>
<a class="privacywire-page-link" href="<?php echo $imprintPage; ?>"
title="<?php echo $module->get("content_banner_imprint_title{$module->lang}|content_banner_imprint_title"); ?>"><?php echo $module->get("content_banner_imprint_title{$module->lang}|content_banner_imprint_title"); ?></a>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
</div>
<div class="privacywire privacywire-options">
<?php if (!empty($optionsTitle)) {
echo "<{$module->banner_header_tag} class='privacywire-header'>{$optionsTitle}</{$module->banner_header_tag}>";
} ?>
<div class="privacywire-body">
<div class="privacywire-text"><?php echo $optionsText; ?></div>
<div class="privacywire-text">
<ul>
<li <?php echo (!$showNecessaryButton) ? "hidden" : ""; ?>>
<label for="necessary"><input class="required" type="checkbox" name="necessary" id="necessary" value="1" checked disabled><?php echo $module->get("cookies_necessary_label{$module->lang}|cookies_necessary_label"); ?></label>
</li>
<li <?php echo (!$showFunctionalButton) ? "hidden" : ""; ?>>
<label for="functional"><input class="optional" type="checkbox" name="functional" id="functional" value="0"><?php echo $module->get("cookies_functional_label{$module->lang}|cookies_functional_label"); ?></label>
</li>
<li <?php echo (!$showStatisticsButton) ? "hidden" : ""; ?>>
<label for="statistics"><input class="optional" type="checkbox" name="statistics" id="statistics" value="0"><?php echo $module->get("cookies_statistics_label{$module->lang}|cookies_statistics_label"); ?></label>
</li>
<li <?php echo (!$showMarketingButton) ? "hidden" : ""; ?>>
<label for="marketing"><input class="optional" type="checkbox" name="marketing" id="marketing" value="0"><?php echo $module->get("cookies_marketing_label{$module->lang}|cookies_marketing_label"); ?></label>
</li>
<li <?php echo (!$showExternalMediaButton) ? "hidden" : ""; ?>>
<label for="external_media"><input class="optional" type="checkbox" name="external_media" id="external_media" value="0"><?php echo $module->get("cookies_external_media_label{$module->lang}|cookies_external_media_label"); ?></label>
</li>
</ul>
</div>
<div class="privacywire-buttons">
<button class="toggle" <?php echo ($showAllInsteadToggle) ? "hidden" : ""; ?>><?php echo $module->get("content_banner_button_toggle{$module->lang}|content_banner_button_toggle"); ?></button>
<button class="save"><?php echo $module->get("content_banner_button_save{$module->lang}|content_banner_button_save"); ?></button>
<button class="allow-all" <?php echo ($showAllInsteadToggle) ? "" : "hidden"; ?>><?php echo $module->get("content_banner_button_allow_all{$module->lang}|content_banner_button_allow_all"); ?></button>
</div>
<?php if (!empty($privacyPage) || !empty($imprintPage)): ?>
<div class="privacywire-page-links">
<?php if (!empty($privacyPage)): ?>
<a class="privacywire-page-link" href="<?php echo $privacyPage; ?>"
title="<?php echo $module->get("content_banner_privacy_title{$module->lang}|content_banner_privacy_title"); ?>"><?php echo $module->get("content_banner_privacy_title{$module->lang}|content_banner_privacy_title"); ?></a>
<?php endif; ?>
<?php if (!empty($imprintPage)): ?>
<a class="privacywire-page-link" href="<?php echo $imprintPage; ?>"
title="<?php echo $module->get("content_banner_imprint_title{$module->lang}|content_banner_imprint_title"); ?>"><?php echo $module->get("content_banner_imprint_title{$module->lang}|content_banner_imprint_title"); ?></a>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
</div>
<div class="privacywire privacywire-message"><div class="privacywire-body"><?php echo $module->get("content_banner_save_message{$module->lang}|content_banner_save_message"); ?></div></div>
</div>
</div>

View file

@ -0,0 +1,414 @@
<?php namespace ProcessWire;
class PrivacyWireConfig extends ModuleConfig
{
public function __construct()
{
$textarea_type = 'textarea';
if ($this->wire()->modules->isInstalled('InputfieldTinyMCE')) {
$textarea_type = 'tinymce';
} elseif ($this->wire()->modules->isInstalled('InputfieldCkeditor')) {
$textarea_type = 'ckeditor';
}
$this->add([
[ // general config
'name' => 'privacywire-general',
'type' => 'fieldset',
'label' => 'General Options',
'children' => [
[
'name' => 'is_active',
'type' => 'checkbox',
'label' => $this->_('Do you want to activate PrivacyWire?')
],
[ // opt-in type
'name' => 'cookie_groups',
'type' => 'asmselect',
'label' => $this->_('Available Cookie Groups'),
'description' => sprintf($this->_("Select the cookie groups displayed to the user. If more than the two default groups ('%s' and '%s') are allowed, the option window will be shown to the user."), $this->_("All Cookies"), $this->_("Necessary Cookies")),
'options' => [
"all" => $this->_("All Cookies"),
"necessary" => $this->_("Necessary Cookies"),
"functional" => $this->_("Functional Cookies"),
"statistics" => $this->_("Statistics Cookies"),
'marketing' => $this->_("Marketing Cookies"),
'external_media' => $this->_("External Media Cookies")
],
],
[ // version, integer
'name' => 'version',
'type' => 'integer',
'label' => $this->_('Versioning'),
'description' => $this->_("When you increase the version number, all users have to opt-in again. This version number is saved with the users consent in the cookie."),
'min' => 1,
'columnWidth' => 25,
],
[ // respect "do not track"
'name' => 'respectDNT',
'type' => 'checkbox',
'label' => $this->_('DNT: Do Not Track'),
'description' => $this->_("If enabled, PrivacyWire checks if the users browser sends the DNT-Header. If so, no cookie banner will be shown and the user will be handled like 'Only Necessary Cookies' would be chosen."),
'checkboxLabel' => $this->_('Respect "Do Not Track" Settings from the browser'),
'columnWidth' => 25,
],
[ // handle bots as only necessary
'name' => 'checkForBots',
'type' => 'checkbox',
'label' => $this->_('Bots: Hide Banner'),
'description' => $this->_("If enabled, PrivacyWire checks if the user-agent is some kind of bot. If so, no cookie banner will be shown and the user will be handled like 'Only Necessary Cookies' would be chosen. This im"),
'checkboxLabel' => $this->_('Treat bots as "only necessary" is chosen'),
'columnWidth' => 25,
],
[ // Message Timeout
'name' => 'messageTimeout',
'type' => 'integer',
'label' => $this->_('Consent Saving Confirmation Duration'),
'description' => $this->_("How many milliseconds should the consent saving confirmation be visible after the user makes a choice."),
'columnWidth' => 25,
],
],
],
[ // groups labels
'name' => 'privacywire-group-labels',
'type' => 'fieldset',
'label' => 'Cookie Groups Labels',
'children' => [
[ // label for cookie group: necessary
'name' => 'cookies_necessary_label',
'type' => 'text',
'label' => $this->_('Necessary Cookies'),
'useLanguages' => true,
'columnWidth' => 50,
'value' => $this->_("Necessary Cookies"),
],
[ // label for cookie group: functional
'name' => 'cookies_functional_label',
'type' => 'text',
'label' => $this->_('Functional Cookies'),
'showIf' => 'cookie_groups=functional',
'useLanguages' => true,
'columnWidth' => 50,
'value' => $this->_("Functional Cookies"),
],
[ // label for cookie group: statistics
'name' => 'cookies_statistics_label',
'type' => 'text',
'label' => $this->_('Statistics Cookies'),
'showIf' => 'cookie_groups=statistics',
'useLanguages' => true,
'columnWidth' => 50,
'value' => $this->_("Statistics Cookies"),
],
[ // label for cookie group: marketing
'name' => 'cookies_marketing_label',
'type' => 'text',
'label' => $this->_('Marketing Cookies'),
'showIf' => 'cookie_groups=marketing',
'useLanguages' => true,
'columnWidth' => 50,
'value' => $this->_("Statistics Cookies"),
],
[ // label for cookie group: external media
'name' => 'cookies_external_media_label',
'type' => 'text',
'label' => $this->_('External Media Cookies'),
'showIf' => 'cookie_groups=external_media',
'useLanguages' => true,
'columnWidth' => 50,
'value' => $this->_("External Media Cookies")
],
],
],
[ // banner
'name' => 'privacywire-banner',
'type' => 'fieldset',
'label' => 'Banner Options',
'children' => [
[ // banner headline (optional)
'name' => 'content_banner_title',
'type' => 'text',
'label' => $this->_('Title'),
'description' => $this->_("Optional: If empty, no headline will be shown in the banner."),
'useLanguages' => true,
'columnWidth' => 100,
],
[ // banner body copy
'name' => 'content_banner_text',
'type' => $textarea_type,
'label' => $this->_('Text'),
//'toolbar' => 'Bold, Italic, NumberedList, BulletedList, PWLink, Unlink, PWImage, Table',
'useLanguages' => true,
'columnWidth' => 100,
],
[ // banner show details
'name' => 'content_banner_details_show',
'type' => 'checkbox',
'label' => $this->_('Additional details in the options banner'),
'description' => $this->_("If enabled, you will have the possibility to display additional headline and text elements within the options banner where the user can select the cookies allowed."),
'checkboxLabel' => $this->_('Display additional details in the options banner'),
'columnWidth' => 100,
],
[ // banner details headline (optional)
'name' => 'content_banner_details_title',
'type' => 'text',
'label' => $this->_('Details Headline'),
'description' => $this->_("Optional: If empty, no headline will be shown in the banner."),
'showIf' => "content_banner_details_show=1",
'useLanguages' => true,
'columnWidth' => 100,
],
[ // banner details text
'name' => 'content_banner_details_text',
'type' => $textarea_type,
'label' => $this->_('Details Text'),
//'toolbar' => 'Bold, Italic, NumberedList, BulletedList, PWLink, Unlink, PWImage, Table',
'showIf' => "content_banner_details_show=1",
'useLanguages' => true,
'columnWidth' => 100,
],
],
],
[ // links
'name' => 'privacywire-links',
'type' => 'fieldset',
'label' => 'Links Options',
'children' => [
[ // privacy policy url
'name' => 'content_banner_privacy_link',
'type' => 'url',
'label' => $this->_('Privacy Policy URL'),
'description' => $this->_("If you want to output a link to your privacy policy page, add the URL to this page here."),
'useLanguages' => true,
'columnWidth' => 50,
],
[ // privacy policy link title
'name' => 'content_banner_privacy_title',
'type' => 'text',
'label' => $this->_('Privacy Policy link title'),
'description' => $this->_("The text of the link to your privacy policy page."),
//'showIf' => "content_banner_privacy_link!=''",
'useLanguages' => true,
'columnWidth' => 50,
],
[ // imprint url
'name' => 'content_banner_imprint_link',
'type' => 'url',
'label' => $this->_('Imprint URL'),
'description' => $this->_("If you want to output a link to your imprint page, add the URL to this page here."),
'useLanguages' => true,
'columnWidth' => 50,
],
[ // imprint link title
'name' => 'content_banner_imprint_title',
'type' => 'text',
'label' => $this->_('Imprint link title'),
'description' => $this->_("The text of the link to your imprint page."),
//'showIf' => "content_banner_imprint_link!=''",
'useLanguages' => true,
'columnWidth' => 50,
],
],
],
[ // buttons
'name' => 'privacywire-buttons',
'type' => 'fieldset',
'label' => 'Buttons Options',
'children' => [
[ // Button Label: Allow All
'name' => 'content_banner_button_allow_all',
'type' => 'text',
'label' => $this->_('Button Label: Allow All Cookies'),
'useLanguages' => true,
'columnWidth' => 33,
],
[ // Button Label: Allow Necessary
'name' => 'content_banner_button_allow_necessary',
'type' => 'text',
'label' => $this->_('Button Label: Allow Necessary Cookies'),
'useLanguages' => true,
'columnWidth' => 33,
],
[ // Button Label: Choose Cookies
'name' => 'content_banner_button_choose',
'type' => 'text',
'label' => $this->_('Button Label: Choose Cookies'),
'useLanguages' => true,
'columnWidth' => 34,
],
[ // Button Label: Toggle Cookies Options
'name' => 'content_banner_button_toggle',
'type' => 'text',
'label' => $this->_('Button Label: Toggle Cookie Options'),
'useLanguages' => true,
'columnWidth' => 33,
],
[ // Show another "Accept all" instead of the "Toggle" Button
'name' => 'content_banner_button_all_instead_toggle',
'type' => 'checkbox',
'label' => $this->_('Choose Window: "Accept all" instead of "Toggle"'),
'checkboxLabel' => $this->_('Show "Accept all" Button instead of "Toggle" Button'),
'columnWidth' => 33,
],
[ // Button Label: Save Preferences
'name' => 'content_banner_button_save',
'type' => 'text',
'label' => $this->_('Button Label: Save Preferences'),
'useLanguages' => true,
'columnWidth' => 34,
'value' => "",
],
[ // Saved Message Text
'name' => 'content_banner_save_message',
'type' => 'text',
'label' => $this->_('Message: Save Confirmation'),
'useLanguages' => true,
'columnWidth' => 33,
],
[ // Textformatter Button Label
'name' => 'textformatter_choose_label',
'type' => 'text',
'label' => $this->_('Textformatter Button label'),
'useLanguages' => true,
'columnWidth' => 33,
],
[ // Ask for consent Button label
'name' => 'ask_content_button_label',
'type' => 'text',
'label' => $this->_('Button Label: Ask for consent'),
'description' => $this->_("You can insert the current cookie category name by using the placeholder {category}."),
'useLanguages' => true,
'columnWidth' => 34,
],
[ // ask for consent text field
'name' => 'ask_consent_message',
'type' => $textarea_type,
'label' => $this->_('Text above button: Ask for consent'),
'description' => $this->_("You can insert the current cookie category name by using the placeholder {category}."),
//'toolbar' => 'Bold, Italic, NumberedList, BulletedList, PWLink, Unlink, PWImage, Table',
'useLanguages' => true,
'columnWidth' => 100,
],
],
],
[ // advanced options
'name' => 'privacywire-advanced',
'type' => 'fieldset',
'label' => 'Advanced Options',
'children' => [
[ // Output mode
'name' => 'output_mode',
'type' => 'select',
'label' => $this->_('Output mode of PrivacyWire JS Core'),
'description' => $this->_("Choose if you want to render the PrivacyWire JS Core as inline script or regular script tag."),
'options' => [
"regular" => $this->_("Regular script tag"),
"inline" => $this->_("Inline script"),
],
'columnWidth' => 50,
],
[ // banner header tag
'name' => 'banner_header_tag',
'type' => 'select',
'label' => $this->_('Banner Header Tag'),
'description' => $this->_("Choose between <header> and <div>."),
'options' => [
"div" => $this->_("<div>"),
"header" => $this->_("<header>"),
],
'columnWidth' => 50,
],
[ // add basic css styles or not
'name' => 'add_basic_css_styling',
'type' => 'checkbox',
'label' => $this->_('CSS: Add basic CSS Styling'),
'description' => $this->_("If enabled, PrivacyWire will automatically include some very basic css styles to the output."),
'checkboxLabel' => $this->_('Add basic CSS Styling'),
'columnWidth' => 50,
],
[ // use consent detection by class?
'name' => 'detect_consents_by_class',
'type' => 'checkbox',
'label' => $this->_('Detect consent windows by class `require-consent` instead of data-attribute.'),
'description' => $this->_("If enabled, PrivacyWire will use a class selector instead of data-attribute selector to detect elements which require consent. This is more performant."),
'checkboxLabel' => $this->_('Use consent detection by class instead of data-attribute'),
'columnWidth' => 50,
],
[ // alternate banner template
'name' => 'alternate_banner_template',
'type' => 'text',
'label' => $this->_('Alternate Banner Template'),
'description' => $this->_("If you want to replace the original banner template (located in site/modules/PrivacyWire/PrivacyWireBanner.php ) insert the alternative file path here (starting from webroot without leading slash )"),
'columnWidth' => 50,
],
[ // alternate inline consent template
'name' => 'alternate_inline_consent_template',
'type' => 'text',
'label' => $this->_('Alternate Inline Consent Template'),
'description' => $this->_("If you want to replace the original inline consent template (located in site/modules/PrivacyWire/PrivacyWireConsentBlueprint.php ) insert the alternative file path here (starting from webroot without leading slash )"),
'columnWidth' => 50,
],
[ // Trigger a custom js function
'name' => 'trigger_custom_js_function',
'type' => 'text',
'label' => $this->_('Trigger a custom js function'),
'description' => $this->_("If you want to trigger a custom js function after saving the cookie banner, insert the name of the function here"),
'columnWidth' => 50,
],
[ // render manually
'name' => 'render_manually',
'type' => 'checkbox',
'label' => $this->_('Render Banner and Header Content Manually'),
'description' => $this->_("If you want to render PrivacyWire header and banner content manually instead of letting the module render them for you, check this option."),
'notes' => $this->_("Use \n`\$modules->get('PrivacyWire')->headContent` to render header tags and \n`\$modules->get('PrivacyWire')->bodyContent` to render body content. \n**OR** if you want to have the total flexibility where and how you embed the required scripts and markup, have a look into the PrivacyWire.module and read the comments ;-)"),
'columnWidth' => 50,
],
],
],
]);
}
public function getDefaults()
{
return [
'is_active' => true,
'version' => 1,
'cookie_groups' => ["all", "necessary"],
'respectDNT' => false,
'checkForBots' => false,
'cookies_necessary_label' => $this->_('Necessary'),
'cookies_functional_label' => $this->_('Functional'),
'cookies_statistics_label' => $this->_('Statistics'),
'cookies_marketing_label' => $this->_('Marketing'),
'cookies_external_media_label' => $this->_('External Media'),
'content_banner_title' => $this->_("This website is using cookies to provide a good browsing experience"),
'content_banner_text' => $this->_("These include essential cookies that are necessary for the operation of the site, as well as others that are used only for anonymous statistical purposes, for comfort settings or to display personalized content. You can decide for yourself which categories you want to allow. Please note that based on your settings, not all functions of the website may be available."),
'content_banner_details_show' => false,
'content_banner_details_title' => $this->_("This is how and why we use cookies"),
'content_banner_details_text' => $this->_("Here you can store more detailed information on the cookies used or describe individual cookies in depth."),
'content_banner_privacy_link' => null,
'content_banner_privacy_title' => $this->_("Privacy Policy"),
'content_banner_imprint_link' => null,
'content_banner_imprint_title' => $this->_("Imprint"),
'content_banner_button_allow_all' => $this->_("Accept all"),
'content_banner_button_allow_necessary' => $this->_("Accept necessary cookies only"),
'content_banner_button_choose' => $this->_("Choose cookies"),
'content_banner_button_save' => $this->_("Save preferences"),
'content_banner_button_toggle' => $this->_("Toggle options"),
'content_banner_save_message' => $this->_("Your cookie preferences have been saved."),
'content_banner_button_all_instead_toggle' => false,
'textformatter_choose_label' => $this->_("Show or edit my Cookie Consent"),
'trigger_custom_js_function' => "",
'messageTimeout' => 1500,
'add_basic_css_styling' => true,
'ask_consent_message' => $this->_("To load this element, it is required to consent to the following cookie category: {category}."),
'ask_content_button_label' => $this->_("Load {category} cookies"),
'banner_header_tag' => 'div',
'alternate_banner_template' => '',
'alternate_inline_consent_template' => '',
'render_manually' => false,
'detect_consents_by_class' => false,
'output_mode' => 'regular'
];
}
}

View file

@ -0,0 +1,10 @@
<?php namespace ProcessWire;
/**
* @var PrivacyWire $module Instance of the PrivacyWire
*/
?>
<div hidden class="privacywire-ask-consent-blueprint" id="privacywire-ask-consent-blueprint">
<div class="privacywire-consent-message"><?php echo $module->get("ask_consent_message{$module->lang}|ask_consent_message"); ?></div>
<button class="privacywire-consent-button"
data-consent-category="{categoryname}"><?php echo $module->get("ask_content_button_label{$module->lang}|ask_content_button_label"); ?></button>
</div>

View file

@ -0,0 +1,53 @@
# PrivacyWire
Cookie & Consent Manager for ProcessWire
This module adds the possibility to define cookie / consent groups and load corresponding elements only after the site visitor has given consent.
The following cookie groups are available (the frontend visible label is editable and translatable, this is just the technical name)
* Necessary
* Functional
* Statistics
* Marketing
* External Media
* (All Cookies)
Necessary elements are always active. You can let the user decide, which individual cookie group(s) should be allowed, and/or add an „Allow all“ button.
You can insert basic styles via css or completely style it yourself.
The PrivacyWire Core Javascript file is available both as ES6 as well as transpiled with Babel for IE11 support. Both versions have a very small footprint:
File | Size | Gzipped
--- | :---: | ---:
PrivacyWire.js | < 9 kb | < 3 kb
PrivacyWire_legacy.js | < 13 kb | < 4 kb
To load scripts, frames, images or other elements only after the site visitor has given consent to that specific cookie group, use the following attributes:
```html
<script type="text/plain" data-type="text/javascript" data-category="functional" class="require-consent">console.log("This script only runs after giving consent to functional cookies");</script>
```
You can even render and alternate Opt-In text instead of the element:
```html
<iframe data-src="https://processwire.com/" data-category="marketing" data-ask-consent="1" class="require-consent" frameborder="0" height="400" width="400"></iframe>
```
**Available attributes:**
Attribute | Info | Description | Type
--- | :---: | --- | ---:
class `require-consent` | optional (required if config option enabled) | If the config option "Detect consent windows by class `require-consent` instead of data-attribute" is enabled |string
`data-category` | required | defines the assigned cookie group for this element | string
`data-type` | optional (required for scripts) | replaces the type attribute after giving consent | string
`data-src` | optional (required for external scripts, images or iframes) | replaces the src attribute after giving consent | string
`data-srset` | optional | replaces the srcset attribute for images after giving consent | string
`data-ask-consent`| optional | Replace element with Opt-In-Element | bool `0/1`
For script tags it is required to add `type="text/plain"`, otherwise the script executes directly.
## Textformatter to choose Cookie groups / Opt-Out
With PrivacyWire itself comes a Textformatter with the shortcode `[[privacywire-choose-cookies]]` to add a button to show the cookie group selection window.
To automatically include the Opt-In-Element for embedded videos via [TextformatterVideoEmbed](https://processwire.com/modules/textformatter-video-embed/) you can choose the cookie group in the Textformatter settings.
## Multiple language support / i18n
The module uses the [ProcessWire-integrated translation system](https://processwire.com/docs/multi-language-support/).
## Hookable methods
Most of the module methods are hookable! Have a look into [PrivacyWire.module](PrivacyWire.module) to find out more.

View file

@ -0,0 +1,68 @@
<?php namespace ProcessWire;
/**
* Textformatter PrivacyWire
* This module adds the textformatter for PrivacyWire
*
*
* @author blaueQuelle
*
* ProcessWire 3.x
* Copyright (C) 2011 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://www.processwire.com
* http://www.ryancramer.com
*
*/
class TextformatterPrivacyWire extends Textformatter implements Module
{
public static function getModuleInfo()
{
return [
'title' => 'PrivacyWire Textformatter',
'summary' => "PrivacyWire Textformatter to render privacy options via shortcode [[privacywire-choose-cookies]]",
'author' => 'blaueQuelle',
'href' => "https://github.com/blaueQuelle/privacywire",
'version' => 10,
'requires' => [
"PHP>=7.2",
"ProcessWire>=3.0.110"
],
];
}
/**
* Formats the given $str reference.
* Page and Field context are currently not necessary for the formatter to work.
* The formatter can be called via format(&$str) or formatValue(Page $page, Field $field, &$value)
* formatValue(Page $page, Field $field, &$value) internally calls format(&$str), so the former does not need to be overwritten.
* @param mixed $str
* @return void
*/
public function format(&$str)
{
// Replace privacywire-choose-cookies with button element
$tag_search = $this->open_tag . "privacywire-choose-cookies" . $this->close_tag;
if (strpos($str, $tag_search) !== false) {
$privacyWire = $this->modules->get("PrivacyWire");
// Multi Language Support
$lang = ($this->wire('languages') && !$this->wire('user')->language->isDefault()) ? '__' . $this->wire('user')->language->id : '';
$tag_replace = "<button class='button privacywire-show-options'>{$privacyWire->get("textformatter_choose_label$lang|textformatter_choose_label")}</button>";
$str = str_replace($tag_search, $tag_replace, $str);
}
// Optional: enable PrivacyWire support for embedded media
if ($this->video_category && (strpos($str, 'www.youtube.com/embed/') !== false || strpos($str, 'www.youtube-nocookie.com/embed/') !== false || strpos($str, 'player.vimeo.com') !== false)) {
if (preg_match_all('/\<iframe.*?src=("|\')(?:https?:)\/\/(?:(?:www\.)?youtube-nocookie|(?:www\.)?youtube|player\.vimeo)\..*?\1.*?\<\/iframe\>/is', $str, $matches)) {
foreach ($matches[0] as $match) {
$new_match = str_replace(' src=', ' data-category="' . $this->video_category . '" data-ask-consent=1 data-src=', $match);
$str = str_replace($match, $new_match, $str);
}
}
}
}
}

View file

@ -0,0 +1,54 @@
<?php namespace ProcessWire;
class TextformatterPrivacyWireConfig extends ModuleConfig
{
public function getDefaults()
{
return [
'open_tag' => '[[',
'close_tag' => ']]',
'video_category' => null,
];
}
public function getInputfields()
{
$inputfields = parent::getInputfields();
// open tag
$f = $this->modules->get('InputfieldText');
$f->attr('name', 'open_tag');
$f->label = $this->_('Open Tag');
$f->columnWidth = 50;
$inputfields->add($f);
// close tag
$f = $this->modules->get('InputfieldText');
$f->attr('name', 'close_tag');
$f->label = $this->_('Close Tag');
$f->columnWidth = 50;
$inputfields->add($f);
// embedded media
$fs = $this->modules->get('InputfieldFieldset');
$fs->attr('name', 'embedded_media');
$fs->label = $this->_('Embedded media');
$inputfields->add($fs);
// category for embedded videos (optional)
$f = $this->modules->get('InputfieldSelect');
$f->attr('name', 'video_category');
$f->label = $this->_('Category for embedded videos');
$f->description = $this->_('If you select a category here, users will need to accept said cookie category before embedded video elements are displayed. Leave empty to disable this feature.');
$f->notes = $this->_('Recommended if you\'re using [TextformatterVideoEmbed](https://processwire.com/modules/textformatter-video-embed/). Note that TextformatterPrivacyWire need to run after TextformatterVideoEmbed for this to work.');
$f->columnWidth = 50;
$f->options = [
"statistics" => $this->_("Statistics"),
'marketing' => $this->_("Marketing"),
'external_media' => $this->_("External Media")
];
$fs->add($f);
return $inputfields;
}
}

View file

@ -0,0 +1,14 @@
{
"name": "blauequelle/privacywire",
"license": "GPL-3.0",
"type": "pw-module",
"authors": [
{
"name": "blauequelle",
"email": "jk@blauequelle.de"
}
],
"require": {
"wireframe-framework/processwire-composer-installer": "^1.0.0"
}
}

View file

@ -0,0 +1 @@
.privacywire{background:#fff;bottom:-250%;box-shadow:0 -1px 3px rgba(0,0,0,.3);left:0;opacity:0;padding:1rem;position:fixed;right:0;transition:bottom .3s ease-in,opacity .3s ease;z-index:1}.show-banner .privacywire-banner,.show-message .privacywire-message,.show-options .privacywire-options{bottom:0;opacity:1}.privacywire-header{font-weight:700}.privacywire button[hidden],.privacywire-ask-consent-blueprint,[data-ask-consent-rendered="1"]{display:none}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,134 @@
if (!Array.from) {
Array.from = (function () {
var symbolIterator;
try {
symbolIterator = Symbol.iterator
? Symbol.iterator
: 'Symbol(Symbol.iterator)';
} catch (e) {
symbolIterator = 'Symbol(Symbol.iterator)';
}
var toStr = Object.prototype.toString;
var isCallable = function (fn) {
return (
typeof fn === 'function' ||
toStr.call(fn) === '[object Function]'
);
};
var toInteger = function (value) {
var number = Number(value);
if (isNaN(number)) return 0;
if (number === 0 || !isFinite(number)) return number;
return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
};
var maxSafeInteger = Math.pow(2, 53) - 1;
var toLength = function (value) {
var len = toInteger(value);
return Math.min(Math.max(len, 0), maxSafeInteger);
};
var setGetItemHandler = function setGetItemHandler(isIterator, items) {
var iterator = isIterator && items[symbolIterator]();
return function getItem(k) {
return isIterator ? iterator.next() : items[k];
};
};
var getArray = function getArray(
T,
A,
len,
getItem,
isIterator,
mapFn
) {
// 16. Let k be 0.
var k = 0;
// 17. Repeat, while k < len… or while iterator is done (also steps a - h)
while (k < len || isIterator) {
var item = getItem(k);
var kValue = isIterator ? item.value : item;
if (isIterator && item.done) {
return A;
} else {
if (mapFn) {
A[k] =
typeof T === 'undefined'
? mapFn(kValue, k)
: mapFn.call(T, kValue, k);
} else {
A[k] = kValue;
}
}
k += 1;
}
if (isIterator) {
throw new TypeError(
'Array.from: provided arrayLike or iterator has length more then 2 ** 52 - 1'
);
} else {
A.length = len;
}
return A;
};
// The length property of the from method is 1.
return function from(arrayLikeOrIterator /*, mapFn, thisArg */) {
// 1. Let C be the this value.
var C = this;
// 2. Let items be ToObject(arrayLikeOrIterator).
var items = Object(arrayLikeOrIterator);
var isIterator = isCallable(items[symbolIterator]);
// 3. ReturnIfAbrupt(items).
if (arrayLikeOrIterator == null && !isIterator) {
throw new TypeError(
'Array.from requires an array-like object or iterator - not null or undefined'
);
}
// 4. If mapfn is undefined, then let mapping be false.
var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
var T;
if (typeof mapFn !== 'undefined') {
// 5. else
// 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
if (!isCallable(mapFn)) {
throw new TypeError(
'Array.from: when provided, the second argument must be a function'
);
}
// 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 2) {
T = arguments[2];
}
}
// 10. Let lenValue be Get(items, "length").
// 11. Let len be ToLength(lenValue).
var len = toLength(items.length);
// 13. If IsConstructor(C) is true, then
// 13. a. Let A be the result of calling the [[Construct]] internal method
// of C with an argument list containing the single item len.
// 14. a. Else, Let A be ArrayCreate(len).
var A = isCallable(C) ? Object(new C(len)) : new Array(len);
return getArray(
T,
A,
len,
setGetItemHandler(isIterator, items),
isIterator,
mapFn
);
};
})();
}

4466
site/modules/PrivacyWire/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,26 @@
{
"name": "privacywire",
"author": "webworkerJoshua",
"license": "GPL-3.0",
"private": true,
"engines": {
"node": ">=18",
"npm": ">=9"
},
"scripts": {
"dev": "rollup -c -w",
"build": "rollup -c --compact"
},
"devDependencies": {
"@babel/core": "^7.22.5",
"@babel/preset-env": "^7.22.5",
"@rollup/plugin-babel": "^6.0.3",
"@rollup/plugin-terser": "^0.4.3",
"postcss": "^8.4.24",
"rollup": "^4.13.0",
"rollup-plugin-copy": "^3.4.0",
"rollup-plugin-ignore-import": "^1.3.2",
"rollup-plugin-postcss": "^4.0.2",
"rollup-pluginutils": "^2.8.2"
}
}

View file

@ -0,0 +1,59 @@
import babel from '@rollup/plugin-babel';
import postcss from 'rollup-plugin-postcss';
import ignoreImport from 'rollup-plugin-ignore-import';
import terser from '@rollup/plugin-terser';
import copy from 'rollup-plugin-copy';
const production = !process.env.ROLLUP_WATCH;
export default [
{
// ES6 PrivacyWire JS Frontend File
input: 'src/js/PrivacyWire.js',
output: {
file: 'js/PrivacyWire.js',
format: 'iife',
compact: true
},
plugins: [
postcss({
minimize: true,
extract: "PrivacyWire.css"
}),
production && terser({
keep_classnames: true,
keep_fnames: true
})
],
},
{
// Regular PrivacyWire JS Frontend File
input: 'src/js/PrivacyWire.js',
output: {
file: 'js/PrivacyWire_legacy.js',
format: 'iife',
compact: true
},
plugins: [
ignoreImport({
extensions: ['.css']
}),
babel({
exclude: 'node_modules/**',
babelHelpers: 'bundled',
}),
copy({
targets: [
{
src: "js/PrivacyWire.css",
dest: "css/"
}
]
}),
production && terser({
keep_classnames: true,
keep_fnames: true
})
]
}
];

View file

@ -0,0 +1,28 @@
.privacywire {
position: fixed;
bottom: -250%;
left: 0;
right: 0;
box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.3);
opacity: 0;
background: #fff;
z-index: 1;
padding: 1rem;
transition: bottom .3s ease-in, opacity .3s ease;
}
.show-banner .privacywire-banner,
.show-options .privacywire-options,
.show-message .privacywire-message {
bottom: 0;
opacity: 1;
}
.privacywire-header {
font-weight: 700;
}
[data-ask-consent-rendered="1"], .privacywire-ask-consent-blueprint, .privacywire button[hidden] {
display: none;
}

View file

@ -0,0 +1,456 @@
import '../css/PrivacyWire.css'
import "./string-formatter"
class PrivacyWire {
constructor(PrivacyWireSettings) {
this.name = "privacywire"
this.toggleToStatus = true
this.cookieGroups = Object.freeze([
"necessary",
"functional",
"statistics",
"marketing",
"external_media"
])
this.settings = this.sanitizeSettings(PrivacyWireSettings)
this.userConsent = this.sanitizeStoredConsent()
this.elements = this.initiateElements()
this.syncConsentToCheckboxes()
if (!this.checkForValidConsent()) {
this.showBanner()
}
this.checkElementsWithRequiredConsent()
this.handleButtons()
}
/**
* Sanitize the inline script settings
* @param {Object} PrivacyWireSettings - The inline script settings container
* @returns {Object} Sanitized object with the settings
*/
sanitizeSettings(PrivacyWireSettings) {
let settings = {}
settings.version = parseInt(PrivacyWireSettings.version)
settings.dnt = Boolean(parseInt(PrivacyWireSettings.dnt))
settings.bots = Boolean(parseInt(PrivacyWireSettings.bots))
settings.customFunction = `${PrivacyWireSettings.customFunction}`
settings.messageTimeout = parseInt(PrivacyWireSettings.messageTimeout)
settings.consentByClass = Boolean(parseInt(PrivacyWireSettings.consentByClass))
settings.cookieGroups = {}
for (const key of this.cookieGroups) {
settings.cookieGroups[key] = `${PrivacyWireSettings.cookieGroups[key]}`
}
return settings
}
/**
* Sanitize stored consent from LocalStorage
* @returns {Object} either empty object or sanitized stored consent object if version matches with settings version
*/
sanitizeStoredConsent() {
if (!window.localStorage.getItem(this.name)) {
return this.getDefaultConsent()
}
const storedConsentRaw = JSON.parse(window.localStorage.getItem(this.name))
if (parseInt(storedConsentRaw.version) !== this.settings.version) {
return this.getDefaultConsent()
}
if (typeof storedConsentRaw.cookieGroups === 'undefined') {
this.removeStoredConsent();
return this.getDefaultConsent()
}
let storedConsent = {}
storedConsent.version = parseInt(storedConsentRaw.version)
storedConsent.cookieGroups = {}
for (const key of this.cookieGroups) {
storedConsent.cookieGroups[key] = Boolean(storedConsentRaw.cookieGroups[key])
}
return storedConsent
}
/**
* Get default Consent object
* @returns {Object} Consent object with only necessary allowed
*/
getDefaultConsent() {
let consent = {}
consent.version = 0
consent.cookieGroups = {}
for (const key of this.cookieGroups) {
consent.cookieGroups[key] = (key === "necessary")
}
return consent
}
initiateElements() {
let elements = {}
elements.banner = {}
elements.banner.wrapper = document.getElementById("privacywire-wrapper")
elements.banner.intro = elements.banner.wrapper.getElementsByClassName("privacywire-banner")
elements.banner.options = elements.banner.wrapper.getElementsByClassName("privacywire-options")
elements.banner.message = elements.banner.wrapper.getElementsByClassName("privacywire-message")
elements.buttons = {}
elements.buttons.acceptAll = elements.banner.wrapper.getElementsByClassName("allow-all")
elements.buttons.acceptNecessary = elements.banner.wrapper.getElementsByClassName("allow-necessary")
elements.buttons.choose = elements.banner.wrapper.getElementsByClassName("choose")
elements.buttons.toggle = elements.banner.wrapper.getElementsByClassName("toggle")
elements.buttons.save = elements.banner.wrapper.getElementsByClassName("save")
elements.buttons.askForConsent = document.getElementsByClassName("privacywire-consent-button")
elements.buttons.externalTrigger = document.getElementsByClassName("privacywire-show-options")
elements.checkboxes = {}
for (const key of this.cookieGroups) {
if (key === "necessary") {
continue
}
elements.checkboxes[key] = document.getElementById(key)
}
elements.blueprint = document.getElementById("privacywire-ask-consent-blueprint")
elements.elementsWithRequiredConsent = (this.settings.consentByClass === true) ? document.getElementsByClassName("require-consent") : document.querySelectorAll("[data-category]")
elements.consentWindows = document.getElementsByClassName("privacywire-ask-consent")
return elements
}
handleButtons() {
this.handleButtonHelper(this.elements.buttons.acceptAll, "handleButtonAcceptAll")
this.handleButtonHelper(this.elements.buttons.acceptNecessary, "handleButtonAcceptNecessary")
this.handleButtonHelper(this.elements.buttons.choose, "handleButtonChoose")
this.handleButtonHelper(this.elements.buttons.toggle, "handleButtonToggle")
this.handleButtonHelper(this.elements.buttons.save, "handleButtonSave")
this.handleButtonHelper(this.elements.buttons.askForConsent, "handleButtonAskForConsent")
this.handleButtonHelper(this.elements.buttons.externalTrigger, "handleButtonExternalTrigger")
}
handleButtonHelper(buttons, method) {
if (buttons) {
const pw = this
Array.from(buttons).forEach((btn) => {
pw[method](btn)
})
}
}
reHandleExternalButtons() {
this.elements.buttons.externalTrigger = document.getElementsByClassName("privacywire-show-options")
this.handleButtonHelper(this.elements.buttons.externalTrigger, "handleButtonExternalTrigger")
}
handleButtonAcceptAll(btn) {
btn.addEventListener("click", () => {
for (const key of this.cookieGroups) {
this.userConsent.cookieGroups[key] = true
}
this.syncConsentToCheckboxes()
this.saveConsent()
})
}
handleButtonAcceptNecessary(btn) {
btn.addEventListener("click", () => {
this.userConsent = this.getDefaultConsent()
this.syncConsentToCheckboxes()
this.saveConsent()
})
}
handleButtonChoose(btn) {
btn.addEventListener("click", () => {
this.showOptions()
})
}
handleButtonToggle(btn) {
btn.addEventListener("click", () => {
for (const key in this.elements.checkboxes) {
this.elements.checkboxes[key].checked = this.toggleToStatus
}
this.toggleToStatus = !this.toggleToStatus
})
}
handleButtonSave(btn) {
btn.addEventListener("click", () => {
for (const key of this.cookieGroups) {
if (key === "necessary") {
continue
}
this.userConsent.cookieGroups[key] = this.elements.checkboxes[key].checked
}
this.saveConsent()
})
}
handleButtonAskForConsent(btn) {
btn.addEventListener("click", () => {
const {dataset} = btn
this.userConsent.cookieGroups[dataset.consentCategory] = true
this.syncConsentToCheckboxes()
this.saveConsent()
btn.parentElement.remove()
})
}
handleButtonExternalTrigger(btn) {
btn.addEventListener("click", (event) => {
event.preventDefault()
this.showOptions()
})
}
syncConsentToCheckboxes() {
for (const key of this.cookieGroups) {
if (key === "necessary") {
continue
}
this.elements.checkboxes[key].checked = this.userConsent.cookieGroups[key]
}
}
checkForValidConsent() {
if (this.userConsent.version > 0 && this.userConsent.version === this.settings.version) {
return true
}
if (this.settings.bots) {
return this.checkForBots();
}
return this.settings.dnt && this.checkForUsersDNT() === true
}
checkForUsersDNT() {
if (this.settings.dnt && navigator.doNotTrack === "1") {
this.userConsent = this.getDefaultConsent()
this.saveConsent(true)
return true
}
return false
}
detectRobot() {
const robots = new RegExp([
/bot/, /spider/, /crawl/, // GENERAL TERMS
/APIs-Google/, /AdsBot/, /Googlebot/, // GOOGLE ROBOTS
/mediapartners/, /Google Favicon/,
/Google Page Speed Insights/, /Chrome-Lighthouse/, // GOOGLE PAGESPEED AND LIGHTHOUSE
/FeedFetcher/, /Google-Read-Aloud/,
/DuplexWeb-Google/, /googleweblight/,
/bing/, /yandex/, /baidu/, /duckduck/, /yahoo/, // OTHER ENGINES
/ecosia/, /ia_archiver/,
/facebook/, /instagram/, /pinterest/, /reddit/, // SOCIAL MEDIA
/slack/, /twitter/, /whatsapp/, /youtube/,
/semrush/, // OTHER
].map((r) => r.source).join("|"), "i"); // BUILD REGEXP + "i" FLAG
return robots.test(navigator.userAgent);
}
checkForBots() {
if (this.detectRobot()) {
this.userConsent = this.getDefaultConsent()
this.saveConsent(true)
return true
}
return false
}
saveConsent(silent = false) {
this.userConsent.version = this.settings.version
window.localStorage.removeItem(this.name)
window.localStorage.setItem(this.name, JSON.stringify(this.userConsent))
this.hideBannerAndOptions()
if (!silent) {
this.showMessage()
}
this.checkElementsWithRequiredConsent()
this.triggerCustomFunction()
}
triggerCustomFunction() {
if (this.settings.customFunction.length && typeof window[this.settings.customFunction] === "function") {
window[this.settings.customFunction]()
}
}
hideBannerAndOptions() {
this.elements.banner.wrapper.classList.remove("show-banner", "show-options")
document.body.classList.remove("has-privacywire-window-opened")
document.dispatchEvent(new CustomEvent('PrivacyWireBannerAndOptionsClosed'))
}
showBanner() {
this.elements.banner.wrapper.classList.add("show-banner")
document.body.classList.add("has-privacywire-window-opened")
document.dispatchEvent(new CustomEvent('PrivacyWireBannerOpened'))
}
showOptions() {
this.elements.banner.wrapper.classList.remove("show-banner")
this.elements.banner.wrapper.classList.add("show-options")
document.body.classList.add("has-privacywire-window-opened")
document.dispatchEvent(new CustomEvent('PrivacyWireOptionsOpened'))
}
showMessage() {
this.elements.banner.wrapper.classList.add("show-message")
setTimeout(() => {
this.elements.banner.wrapper.classList.remove("show-message")
}, this.settings.messageTimeout)
}
checkElementsWithRequiredConsent() {
if (this.settings.consentByClass === false) {
this.elements.elementsWithRequiredConsent = document.querySelectorAll("[data-category]")
}
this.cleanOldConsentWindows()
if (this.elements.elementsWithRequiredConsent) {
const pw = this
Array.from(this.elements.elementsWithRequiredConsent).forEach(function (el) {
const category = el.dataset.category
if (!category) {
return
}
let allowed = false
for (const consentCategory in pw.userConsent.cookieGroups) {
if (consentCategory === category && pw.userConsent.cookieGroups[consentCategory] === true) {
allowed = true
break
}
}
if (!allowed) {
pw.updateDisallowedElement(el)
return
}
pw.updateAllowedElement(el)
})
}
}
cleanOldConsentWindows() {
if (this.elements.consentWindows) {
Array.from(this.elements.consentWindows).forEach((el) => {
const {dataset} = el
const category = dataset.disallowedConsentCategory
let allowed = false
for (const consentCategory in this.userConsent.cookieGroups) {
if (consentCategory === category && this.userConsent.cookieGroups[consentCategory] === true) {
allowed = true
break
}
}
if (allowed) {
el.remove()
}
})
}
}
updateDisallowedElement(el) {
const {dataset} = el
if (!dataset.askConsent || dataset.askConsentRendered === "1") {
return
}
const category = dataset.category
const categoryLabel = this.settings.cookieGroups[category]
let newEl = document.createElement("div")
newEl.classList.add("privacywire-ask-consent", "consent-category-" + category)
newEl.dataset.disallowedConsentCategory = category
newEl.innerHTML = this.elements.blueprint.innerHTML.formatUnicorn({
category: categoryLabel,
categoryname: category
})
el.insertAdjacentElement('afterend', newEl)
el.dataset.askConsentRendered = "1"
}
updateAllowedElement(el) {
if (el.tagName.toLowerCase() === "script") {
this.updateAllowedElementScript(el)
} else {
this.updateAllowedElementOther(el)
}
}
updateAllowedElementScript(el) {
const {dataset} = el
let newEl = document.createElement(el.tagName)
for (const key of Object.keys(dataset)) {
newEl.dataset[key] = el.dataset[key]
}
newEl.type = dataset.type
if (dataset.src) {
newEl.src = dataset.src
}
// textContent is more suitable as innerText may change the value, is limited, costly and slower
// (like introduced <br> elements instead of new lines in inline scripts).
// More: https://stackoverflow.com/questions/35213147/difference-between-textcontent-vs-innertext
newEl.textContent = el.textContent
if (el.id) { newEl.id = el.id} // Do not create an empty ID attribute if no ID exist
newEl.defer = el.defer
newEl.async = el.async
newEl = this.removeUnusedAttributesFromElement(newEl)
el.insertAdjacentElement('afterend', newEl)
el.remove()
}
updateAllowedElementOther(el) {
const {dataset} = el
el.type = dataset.type ?? 'text/javascript'
el.src = dataset.src
el.srcset = dataset.srcset
this.removeUnusedAttributesFromElement(el)
}
removeUnusedAttributesFromElement(el) {
el.removeAttribute("data-ask-consent")
el.removeAttribute("data-ask-consent-rendered")
el.removeAttribute("data-category")
el.removeAttribute("data-src")
el.removeAttribute("data-srcset")
el.removeAttribute("data-type")
el.classList.remove("require-consent")
return el
}
refresh() {
this.checkElementsWithRequiredConsent()
this.handleButtonHelper(this.elements.buttons.askForConsent, "handleButtonAskForConsent")
}
removeStoredConsent() {
if (!window.localStorage.getItem(this.name)) {
return;
}
window.localStorage.removeItem(this.name);
}
}
document.addEventListener("DOMContentLoaded", function () {
window.PrivacyWire = new PrivacyWire(PrivacyWireSettings)
});

View file

@ -0,0 +1,20 @@
// String formatter to output opt-in message of disabled elements
// source: https://stackoverflow.com/a/18234317
String.prototype.formatUnicorn = String.prototype.formatUnicorn ||
function () {
"use strict";
var str = this.toString();
if (arguments.length) {
var t = typeof arguments[0];
var key;
var args = ("string" === t || "number" === t) ?
Array.prototype.slice.call(arguments)
: arguments[0];
for (key in args) {
str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
}
}
return str;
};