<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\Environment;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use App\Exception\ResouceNotFoundException as ResourceNotFoundException;
use App\Utils\ContentHelper;
use App\Utils\CategoryHelper;
use App\Utils\CustomerHelper;
use App\Utils\MediaHelper;
use App\Utils\MenuHelper;
use App\Utils\DefaultHelper;
use App\Utils\PollHelper;
use Symfony\Component\Form\Forms;
use App\Form\DirectoryLeadType;
use App\Entity\Lead;
use App\Entity\Content;
use App\Entity\SiteConfig;
use Doctrine\Common\Collections\ArrayCollection;
use \SimpleXMLElement as SimpleXMLElement;
class RCSExtension extends AbstractExtension
{
protected $defaultHelper;
protected $contentHelper;
protected $menuHelper;
protected $mediaHelper;
protected $categoryHelper;
protected $customerHelper;
protected $pollHelper;
protected $twig;
protected $request;
protected $security;
protected $container;
public function __construct (
DefaultHelper $defaultHelper,
ContentHelper $contentHelper,
MenuHelper $menuHelper,
MediaHelper $mediaHelper,
CategoryHelper $categoryHelper,
CustomerHelper $customerHelper,
PollHelper $pollHelper,
Environment $twig,
RequestStack $reqStack,
Security $security,
Container $container
) {
$this->defaultHelper = $defaultHelper;
$this->contentHelper = $contentHelper;
$this->menuHelper = $menuHelper;
$this->mediaHelper = $mediaHelper;
$this->categoryHelper = $categoryHelper;
$this->customerHelper = $customerHelper;
$this->pollHelper = $pollHelper;
$this->request = $reqStack->getCurrentRequest();
$this->security = $security;
$this->container = $container;
$this->twig = $twig;
}
public function getFunctions (): array
{
// add custom functions below
return array (
// show_module function
new TwigFunction (
"show_module",
array ($this, "show_module"),
array(
// "needs_environment" => true,
"is_safe" => array ("html"),
)
),
new TwigFunction (
"rawTwig",
array ($this, "rawTwig"),
array(
// "needs_environment" => true,
"is_safe" => array ("html"),
)
),
// show_menu function
new TwigFunction (
"show_menu",
array ($this, "show_menu"),
array (
// "needs_environment" => true,
"is_safe" => array ("html"),
)
),
new TwigFunction (
"check_modules",
array ($this, "check_modules")
),
// get_attributes
new TwigFunction (
"get_attributes",
array ($this, "get_attributes"),
array (
"is_safe" => array ("html")
)
),
new TwigFunction (
"get_href",
array ($this, "get_href")
),
new TwigFunction (
"rcs_include",
array ($this, "rcsInclude"),
array (
// "needs_environment" => true
)
),
new TwigFunction (
"show_media",
array ($this, "show_media")
),
new TwigFunction (
"post_age_format",
array ($this, "post_age_format")
),
new TwigFunction (
"gravity_form",
array ($this, "gravity_form")
),
new TwigFunction (
"get_entity",
array ($this, "get_entity")
),
new TwigFunction (
"unserialize",
array ($this, "unserialize")
),
new TwigFunction (
"from_json",
array ($this, "from_json")
)
);
}
public function from_json ($string)
{
try {
$return = json_decode($string, true);
return $return;
} catch (\Exception $e) {
}
return [];
}
public function get_entity ($type = "", $column = "", $value = "")
{
try {
switch ($type) {
case "Media":
// TODO - need to move all of these functions into helper...
if ($column == "old_id") {
return $this->mediaHelper->getMediaByOldId($value);
} else if (!$value) {
return $this->mediaHelper->getMediaById($column);
}
break;
case "Content":
if ($column == "old_id") {
return $this->contentHelper->getContentByOldId($value);
} else if (!$value) {
return $this->contentHelper->getContentById($column);
}
break;
}
} catch (\Exception $e) {
if (get_class($e) === "App\Exception\ResourceNotFoundException") {
return null;
}
// re-throw otherwise
throw $e;
}
}
public function unserialize ($data = "")
{
return unserialize($data);
}
// hack to convert current gravity forms to default lead form
public function gravity_form ($content = "", $meta = array ())
{
if (strpos($content, "[gravityform") !== false) {
$buttonColor = "#A41822";
if (!empty($meta["btn_color"])) {
$buttonColor = $meta["btn_color"];
}
$buttonText = "Submit";
if (!empty($meta["btn_text"])) {
$buttonText = $meta["btn_text"];
}
/*
$factory = Forms::createFormFactory();
$form = $factory
->create(
DirectoryLeadType::class,
new Lead()
)->createView();
$module = $this->show_module(array(
"type" => "form2",
"form" => $form,
));
*/
// for time being just create static default form
$module = '
<form method="post" class="py-4">
<label class="btn-block"><span>First Name:</span>
<input
type="text"
class="form-control"
placeholder="Your First Name"
name="firstname"
required
/>
</label>
<label class="btn-block"><span>Last Name:</span>
<input
type="text"
class="form-control"
placeholder="Your Last Name"
name="lastname"
required
/>
</label>
<label class="btn-block"><span>Company:</span>
<input
type="text"
class="form-control"
placeholder="Your Company"
name="company"
required
/>
</label>
<label class="btn-block"><span>Phone:</span>
<input
type="text"
class="form-control"
placeholder="Your Phone"
name="phone"
required
/>
</label>
<label class="btn-block"><span>Email:</span>
<input
type="text"
class="form-control"
placeholder="Your Email Address"
name="email"
required
/>
</label>
<label class="btn-block"><span>Type of Contractor:</span></label>
<label class="btn-block">
<input
type="radio"
name="contractor_type"
value="Primarily Residential"
required
/>
<span>Primarily Residential</span>
</label>
<label class="btn-block">
<input
type="radio"
name="contractor_type"
value="Primarily Commercial"
required
/>
<span>Primarily Commercial</span>
</label>
<label class="btn-block">
<input
type="radio"
name="contractor_type"
value="Both"
required
/>
<span>Both</span>
</label>
<label class="btn-block">
<input
type="radio"
name="contractor_type"
value="Not a Contractor"
required
/>
<span>Not a Contractor</span>
</label>
<div style="text-align: center;">
<button
class="btn mt-3"
type="submit"
style="color: #fff; background: ' . $buttonColor . ';"
>' . $buttonText . '</button>
</div>
</form>
';
// replace gravity form with default lead form
$content = preg_replace("#\[gravityform[^\]]*\]#", $module, $content);
$content = $this->check_modules($content);
}
return $content;
}
public function check_modules ($content)
{
if (is_string($content)) {
$html = $content;
} else {
$html = $content->getContentFull();
}
// first replace any empty <p> tags - from wysiwyg
$html = preg_replace("#<p>[^<]*\[{#", "[{", $html);
$html = preg_replace("#}\][^<]*</p>#", "}]", $html);
// TODO - only replace modules based on author roles
// ...
// render any container elements
if (strpos($html, "[{div") !== false) {
$html = preg_replace_callback (
"#\[{div(.+?)}\]#",
array ($this, "renderDiv"),
$html
);
// add all closing tags
$html = str_replace("[{/div}]", "</div>", $html);
}
// render any modules
if (strpos($html, "[{module") !== false) {
// render any modules included in entity content
$html = preg_replace_callback (
"#\[{module(.+?)}\]#",
array ($this, "renderModule"),
$html
);
}
return $html;
}
public function renderDiv ($match)
{
$match = $match[1];
return "<div {$match}>";
}
public function renderModule ($match)
{
// we want the attributes
$match = $match[1];
$match = new SimpleXMLElement("<temp $match />");
$match = current($match->attributes());
return $this->show_module($match);
}
public function show_media ($obj)
{
// TODO
}
/*
* ... pretty ugly - would be cleaner to add into the entity with a $entity->getURL() - for all content types...
*
* @param {many} $link
*/
public function get_href ($link)
{
$class = \get_class($link);
$class = explode("\\", $class);
$class = array_pop($class);
// if content class - get the href from the content helper
if ($class == "Content") {
return $this->contentHelper->getHref($link);
}
$href = "";
switch($link->getType()) {
case "content":
// grab the content URI
$ref = $link->getRefContent();
$href = $this->contentHelper->getHrefById($ref->getId());
break;
case "media":
break;
case "external":
$href = $link->getRefExternal();
break;
}
return $href;
}
public function show_module ($attrs = array())
{
if (is_string($attrs)) {
die(__FILE__.":".__LINE__." - Needs Implemented");
}
// include any used keys to prevent twig errors
$attrs = array_merge(array(
"id" => "",
"slug" => "",
"type" => "",
"form" => "",
"title" => "",
"content" => "",
"position" => "",
"customer_level_or_higher" => "",
), $attrs);
$html = "";
try {
switch ($attrs["type"]) {
case "mediagroup":
$html = $this->getMediaGroup($attrs);
/*
$module = $this->mediaHelper->getMediaGroupByPosition($attrs["position"]);
$attrs["data"] = $module;
$tmpl = $this->twig->load("elements/media-group.html.twig");
$html = $tmpl->render(array(
"module" => $attrs
/ *
"attr" => $attrs,
"mediagroup" => $module,
* /
));
*/
break;
case "gallery":
$html = $this->getGallery($attrs);
break;
case "category":
$attrs = array_merge(array ("slug" => "", "length" => ""), $attrs);
$module = $this->contentHelper->getPostsByCategory($attrs["slug"], $attrs["length"]);
$tmpl = $this->twig->load("modules/category-list.html.twig");
$html = $tmpl->render(array(
"attr" => $attrs,
"posts" => $module,
));
break;
/*
case "customer":
$attrs = array_merge(array ("slug" => "", "length" => ""), $attrs);
$module = $this->contentHelper->getPostsByCategory($attrs["slug"], $attrs["length"]);
$tmpl = $this->twig->load("modules/category-list.html.twig");
$html = $tmpl->render(array(
"attr" => $attrs,
"posts" => $module,
));
break;
*/
case "customers":
$html = $this->getCustomerList($attrs);
break;
case "title":
$tmpl = $this->twig->load("modules/module-title.html.twig");
$html = $tmpl->render(array(
"attr" => $attrs,
));
break;
case "html":
$tmpl = $this->twig->load("modules/module-html.html.twig");
$html = $tmpl->render(array(
"attr" => $attrs
));
break;
/*
Do we still need these? Merge 6/12
case "signup":
$tmpl = $this->twig->load("modules/enews-signup-home.html.twig");
$html = $tmpl->render();
break;
case "latest_classifieds":
$tmpl = $this->twig->load("modules/latest-classifieds.html.twig");
$html = $tmpl->render(array(
"attr" => $attrs,
));
break;
*/
case "form":
$attrs = array_merge(array ("slug" => ""), $attrs);
switch($attrs["slug"]) {
case "lead":
$tmpl = $this->twig->load("forms/temp.html.twig");
if(isset($attrs["fields"])) {
$html = $tmpl->render(array(
"fields" => $attrs["fields"],
));
}
else {
//should set default fields that all forms will use
$html = $tmpl->render(array(
"fields" => "",
));
}
break;
}
break;
case "form2":
$tmpl = $this->twig->load("forms/default.html.twig");
$html = $tmpl->render(array(
"module" => $attrs,
));
break;
/*
case "signup":
$tmpl = $this->twig->load("modules/sign-up.html.twig");
$html = $tmpl->render(array(
"module" => $attrs,
));
break;
case "signin":
$tmpl = $this->twig->load("modules/sign-in.html.twig");
$html = $tmpl->render(array(
"module" => $attrs,
));
break;
*/
case "sign-in":
$tmpl = $this->twig->load("modules/static-sign-in.html.twig");
$html = $tmpl->render(array(
"module" => $attrs,
));
break;
case "mobile-sign-in":
$tmpl = $this->twig->load("modules/mobile-sign-in.html.twig");
$html = $tmpl->render(array(
"module" => $attrs,
));
break;
case "mobile-virus-alert":
$tmpl = $this->twig->load("modules/mobile-virus-alert.html.twig");
$html = $tmpl->render(array(
"module" => $attrs,
));
break;
case "enews-home":
$tmpl = $this->twig->load("modules/enews-signup-home.html.twig");
$html = $tmpl->render(array(
"module" => $attrs,
));
break;
case "enews":
$tmpl = $this->twig->load("modules/enews-signup.html.twig");
$html = $tmpl->render(array(
"module" => $attrs,
));
break;
case "up-to-the-minute":
$tmpl = $this->twig->load("modules/up-to-the-minute.html.twig");
$html = $tmpl->render(array(
"module" => $attrs,
));
break;
case "gallery":
$html = $this->getGallery($attrs);
break;
case "content":
$type = isset($attrs["ctype"]) ? $attrs["ctype"] : "";
$attrs["type"] = $type;
$html = $this->getContent($attrs);
break;
case "aar-base-sidebar":
$tmpl = $this->twig->load("modules/aar-base-sidebar.html.twig");
$html = $tmpl->render(array(
"module" => $attrs,
));
break;
case "aar-social":
$tmpl = $this->twig->load("modules/aar-social.html.twig");
$html = $tmpl->render(array(
"module" => $attrs,
));
break;
case "ad":
$html = $this->getAds($attrs);
break;
}
} catch (\Exception $e) {
if (get_class($e) === "App\Exception\ResourceNotFoundException") {
return "";
}
// re-throw otherwise
throw $e;
}
return $html;
}
// public function show_menu ($twig, $position = "")
public function show_menu ($position = "")
{
$menus = null;
try {
$menus = $this->menuHelper->getMenusByPosition($position);
} catch (\Exception $e) {
if (get_class($e) === "App\Exception\ResourceNotFoundException") {
return "";
}
// re-throw otherwise
throw $e;
}
$tmpl = $this->twig->load("elements/menu.html.twig");
return $tmpl->render(array("menus" => $menus));
/*
try {
return $this->menuHelper->buildHtmlByPosition($position);
} catch (ResourceNotFoundException $e) {
// fail silently - but ... not working ...
return "";
} catch (\Exception $e) {
// - strange that the custom exception catching is not working above...
if (get_class($e) === "App\Exception\ResourceNotFoundException") {
return "";
}
// re-throw otherwise
throw $e;
}
*/
}
public function get_attributes ($attrs = "")
{
return $this->defaultHelper->attributeMapToString($attrs);
}
public function rcsInclude ($type = "", $id = "", $attr = "")
{
$ref = null;
try {
switch ($type) {
case "content" :
return "content";
case "menu":
return $this->menuHelper->buildHTMLById($id);
}
} catch (ResouceNotFoundException $e) {
// fail silently
return "";
}
}
public function snippetFilter($description, $length = 320)
{
$description = strip_tags($description);
if(strlen($description) > $length) {
return substr($description, 0, $length) . "...";
}
else {
return $description;
}
}
public function externalLinkFilter($url)
{
// The directory 'email' field can be an email address or a url, so adding to use there
if (filter_var($url, FILTER_VALIDATE_EMAIL)) {
return "mailto:" . $url;
}
if(!preg_match("~https?://~i", $url)) {
return "http://" . $url;
}
return $url;
}
public function timezoneFilter($tz)
{
switch($tz){
case "America/New_York":
return "EST";
case "America/Los_Angeles":
return "PST";
case "America/Chicago":
return "CST";
case "America/Denver":
case "America/Phoenix":
return "MST";
default:
return "";
}
/*
$description = strip_tags($description);
if(strlen($description) > $length) {
return substr($description, 0, $length) . "...";
}
else {
return $description;
}*/
}
public function rcsDateFormat($date)
{
return str_replace(["AM", "PM"], ["a.m.", "p.m."], date("F j, Y \\a\\t g:i A", strtotime($date)));
}
public function rawTwig($content, $data = array())
{
$tmpl = $this->twig->createTemplate($content);
$html = $tmpl->render($data);
return $html;
}
public function twigRandom($stuff)
{
$stuff = $stuff->toArray();
shuffle($stuff);
return new ArrayCollection($stuff);
}
public function post_age_format($date)
{
$return = "";
if($date->y > 0) {
$return .= $date->y . " year" . ($date->y == 1 ? "" : "s");
if($date->m > 0) {
$return .= ", ". $date->m . " month" . ($date->m == 1 ? "" : "s");
}
}
else if($date->m > 0) {
$return .= $date->m . " month" . ($date->m == 1 ? "" : "s");
if($date->d >= 7) {
$return .= ", ". floor($date->d / 7) . " week" . (floor($date->d / 7) == 1 ? "" : "s");
}
}
else if($date->d >= 7) {
$return .= floor($date->d / 7) . " week" . (floor($date->d / 7) == 1 ? "" : "s");
if(($date->d % 7) > 0) {
$return .= ", ". ($date->d % 7) . " day" . (($date->d % 7) == 1 ? "" : "s");
}
}
else if($date->d > 0) {
$return .= $date->d . " day" . ($date->d == 1 ? "" : "s");
if($date->h > 0) {
$return .= ", ". $date->h . " hour" . ($date->h == 1 ? "" : "s");
}
}
else if($date->h > 0) {
$return .= $date->h . " hour" . ($date->h == 1 ? "" : "s");
if($date->i > 0) {
$return .= ", ". $date->i . " minute" . ($date->i == 1 ? "" : "s");
}
}
else if($date->i > 0) {
$return .= $date->i . " minute" . ($date->i == 1 ? "" : "s");
}
else {
return "Just now";
}
return $return . " ago";
//return var_dump($date);
//$date2 = strtotime($date);
//return date_format($date2,"Y/m/d");
}
public function getFilters()
{
// add custom filters below
return array(
// new TwigFilter('price', array($this, 'priceFilter')),
new TwigFilter (
"dump",
array($this, "flatDump")
),
new TwigFilter (
"wordpress",
array ($this, "wordpress")
),
new TwigFilter (
"builder",
array ($this, "builder")
),
new TwigFilter (
"snippet",
array ($this, "snippetFilter")
),
new TwigFilter (
"external_link",
array ($this, "externalLinkFilter")
),
new TwigFilter (
"usd",
array ($this, "usd")
),
new TwigFilter (
"timezone",
array ($this, "timezoneFilter")
),
new TwigFilter (
"rcsDateFormat",
array ($this, "rcsDateFormat")
),
/*new TwigFilter (
"rawTwig",
array ($this, "rawTwig")
),*/
// sort random twig fitler
new TwigFilter (
"shuffle",
array ($this, "twigRandom")
),
);
}
public function builder ($content = "")
{
try {
$content = json_decode($content, true);
$return = array ();
foreach ($content as $row) {
$return[] = "<div class='row'>";
foreach ($row as $col) {
$return[] = "<div class='col-md-{$col["c"]}'>";
$return[] = $col["t"];
$return[] = "</div>";
}
$return[] = "</div>";
}
}
catch (\Exception $e) {
throw $e;
}
// run through the wordpress filter...
return $this->wordpress(implode("", $return));
}
public function flatDump ($data = "")
{
$data = \Doctrine\Common\Util\Debug::dump($data);
return $data;
}
/**
* https://developer.wordpress.org/reference/functions/get_html_split_regex/
*/
protected function get_html_split_regex() {
static $regex;
if ( ! isset( $regex ) ) {
$comments =
'!' // Start of comment, after the <.
. '(?:' // Unroll the loop: Consume everything until --> is found.
. '-(?!->)' // Dash not followed by end of comment.
. '[^\-]*+' // Consume non-dashes.
. ')*+' // Loop possessively.
. '(?:-->)?'; // End of comment. If not found, match all input.
$cdata =
'!\[CDATA\[' // Start of comment, after the <.
. '[^\]]*+' // Consume non-].
. '(?:' // Unroll the loop: Consume everything until ]]> is found.
. '](?!]>)' // One ] not followed by end of comment.
. '[^\]]*+' // Consume non-].
. ')*+' // Loop possessively.
. '(?:]]>)?'; // End of comment. If not found, match all input.
$escaped =
'(?=' // Is the element escaped?
. '!--'
. '|'
. '!\[CDATA\['
. ')'
. '(?(?=!-)' // If yes, which type?
. $comments
. '|'
. $cdata
. ')';
$regex =
'/(' // Capture the entire match.
. '<' // Find start of element.
. '(?' // Conditional expression follows.
. $escaped // Find end of escaped element.
. '|' // ... else ...
. '[^>]*>?' // Find end of normal element.
. ')'
. ')/';
}
return $regex;
}
/**
* https://developer.wordpress.org/reference/functions/wp_html_split/
*/
protected function wp_html_split( $input ) {
return preg_split( $this->get_html_split_regex(), $input, -1, PREG_SPLIT_DELIM_CAPTURE );
}
/**
* https://developer.wordpress.org/reference/functions/wp_replace_in_html_tags/
*/
protected function wp_replace_in_html_tags( $haystack, $replace_pairs ) {
// Find all elements.
$textarr = $this->wp_html_split( $haystack );
$changed = false;
// Optimize when searching for one item.
if ( 1 === count( $replace_pairs ) ) {
// Extract $needle and $replace.
foreach ( $replace_pairs as $needle => $replace );
// Loop through delimiters (elements) only.
for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
if ( false !== strpos( $textarr[$i], $needle ) ) {
$textarr[$i] = str_replace( $needle, $replace, $textarr[$i] );
$changed = true;
}
}
} else {
// Extract all $needles.
$needles = array_keys( $replace_pairs );
// Loop through delimiters (elements) only.
for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
foreach ( $needles as $needle ) {
if ( false !== strpos( $textarr[$i], $needle ) ) {
$textarr[$i] = strtr( $textarr[$i], $replace_pairs );
$changed = true;
// After one strtr() break out of the foreach loop and look at next element.
break;
}
}
}
}
if ( $changed ) {
$haystack = implode( $textarr );
}
return $haystack;
}
/**
* https://developer.wordpress.org/reference/functions/wpautop/
*/
public function wordpress ($pee = "", $extra_attrs = array ())
{
try {
$br = false; // ?
$pre_tags = array();
if ( trim($pee) === '' )
return '';
// Just to make things a little easier, pad the end.
$pee = $pee . "\n";
/*
* Pre tags shouldn't be touched by autop.
* Replace pre tags with placeholders and bring them back after autop.
*/
if ( strpos($pee, '<pre') !== false ) {
$pee_parts = explode( '</pre>', $pee );
$last_pee = array_pop($pee_parts);
$pee = '';
$i = 0;
foreach ( $pee_parts as $pee_part ) {
$start = strpos($pee_part, '<pre');
// Malformed html?
if ( $start === false ) {
$pee .= $pee_part;
continue;
}
$name = "<pre wp-pre-tag-$i></pre>";
$pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
$pee .= substr( $pee_part, 0, $start ) . $name;
$i++;
}
$pee .= $last_pee;
}
// Change multiple <br>s into two line breaks, which will turn into paragraphs.
$pee = preg_replace('|<br\s*/?>\s*<br\s*/?>|', "\n\n", $pee);
$allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
// Add a double line break above block-level opening tags.
$pee = preg_replace('!(<' . $allblocks . '[\s/>])!', "\n\n$1", $pee);
// Add a double line break below block-level closing tags.
$pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
// Standardize newline characters to "\n".
$pee = str_replace(array("\r\n", "\r"), "\n", $pee);
// Find newlines in all elements and add placeholders.
$pee = $this->wp_replace_in_html_tags( $pee, array( "\n" => " <!-- wpnl --> " ) );
// Collapse line breaks before and after <option> elements so they don't get autop'd.
if ( strpos( $pee, '<option' ) !== false ) {
$pee = preg_replace( '|\s*<option|', '<option', $pee );
$pee = preg_replace( '|</option>\s*|', '</option>', $pee );
}
/*
* Collapse line breaks inside <object> elements, before <param> and <embed> elements
* so they don't get autop'd.
*/
if ( strpos( $pee, '</object>' ) !== false ) {
$pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
$pee = preg_replace( '|\s*</object>|', '</object>', $pee );
$pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
}
/*
* Collapse line breaks inside <audio> and <video> elements,
* before and after <source> and <track> elements.
*/
if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
$pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
$pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
$pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
}
// Collapse line breaks before and after <figcaption> elements.
if ( strpos( $pee, '<figcaption' ) !== false ) {
$pee = preg_replace( '|\s*(<figcaption[^>]*>)|', '$1', $pee );
$pee = preg_replace( '|</figcaption>\s*|', '</figcaption>', $pee );
}
// Remove more than two contiguous line breaks.
$pee = preg_replace("/\n\n+/", "\n\n", $pee);
// Split up the contents into an array of strings, separated by double line breaks.
$pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
// Reset $pee prior to rebuilding.
$pee = '';
// Rebuild the content as a string, wrapping every bit with a <p>.
foreach ( $pees as $tinkle ) {
$pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
}
// Under certain strange conditions it could create a P of entirely whitespace.
$pee = preg_replace('|<p>\s*</p>|', '', $pee);
// Add a closing <p> inside <div>, <address>, or <form> tag if missing.
$pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
// If an opening or closing block element tag is wrapped in a <p>, unwrap it.
$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
// In some cases <li> may get wrapped in <p>, fix them.
$pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee);
// If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
$pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
$pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
// If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
// If an opening or closing block element tag is followed by a closing <p> tag, remove it.
$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
// Optionally insert line breaks.
if ( $br ) {
// Replace newlines that shouldn't be touched with a placeholder.
$pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
// Normalize <br>
$pee = str_replace( array( '<br>', '<br/>' ), '<br />', $pee );
// Replace any new line characters that aren't preceded by a <br /> with a <br />.
$pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee);
// Replace newline placeholders with newlines.
$pee = str_replace('<WPPreserveNewline />', "\n", $pee);
}
// If a <br /> tag is after an opening or closing block tag, remove it.
$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
// If a <br /> tag is before a subset of opening or closing block tags, remove it.
$pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
$pee = preg_replace( "|\n</p>$|", '</p>', $pee );
// Replace placeholder <pre> tags with their original content.
if ( !empty($pre_tags) )
$pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
// Restore newlines in all elements.
if ( false !== strpos( $pee, '<!-- wpnl -->' ) ) {
$pee = str_replace( array( ' <!-- wpnl --> ', '<!-- wpnl -->' ), "\n", $pee );
}
// WordPress shortcodes come in 2 flavors ...
// EWG 12/20: New tag shortcodes
//TEMPORARY: running twice until I can get it to run recursively w/o crashing
$pee = $this->tagShortcodes($pee);
$pee = $this->tagShortcodes($pee);
/*
preg_match_all('/\[url\](.*?)\[\/url\]/s', $pee, $matches);
if (!empty($matches)) {
foreach ($matches as $val) {
$pee = str_replace($val[0], "<a href='$val[2]' target='_blank'>".$val[2]."</a>", $pee);
}
}
*/
// tag shortcodes
preg_match_all("#\[([^\[]*)\[\/#", $pee, $matches);
if (!empty($matches[1])) {
foreach ($matches[1] as $i => $shortcode) {
$temp = explode(" ", $shortcode);
$type = array_shift($temp);
$attr = implode(" ", $temp);
// $attr = htmlspecialchars_decode($attr);
$attr = str_replace(" ", " ", $attr);
$attr = html_entity_decode($attr);
$pos = strpos($attr, "]");
$text = substr($attr, $pos + 1);
$attr = substr($attr, 0, $pos);
try {
$str = "<temp $attr />";
$xml = new SimpleXMLElement($str);
$attr = current($xml->attributes());
} catch (\Exception $e) {
// echo "<pre>";
// var_dump($e->getMessage(), $str);
// exit;
}
if (is_array($attr)) {
$attr["html"] = $text;
}
/*
echo "<pre>";
var_dump($attr);
exit;
*/
switch ($type) {
case "caption":
$pee = str_replace(
"{$matches[0][$i]}$type]",
$this->getCaption($attr),
$pee
);
break;
}
}
}
// members and non-members shortcodes. Only displays these sections for RCS-Club members or non-members
$user = $this->security->getUser();
$isMember = false;
if($user && $user->isMember()) {
$isMember = true;
}
preg_match_all("'\[members\](.*?)\[/members\]'si", $pee, $matches);
if (!empty($matches[1])) {
foreach ($matches[1] as $i => $match) {
if($isMember) {
$replace = $matches[1][$i];
}
else {
$replace = "";
}
$pee = str_replace(
$matches[0][$i],
$replace,
$pee
);
}
}
preg_match_all("'\[non-members\](.*?)\[/non-members\]'si", $pee, $matches);
if (!empty($matches[1])) {
foreach ($matches[1] as $i => $match) {
if(!$isMember) {
$replace = $matches[1][$i];
}
else {
$replace = "";
}
$pee = str_replace(
$matches[0][$i],
$replace,
$pee
);
}
}
// self closing shortcodes (not really working? see the members / non-members above for more specific preg_match that works)
preg_match_all("/\[([^\]]*)]/", $pee, $matches);
if (!empty($matches[1])) {
foreach ($matches[1] as $i => $shortcode) {
$temp = explode(" ", $shortcode);
$type = array_shift($temp);
$attr = implode(" ", $temp);
$attr = str_replace(" ", " ", $attr);
$attr = html_entity_decode($attr);
$attr = str_replace("&", "&", $attr);
//$attr = str_replace(array('&', '<', '>', '\'', '"'), array('&', '<', '>', ''', '"'), $attr);
try {
$str = "<temp $attr />";
$xml = new SimpleXMLElement($str);
$attr = current($xml->attributes());
} catch (\Exception $e) {
// echo "<pre>";
// var_dump($e->getMessage(), $str);
// exit;
}
switch ($type) {
// FontAwesome shortcodes
case "fa":
$class = isset($attr["class"]) ? $attr["class"] : "";
$pee = str_replace(
$matches[0][$i],
"<i class=\"fa fa-{$attr["type"]} {$class}\"></i>",
$pee
);
break;
//Adding some basic tags here...
//Should be in non self closing shortcodes section above but can't get those to work at the moment
case "b":
$pee = str_replace($matches[0][$i], "<b>", $pee);
break;
case "/b":
$pee = str_replace($matches[0][$i], "</b>", $pee);
break;
case "i":
$pee = str_replace($matches[0][$i], "<i>", $pee);
break;
case "/i":
$pee = str_replace($matches[0][$i], "</i>", $pee);
break;
case "u":
$pee = str_replace($matches[0][$i], "<u>", $pee);
break;
case "/u":
$pee = str_replace($matches[0][$i], "</u>", $pee);
break;
case "quote/":
$pee = str_replace($matches[0][$i], "<blockquote>", $pee);
break;
case "/quote":
$pee = str_replace($matches[0][$i], "</blockquote>", $pee);
break;
case "embed":
$pee = str_replace($matches[0][$i], "<iframe width='560' height='315' src='", $pee);
break;
case "/embed":
$pee = str_replace($matches[0][$i], "' frameborder='0' allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>", $pee);
break;
// Gravity Forms ...
// for time being simply hard code all fields ...
// will create a new module that will allow adding custom fields ... see below
case "gravityform":
$pee = str_replace(
$matches[0][$i],
$this->getGravityForm($extra_attrs, $attr),
$pee
);
break;
case "contact-form-7":
$pee = str_replace(
$matches[0][$i],
$this->getContactForm($extra_attrs, $attr),
$pee
);
break;
// To replace the above forms ...
case "symform":
$pee = str_replace(
$matches[0][$i],
$this->getSymfonyForm($attr),
$pee
);
break;
case "content":
$pee = str_replace(
$matches[0][$i],
$this->getContent($attr),
$pee
);
break;
case "category":
$pee = str_replace(
$matches[0][$i],
$this->getCategoryList($attr),
$pee
);
break;
case "customers":
$pee = str_replace(
$matches[0][$i],
$this->getCustomerList($attr),
$pee
);
break;
case "gallery":
$pee = str_replace(
$matches[0][$i],
$this->getGallery($attr),
$pee
);
break;
case "mediagroup":
$pee = str_replace(
$matches[0][$i],
$this->getMediaGroup($attr),
$pee
);
break;
case "twitter":
$pee = str_replace(
$matches[0][$i],
$this->getTweets($attr),
$pee
);
break;
case "facebook":
$pee = str_replace(
$matches[0][$i],
$this->getFBPost($attr),
$pee
);
break;
case "poll":
$pee = str_replace(
$matches[0][$i],
$this->getPoll($attr),
$pee
);
break;
case "ad":
$pee = str_replace(
$matches[0][$i],
$this->getAds($attr),
$pee
);
break;
}
}
}
} catch (Exception $e) {
}
// for time being replace old events until we completely remove the system...
//
return $pee;
}
public function getCaption ($attr = array())
{
$html = "";
try {
$tmpl = $this->twig->load("modules/captions.html.twig");
$html = $tmpl->render(array(
"module" => $attr,
));
} catch (Exception $e) {
}
return $html;
}
public function getCategoryList ($attr = array ())
{
$html = "";
try {
if (isset($attr["taxonomy"])) {
$categories = $this->categoryHelper->getCategoriesByTaxonomy ($attr["taxonomy"]);
$attr["data"] = $categories;
$tmpl = $this->twig->load("modules/category-list.html.twig");
$html = $tmpl->render(array(
"module" => $attr
));
}
} catch (Exception $e) {
}
return $html;
}
//Currently just used to get customers who have content of a certain type, and display a list that links to their content pages
//(Made for the RLW page's sidebar)
public function getCustomerList ($attr = array ())
{
$html = "";
try {
if (isset($attr["ctype"])) {
$customers = $this->customerHelper->getCustomersByContentType ($attr["ctype"]);
$attr["data"] = $customers;
$tmpl = $this->twig->load("modules/customer-list.html.twig");
$html = $tmpl->render(array(
"module" => $attr
));
}
} catch (Exception $e) {
}
return $html;
}
protected function getGallery ($attr = array ())
{
$attr = array_merge([
"columns" => 3,
"link" => "file",
"ids" => [],
"gallerySlug" => "",
"links" => [],
"idtype" => "",
"limit" => ""
], $attr);
$attr["class"] = !empty($attr["class"]) ? $attr["class"] . " gallery" : "gallery";
if (!empty($attr["ids"]) && is_string($attr["ids"])) {
$attr["ids"] = explode(",", $attr["ids"]);
}
if (!empty($attr["links"]) && is_string($attr["links"])) {
$attr["links"] = array_map('trim', explode(",", $attr["links"]));
}
$limit = (int) $attr["limit"];
$data = array ();
foreach ($attr["ids"] as $id) {
try {
if($attr["idtype"] == "old") {
$media = $this->mediaHelper->getMediaByOldId($id);
}
else {
$media = $this->mediaHelper->getMediaById($id);
}
$data[] = $media;
} catch (\Exception $e) {
// ignore
}
}
$attr["mitems"] = [];
if(!empty($attr["gallerySlug"]) && $attr["gallerySlug"]) {
$data = [];//media
$mitems = [];
$gallery = $this->contentHelper->getContentBySlug(Content::GALLERY, $attr["gallerySlug"]);
$mediaIds = [];
foreach($gallery->getMediaGroupContainers() as $mgroupc) {
$mgroup = $mgroupc->getMediaGroup();
if($mgroup) {
foreach($mgroup->getMediaGroupItems() as $mitem) {
$mitems[] = $mitem;
$media = $mitem->getMedia();
if($media) {
$data[] = $media;
}
}
}
}
$attr["mitems"] = $mitems;
}
if($limit && $limit < count($data)) {
$rand = $this->getUniqueRandomNumbers(0, count($data)-1, $limit);
$links = array();
$attr["data"] = array();
foreach($rand as $r) {
$attr["data"][] = $data[$r];
if($attr["links"]) {
$links[] = $attr["links"][$r];
}
}
$attr["links"] = $links;
}
else {
$attr["data"] = $data;
}
$tmpl = $this->twig->load("modules/gallery-display.html.twig");
$html = $tmpl->render(array(
"module" => $attr,
));
return $html;
}
protected function getContactForm ($meta = array (), $attr = array ())
{
$module = "";
// hack to convert current gravity forms to default lead form
$buttonColor = "#F1592A";
$buttonText = "Submit";
if($attr["id"] == 10537) { //contact us
$module = implode(" ", array (
'<form method="post" class="py-4">',
'<label class="btn-block"><span>First Name:</span>
<input
type="text"
class="form-control"
placeholder="Your First Name"
name="contact[firstname]"
required
/>
</label>',
'<label class="btn-block"><span>Last Name:</span>
<input
type="text"
class="form-control"
placeholder="Your Last Name"
name="contact[lastname]"
required
/>
</label>',
'<label class="btn-block"><span>Email:</span>
<input
type="text"
class="form-control"
placeholder="Your Email Address"
name="contact[email]"
required
/>
</label>',
'<label class="btn-block"><span>State / Region:</span>
<input
type="text"
class="form-control"
placeholder="Your State / Region"
name="contact[state]"
required
/>
</label>',
'<label class="btn-block"><span>ZIP / Postal Code:</span>
<input
type="text"
class="form-control"
placeholder="Your ZIP Code"
name="contact[zip]"
required
/>
</label>',
'<label class="btn-block"><span>Subject:</span>
<input
type="text"
class="form-control"
placeholder="The Subject of Your Message"
name="contact[subject]"
required
/>
</label>',
'<label class="btn-block"><span>Your Message:</span>
<textarea
type="text"
class="form-control"
placeholder="Your Message"
name="contact[message]"
required
></textarea>
</label>',
'<div class="form-row g-recaptcha" data-sitekey="6LeEIlMUAAAAAGhdmJJLdJHPxaWx2GqBjber5n6B"></div>',
'<div style="text-align: center;">
<button
class="btn mt-3"
type="submit"
style="color: #fff; background: ' . $buttonColor . ';"
>' . $buttonText . '</button>
</div>
</form>',
));
}
elseif($attr["id"] == 8457) { //have a question
$module = implode(" ", array (
'<form method="post" class="py-4" enctype="multipart/form-data">',
'<label class="btn-block"><span>First Name:</span>
<input
type="text"
class="form-control"
placeholder="Your First Name"
name="contact[firstname]"
required
/>
</label>',
'<label class="btn-block"><span>Last Name:</span>
<input
type="text"
class="form-control"
placeholder="Your Last Name"
name="contact[lastname]"
required
/>
</label>',
'<label class="btn-block"><span>Email:</span>
<input
type="text"
class="form-control"
placeholder="Your Email Address"
name="contact[email]"
required
/>
</label>',
'<label class="btn-block"><span>Phone (to help with complicated answers):</span>
<input
type="text"
class="form-control"
placeholder="Your Phone"
name="contact[phone]"
required
/>
</label>',
'<label class="btn-block"><span>Zip Code (to determine area of country and requirements):</span>
<input
type="text"
class="form-control"
placeholder="Your Zip Code"
name="contact[zip]"
required
/>
</label>',
'<label class="btn-block"><span>State / Region:</span>
<input
type="text"
class="form-control"
placeholder="Your State / Region"
name="contact[state]"
required
/>
</label>',
'<label class="btn-block"><span>What\'s your Question?:</span>
<textarea
type="text"
class="form-control"
placeholder="Your Question"
name="contact[question]"
required
></textarea>
</label>',
'<label class="btn-block"><span>Photo of the problem area:</span>
<input type="file" class="form-control-file" id="photo" name="photo">
</label>',
'<div class="form-row g-recaptcha" data-sitekey="6LeEIlMUAAAAAGhdmJJLdJHPxaWx2GqBjber5n6B"></div>',
'<div style="text-align: center;">
<button
class="btn mt-3"
type="submit"
style="color: #fff; background: ' . $buttonColor . ';"
>' . $buttonText . '</button>
</div>
</form>',
));
}
return $module;
}
protected function getGravityForm ($meta = array (), $attr = array ())
{
// hack to convert current gravity forms to default lead form
$buttonColor = "#A41822";
if (!empty($meta["btn_color"])) {
$buttonColor = $meta["btn_color"];
}
$buttonText = "Submit";
if (!empty($meta["btn_text"])) {
$buttonText = $meta["btn_text"];
}
/* - Too complex for now - we will replace with a form building entity soon ...
$factory = Forms::createFormFactory();
$form = $factory
->create(
DirectoryLeadType::class,
new Lead()
)->createView();
$module = $this->show_module(array(
"type" => "form2",
"form" => $form,
));
*/
// for time being just create static default form
if($attr["id"] == 2) { //contact us
$module = implode(" ", array (
'<form method="post" class="py-4">',
'<label class="btn-block"><span>First Name:</span>
<input
type="text"
class="form-control"
placeholder="Your First Name"
name="contact[firstname]"
required
/>
</label>',
'<label class="btn-block"><span>Last Name:</span>
<input
type="text"
class="form-control"
placeholder="Your Last Name"
name="contact[lastname]"
required
/>
</label>',
'<label class="btn-block"><span>Email:</span>
<input
type="text"
class="form-control"
placeholder="Your Email Address"
name="contact[email]"
required
/>
</label>',
'<label class="btn-block"><span>State / Region:</span>
<input
type="text"
class="form-control"
placeholder="Your State / Region"
name="contact[state]"
required
/>
</label>',
'<label class="btn-block"><span>ZIP / Postal Code:</span>
<input
type="text"
class="form-control"
placeholder="Your ZIP Code"
name="contact[zip]"
required
/>
</label>',
'<label class="btn-block"><span>Subject:</span>
<input
type="text"
class="form-control"
placeholder="The Subject of Your Message"
name="contact[subject]"
required
/>
</label>',
'<label class="btn-block"><span>Your Message:</span>
<textarea
type="text"
class="form-control"
placeholder="Your Message"
name="contact[message]"
required
></textarea>
</label>',
'<div class="form-row g-recaptcha" data-sitekey="6LeEIlMUAAAAAGhdmJJLdJHPxaWx2GqBjber5n6B"></div>',
'<div style="text-align: center;">
<button
class="btn mt-3"
type="submit"
style="color: #fff; background: ' . $buttonColor . ';"
>' . $buttonText . '</button>
</div>
</form>',
));
}
elseif($attr["id"] == 3) { //week in review sign up
$module = implode(" ", array (
'<form method="post" class="py-4">',
'<div class="row">',
'<div class="col-sm-6">',
'<label class="btn-block"><span>First Name:</span>
<input
type="text"
class="form-control"
placeholder="Your First Name"
name="lead[firstname]"
required
/>
</label>',
'</div>',
'<div class="col-sm-6">',
'<label class="btn-block"><span>Last Name:</span>
<input
type="text"
class="form-control"
placeholder="Your Last Name"
name="lead[lastname]"
required
/>
</label>',
'</div>',
'</div>',
'<label class="btn-block"><span>Email:</span>
<input
type="text"
class="form-control"
placeholder="Your Email Address"
name="lead[email]"
required
/>
</label>',
'<label class="btn-block"><span>Company:</span>
<input
type="text"
class="form-control"
placeholder="Your Company"
name="lead[company]"
required
/>
</label>',
'<label class="btn-block"><span>Type of Work Performed:</span>
<select
class="form-control"
name="lead[contractor_type]"
required
>
<option value="Primarily Commercial">Primarily Commercial</option>
<option value="Primarily Residential">Primarily Residential</option>
<option value="Both">Both</option>
<option value="Not a Contractor">Not a Contractor</option>
</select>
</label>',
'<label class="btn-block"><span>Country:</span></label>
<label class="btn-block">
<input
type="radio"
name="lead[country]"
value="United States"
checked
required
/>
<span>United States</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[country]"
value="Canada"
required
/>
<span>Canada</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[country]"
value="European Countries"
required
/>
<span>European Countries</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[country]"
value="Other"
required
/>
<span><input
type="text"
placeholder="Other"
name="lead[country_other]"
/></span>
</label>',
'<label class="btn-block"><span>Business Type:</span>
<select
class="form-control"
name="lead[business_type]"
required
>
<option value="Roofing Contractor">Roofing Contractor</option>
<option value="Exterior/General Contractor">Exterior/General Contractor</option>
<option value="Distributor">Distributor</option>
<option value="Manufacturer/Business Services">Manufacturer/Business Services</option>
<option value="Other">Other</option>
</select>
</label>',
'<div class="form-row g-recaptcha" data-sitekey="6LeEIlMUAAAAAGhdmJJLdJHPxaWx2GqBjber5n6B"></div>',
'<div style="text-align: center;">
<button
class="btn mt-3"
type="submit"
style="color: #fff; background: ' . $buttonColor . ';"
>' . $buttonText . '</button>
</div>
</form>',
));
}
elseif($attr["id"] == 4) { //membership
$module = implode(" ", array (
'<form method="post" class="py-4">',
'<label class="btn-block"><span>First Name:</span>
<input
type="text"
class="form-control"
placeholder="Your First Name"
name="contact[firstname]"
required
/>
</label>',
'<label class="btn-block"><span>Last Name:</span>
<input
type="text"
class="form-control"
placeholder="Your Last Name"
name="contact[lastname]"
required
/>
</label>',
'<label class="btn-block"><span>Phone:</span>
<input
type="text"
class="form-control"
placeholder="Your Phone"
name="lead[phone]"
/>
</label>',
'<label class="btn-block"><span>Email:</span>
<input
type="text"
class="form-control"
placeholder="Your Email Address"
name="contact[email]"
required
/>
</label>',
'<div class="form-row g-recaptcha" data-sitekey="6LeEIlMUAAAAAGhdmJJLdJHPxaWx2GqBjber5n6B"></div>',
'<div style="text-align: center;">
<button
class="btn mt-3"
type="submit"
style="color: #fff; background: ' . $buttonColor . ';"
>' . $buttonText . '</button>
</div>
</form>',
));
}
elseif($attr["id"] == 14 || $attr["id"] == 96) { //order roofing respect sticker
$user = $this->security->getUser();
if($user) {
$module = implode(" ", array (
'<form method="post" class="py-4">',
'<div class="row">',
'<div class="col-sm-6">',
'<label class="btn-block"><span>First Name:</span>
<input
type="text"
class="form-control"
placeholder="Your First Name"
name="lead[firstname]"
required
/>
</label>',
'</div>',
'<div class="col-sm-6">',
'<label class="btn-block"><span>Last Name:</span>
<input
type="text"
class="form-control"
placeholder="Your Last Name"
name="lead[lastname]"
required
/>
</label>',
'</div>',
'</div>',
'<label class="btn-block"><span>Company:</span>
<input
type="text"
class="form-control"
placeholder="Your Company"
name="lead[company]"
required
/>
</label>',
'<label class="btn-block"><span>Phone:</span>
<input
type="text"
class="form-control"
placeholder="Your Phone"
name="lead[phone]"
required
/>
</label>',
'<label class="btn-block"><span>Email:</span>
<input
type="text"
class="form-control"
placeholder="Your Email Address"
name="lead[email]"
required
/>
</label>',
'<div class="row">',
'<div class="col-sm-6">',
'<label class="btn-block"><span>Street Address:</span>
<input
type="text"
class="form-control"
placeholder="Your Address"
name="lead[address1]"
required
/>
</label>',
'</div>',
'<div class="col-sm-6">',
'<label class="btn-block"><span>Address Line 2:</span>
<input
type="text"
class="form-control"
placeholder="Your Address Line 2"
name="lead[address2]"
/>
</label>',
'</div>',
'</div>',
'<div class="row">',
'<div class="col-sm-6">',
'<label class="btn-block"><span>City:</span>
<input
type="text"
class="form-control"
placeholder="Your City"
name="lead[city]"
required
/>
</label>',
'</div>',
'<div class="col-sm-6">',
'<label class="btn-block"><span>State / Providence / Region:</span>
<input
type="text"
class="form-control"
placeholder="Your Region"
name="lead[state]"
required
/>
</label>',
'</div>',
'</div>',
'<label class="btn-block"><span>ZIP / Postal Code:</span>
<input
type="text"
class="form-control"
placeholder="Your Postal Code"
name="lead[zip]"
required
/>
</label>',
'<label class="btn-block"><span>Type of Contractor:</span></label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Primarily Residential"
required
/>
<span>Primarily Residential</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Primarily Commercial"
required
/>
<span>Primarily Commercial</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Both"
required
/>
<span>Both</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Not a Contractor"
required
/>
<span>Not a Contractor</span>
</label>
',
'<div class="form-row g-recaptcha" data-sitekey="6LeEIlMUAAAAAGhdmJJLdJHPxaWx2GqBjber5n6B"></div>',
'<div style="text-align: center;">
<button
class="btn mt-3"
type="submit"
style="color: #fff; background: ' . $buttonColor . ';"
>' . $buttonText . '</button>
</div>
</form>',
));
}
else {
$module = implode(" ", array (
"
<div class='row'>
<div class='col-md-12'>
<div class='alert alert-info'>
<i class='fa fa-info'></i>
A user account is required to complete this offer. Please sign in or sign up to continue.
</div>
</div>
</div>
<div class='row'>
<div class='col-md-6' style='text-align: right;'>
<a class='button text-white' href='/sign-in'><i class='fa fa-key'></i> Sign In</a>
</div>
<div class='col-md-6' style='text-align: left;'>
<a class='button text-white' href='/sign-up'> Sign Up</a>
</div>
</div>
",
));
}
}
elseif($attr["id"] == 1000) { //address etc
$module = implode(" ", array (
'<form method="post" class="py-4">',
'<label class="btn-block"><span>First Name:</span>
<input
type="text"
class="form-control"
placeholder="Your First Name"
name="lead[firstname]"
required
/>
</label>',
'<label class="btn-block"><span>Last Name:</span>
<input
type="text"
class="form-control"
placeholder="Your Last Name"
name="lead[lastname]"
required
/>
</label>',
'<label class="btn-block"><span>Address:</span>
<input
type="text"
class="form-control"
placeholder="Your Address"
name="lead[address1]"
required
/>
</label>',
'<label class="btn-block"><span>Phone:</span>
<input
type="text"
class="form-control"
placeholder="Your Phone"
name="lead[phone]"
required
/>
</label>',
'<label class="btn-block"><span>Email:</span>
<input
type="text"
class="form-control"
placeholder="Your Email Address"
name="lead[email]"
required
/>
</label>',
'<label class="btn-block"><span>Type of Contractor:</span></label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Primarily Residential"
required
/>
<span>Primarily Residential</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Primarily Commercial"
required
/>
<span>Primarily Commercial</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Both"
required
/>
<span>Both</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Not a Contractor"
required
/>
<span>Not a Contractor</span>
</label>',
'<div class="form-row g-recaptcha" data-sitekey="6LeEIlMUAAAAAGhdmJJLdJHPxaWx2GqBjber5n6B"></div>',
'<div style="text-align: center;">
<button
class="btn mt-3"
type="submit"
style="color: #fff; background: ' . $buttonColor . ';"
>' . $buttonText . '</button>
</div>
</form>',
));
}
elseif($attr["id"] == 83) { //Wil-mar collar
$module = implode(" ", array (
'<form method="post" class="py-4">',
'<label class="btn-block"><span>First Name:</span>
<input
type="text"
class="form-control"
placeholder="Your First Name"
name="lead[firstname]"
required
/>
</label>',
'<label class="btn-block"><span>Last Name:</span>
<input
type="text"
class="form-control"
placeholder="Your Last Name"
name="lead[lastname]"
required
/>
</label>',
'<label class="btn-block"><span>Company:</span>
<input
type="text"
class="form-control"
placeholder="Your Company"
name="lead[company]"
/>
</label>',
'<label class="btn-block"><span>Address Line 1:</span>
<input
type="text"
class="form-control"
placeholder="Your Address Line 1"
name="lead[address1]"
/>
</label>',
'<label class="btn-block"><span>Address Line 2:</span>
<input
type="text"
class="form-control"
placeholder="Your Address Line 2"
name="lead[address2]"
/>
</label>',
'<label class="btn-block"><span>City:</span>
<input
type="text"
class="form-control"
placeholder="Your City"
name="lead[city]"
/>
</label>',
'<label class="btn-block"><span>State / Region:</span>
<input
type="text"
class="form-control"
placeholder="Your State / Region"
name="lead[state]"
/>
</label>',
'<label class="btn-block"><span>Zip Code:</span>
<input
type="text"
class="form-control"
placeholder="Your Zip Code"
name="lead[zip]"
/>
</label>',
'<label class="btn-block"><span>Phone:</span>
<input
type="text"
class="form-control"
placeholder="Your Phone"
name="lead[phone]"
required
/>
</label>',
'<label class="btn-block"><span>Email:</span>
<input
type="text"
class="form-control"
placeholder="Your Email Address"
name="lead[email]"
required
/>
</label>',
'<label class="btn-block"><span>Collar Size?:</span>
<select
class="form-control"
name="lead[collar_size]"
required
>
<option value="">- Select Size -</option>
<option value="3/4 inch">3/4 inch</option>
<option value="1 inch">1 inch</option>
<option value="1 - 1/2 inches">1 - 1/2 inches</option>
<option value="2 inches">2 inches</option>
<option value="3 inches">3 inches</option>
<option value="4 inches">4 inches</option>
</select>
</label>',
'<label class="btn-block"><span>Type of Contractor:</span></label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Primarily Residential"
required
/>
<span>Primarily Residential</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Primarily Commercial"
required
/>
<span>Primarily Commercial</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Both"
required
/>
<span>Both</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Not a Contractor"
required
/>
<span>Not a Contractor</span>
</label>',
'<div class="form-row g-recaptcha" data-sitekey="6LeEIlMUAAAAAGhdmJJLdJHPxaWx2GqBjber5n6B"></div>',
'<div style="text-align: center;">
<button
class="btn mt-3"
type="submit"
style="color: #fff; background: ' . $buttonColor . ';"
>' . $buttonText . '</button>
</div>
</form>',
));
}
elseif($attr["id"] == 103789) { //Contractor Exit Strategy
$module = implode(" ", array (
'<form method="post" class="py-4">',
'<label class="btn-block"><span>First Name:</span>
<input
type="text"
class="form-control"
placeholder="Your First Name"
name="lead[firstname]"
required
/>
</label>',
'<label class="btn-block"><span>Last Name:</span>
<input
type="text"
class="form-control"
placeholder="Your Last Name"
name="lead[lastname]"
required
/>
</label>',
'<label class="btn-block"><span>Company:</span>
<input
type="text"
class="form-control"
placeholder="Your Company"
name="lead[company]"
/>
</label>',
'<label class="btn-block"><span>Address Line 1:</span>
<input
type="text"
class="form-control"
placeholder="Your Address Line 1"
name="lead[address1]"
/>
</label>',
'<label class="btn-block"><span>Address Line 2:</span>
<input
type="text"
class="form-control"
placeholder="Your Address Line 2"
name="lead[address2]"
/>
</label>',
'<label class="btn-block"><span>City:</span>
<input
type="text"
class="form-control"
placeholder="Your City"
name="lead[city]"
/>
</label>',
'<label class="btn-block"><span>State / Region:</span>
<input
type="text"
class="form-control"
placeholder="Your State / Region"
name="lead[state]"
/>
</label>',
'<label class="btn-block"><span>Zip Code:</span>
<input
type="text"
class="form-control"
placeholder="Your Zip Code"
name="lead[zip]"
/>
</label>',
'<label class="btn-block"><span>Phone:</span>
<input
type="text"
class="form-control"
placeholder="Your Phone"
name="lead[phone]"
required
/>
</label>',
'<label class="btn-block"><span>Email:</span>
<input
type="text"
class="form-control"
placeholder="Your Email Address"
name="lead[email]"
required
/>
</label>',
'<label class="btn-block"><span>Type of Contractor:</span></label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Primarily Residential"
required
/>
<span>Primarily Residential</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Primarily Commercial"
required
/>
<span>Primarily Commercial</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Both"
required
/>
<span>Both</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Not a Contractor"
required
/>
<span>Not a Contractor</span>
</label>',
'<label class="btn-block"><span>Years in Business:</span>
<input
type="text"
class="form-control"
placeholder="Years in Business"
name="lead[years_in_business]"
required
/>
</label>',
'<label class="btn-block"><span>Approximate Number of Field Crew (height of the season):</span>
<input
type="text"
class="form-control"
placeholder="Number of Field Crew"
name="lead[num_field_crew]"
required
/>
</label>',
'<label class="btn-block"><span>Annual Revenue:</span>
<input
type="text"
class="form-control"
placeholder="Annual Revenue"
name="lead[annual_revenue]"
required
/>
</label>',
'<label class="btn-block"><span>Self-Perform Trade (Your own crews?):</span>
<input
type="text"
class="form-control"
placeholder="Self-Perform Trade"
name="lead[self_perform_trade]"
required
/>
</label>',
'<div class="form-row g-recaptcha" data-sitekey="6LeEIlMUAAAAAGhdmJJLdJHPxaWx2GqBjber5n6B"></div>',
'<div style="text-align: center;">
<button
class="btn mt-3"
type="submit"
style="color: #fff; background: ' . $buttonColor . ';"
>' . $buttonText . '</button>
</div>
</form>',
));
}
else {
$module = implode(" ", array (
'<form method="post" class="py-4">',
'<label class="btn-block"><span>First Name:</span>
<input
type="text"
class="form-control"
placeholder="Your First Name"
name="lead[firstname]"
required
/>
</label>',
'<label class="btn-block"><span>Last Name:</span>
<input
type="text"
class="form-control"
placeholder="Your Last Name"
name="lead[lastname]"
required
/>
</label>',
'<label class="btn-block"><span>Company:</span>
<input
type="text"
class="form-control"
placeholder="Your Company"
name="lead[company]"
/>
</label>',
'<label class="btn-block"><span>Address Line 1:</span>
<input
type="text"
class="form-control"
placeholder="Your Address Line 1"
name="lead[address1]"
/>
</label>',
'<label class="btn-block"><span>Address Line 2:</span>
<input
type="text"
class="form-control"
placeholder="Your Address Line 2"
name="lead[address2]"
/>
</label>',
'<label class="btn-block"><span>City:</span>
<input
type="text"
class="form-control"
placeholder="Your City"
name="lead[city]"
/>
</label>',
'<label class="btn-block"><span>State / Region:</span>
<input
type="text"
class="form-control"
placeholder="Your State / Region"
name="lead[state]"
/>
</label>',
'<label class="btn-block"><span>Zip Code:</span>
<input
type="text"
class="form-control"
placeholder="Your Zip Code"
name="lead[zip]"
/>
</label>',
'<label class="btn-block"><span>Phone:</span>
<input
type="text"
class="form-control"
placeholder="Your Phone"
name="lead[phone]"
required
/>
</label>',
'<label class="btn-block"><span>Email:</span>
<input
type="text"
class="form-control"
placeholder="Your Email Address"
name="lead[email]"
required
/>
</label>',
'<label class="btn-block"><span>Type of Contractor:</span></label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Primarily Residential"
required
/>
<span>Primarily Residential</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Primarily Commercial"
required
/>
<span>Primarily Commercial</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Both"
required
/>
<span>Both</span>
</label>
<label class="btn-block">
<input
type="radio"
name="lead[contractor_type]"
value="Not a Contractor"
required
/>
<span>Not a Contractor</span>
</label>',
'<div class="form-row g-recaptcha" data-sitekey="6LeEIlMUAAAAAGhdmJJLdJHPxaWx2GqBjber5n6B"></div>',
'<div style="text-align: center;">
<button
class="btn mt-3"
type="submit"
style="color: #fff; background: ' . $buttonColor . ';"
>' . $buttonText . '</button>
</div>
</form>',
));
}
return $module;
}
protected function getSymfonyForm ($attr = array ())
{
}
protected function getContent ($attr = array ())
{
$html = ""; //HTML to be returned
try {
$type = empty($attr["type"]) ? "*" : $attr["type"];
$category = empty($attr["category"]) ? "*" : $attr["category"];
$order = empty($attr["order"]) ? "" : $attr["order"];
$dir = empty($attr["dir"]) ? "" : $attr["dir"];
$page = empty($_GET["p"]) ? 0 : (int) $_GET["p"];
$limit = isset($attr["limit"]) ? $attr["limit"] : 0;
$use_secondary_categories = isset($attr["use_secondary_categories"]) ? $attr["use_secondary_categories"] : false;
$members_only = isset($attr["members_only"]) ? $attr["members_only"] : false;
$allowDupes = isset($attr["dupes"]) ? (strtolower($attr["dupes"]) === "yes") : false;
$excludeInDupes = isset($attr["exclude_in_dupes"]) ? (strtolower($attr["exclude_in_dupes"]) === "yes") : false;
$as_gallery = isset($attr["as_gallery"]) ? (strtolower($attr["as_gallery"]) === "yes") : false;
$only_featured = isset($attr["only_featured"]) ? (strtolower($attr["only_featured"]) === "yes") : false;
$only_announcements = isset($attr["only_announcements"]) ? (strtolower($attr["only_announcements"]) === "yes") : false;
$customer_level_or_higher = isset($attr["customer_level_or_higher"]) ? $attr["customer_level_or_higher"] : false;
$site_override = isset($attr["site"]) ? $attr["site"] : false;
//$cache_test = $cache_time ? true : false;
//$display_no_content_message = isset($attr["display_no_content_message"]) ? $attr["display_no_content_message"] : false;
$no_content_message = isset($attr["no_content_message"]) ? $attr["no_content_message"] : "";
if (!empty($attr["links"]) && is_string($attr["links"])) {
$attr["links"] = array_map('trim', explode(",", $attr["links"]));
}
$content = $this->contentHelper->getContent(
$type,
$category,
$order,
$dir,
$page,
$limit,
$allowDupes,
"*",
$use_secondary_categories,
$members_only,
$as_gallery, //require a featured image
$only_featured,
"",
$customer_level_or_higher,
$only_announcements,
$excludeInDupes,
$site_override
);
if($this->request) {
if(preg_match('/bot|crawl|curl|dataprovider|search|get|spider|find|java|majesticsEO|google|yahoo|teoma|contaxe|yandex|libwww-perl|sleuth|audit|robot|Node|seo|broken|buck|Anthill|facebookexternalhit/i', $this->request->headers->get("User-Agent"))) {
$this->contentHelper->addImpressions($this->request, $content["content"]);
}
else {
$this->contentHelper->enqueueImpressions($this->request, $content["content"]);
}
}
$cache_time = isset($attr["cache_time"]) ? (int) $attr["cache_time"] : 0;
if($cache_time) {
$cache = new FilesystemAdapter();
$env = $this->container->getParameter('kernel.environment');
$site_code = "";
$request = $this->request;
if($request) {
$session = $request->getSession();
if($session) {
$site_code = $session->get("site");
}
}
$cache_item = $cache->getItem($site_code . $env . str_replace(['{','}','(',')','/','\\','@',':', '"'], "", __METHOD__ . serialize(func_get_args())));
if($cache_item->isHit()) {
$results = $cache_item->get();
return $results;
}
}
$attr["data"] = $content["content"];
$attr["total"] = $content["total"];
$attr["page"] = $page;
/*
if($type == 8) {
$attr["media"] = [];
foreach($content["content"] as $c) {
$cm = $c->getContentMetaByKey("webinar_showgraphic");
if(is_null($cm)) {
$attr["media"][] = "";
}
else {
$m = $this->mediaHelper->getMediaByOldId($cm->getMetavalue());
$attr["media"][] = $m;
}
}
}
*/
// convert the content into a module
if($type == 5 || $type == 4 || $as_gallery) {
if($type == 4) {
$attr["class"] = isset($attr["class"]) ? $attr["class"] . " directory" : "directory";
}
$attr["class"] = isset($attr["class"]) ? $attr["class"] . " gallery" : "gallery";
$attr["columns"] = isset($attr["columns"]) ? $attr["columns"] : 3;
$attr["mitems"] = "";
$tmpl = $this->twig->load("modules/gallery-display.html.twig");
}
else {
$tmpl = $this->twig->load("modules/default-loop.html.twig");
}
//if($attr["total"] > 0) {
$html = $tmpl->render(array(
"module" => $attr,
));
if($cache_time) {
$cache_item->set($html);
$cache_item->expiresAfter($cache_time);
$cache->save($cache_item);
}
//}
}
catch (\Exception $e) {
var_dump("File: ", $e->getFile());
var_dump("Line: ", $e->getLine());
var_dump($e->getMessage());
exit;
}
return $html;
}
protected function getAds($attr = array ()) {
$position = empty($attr["position"]) ? "" : $attr["position"];
$site_code = 1;
$request = $this->request;
if($request) {
$session = $request->getSession();
if($session) {
$site_code = $session->get("site");
}
}
//Only set up for the poll ad section at the moment.
//Update if we need to pull other ad types / add specific options.
if($position == "ad-poll") {
$mediaGroup = $this->mediaHelper->getMediaGroupByPosition($attr["position"]);
$ads = $mediaGroup->getActiveMediaGroupItemsBySiteId($site_code);
if(empty($ads)) {
return "";
}
shuffle($ads);
$ad = $ads[0];
$adHtml = "";
$adHtml .= "<h3 class='module-title' style='margin: 0 0 0.8rem 0;text-transform: unset;'>" . strtoupper(SiteConfig::CONFIGS[$site_code]["site_code"]) . " Poll brought to you by:</h3>";
$adHtml .= "<div style='text-align:center;'>";
$adHtml .= $ad->getMediaImageTag("", "");
$adHtml .= "</div>";
return $adHtml;
}
}
protected function getMediaGroup ($attr = array ())
{
$attr = array_merge([
"columns" => 3,
"limit" => "",
"class" => ""
], $attr);
$data = $this->mediaHelper->getMediaGroupByPosition($attr["position"]);
$attr["data"] = $data;
$temp_items = null;
$site_code = "";
if($data->isAdGroup()) {
$request = $this->request;
if($request) {
$session = $request->getSession();
if($session) {
$site_code = $session->get("site");
//$temp_items = $data->getMediaGroupItemsBySiteId($site_code);
}
}
}
$limit = $attr["limit"] ? $attr["limit"] : $data->getDisplayLimit();
if($attr["position"] == "ad-rotation") {
//Get up to 3 priority ads - these each must show up in one of the first 3 spots
$unPriorityAds = $this->mediaHelper->getRandomUnpriorityAds($data, $limit, $site_code);
$priorityAds = $this->mediaHelper->getRandomPriorityAds($data, 3, $site_code);
$ads = array_merge($priorityAds, $unPriorityAds);
$firstThree = array_slice($ads, 0, 3);
shuffle($firstThree);
$ads = array_merge($firstThree, array_slice($ads, 3));
}
else if($attr["position"] == "ad-sidebar") {
//Get up to 3 priority ads - these each must all show up in the sidebar
$unPriorityAds = $this->mediaHelper->getRandomUnpriorityAds($data, $limit, $site_code);
$priorityAds = $this->mediaHelper->getRandomPriorityAds($data, 3, $site_code);
$ads = array_merge($priorityAds, $unPriorityAds);
$ads = array_slice($ads, 0, $limit);
shuffle($ads);
}
else if($attr["position"] == "ad-bottom") {
//Priority ads have a flat 20% chance of showing up
if(rand(1, 100) <= 20) {
$ads = $this->mediaHelper->getRandomPriorityAds($data, $limit, $site_code);
}
else {
$ads = $this->mediaHelper->getRandomUnpriorityAds($data, $limit, $site_code);
}
//In case there are no priority ads
if(count($ads) == 0) {
$ads = $this->mediaHelper->getRandomMediaGroupItems($data, $limit, $site_code);
}
}
else {
$ads = $this->mediaHelper->getRandomMediaGroupItems($data, $limit, $site_code);
}
$attr["items"] = $ads;
//$temp_items = $data->getMediaGroupItems()->toArray();
//shuffle($temp_items);
//$attr["items"] = $attr["limit"] ? array_slice($temp_items, 0, $attr["limit"]) : $temp_items;
$tmpl = $this->twig->load("elements/media-group-v2.html.twig");
$html = $tmpl->render(array(
"module" => $attr,
/*
"attr" => $attrs,
"mediagroup" => $module,
*/
));
return $html;
}
protected function getGallery2 ($attr = array ())
{
$attr = array_merge([
"columns" => 3,
"link" => "file",
"ids" => [],
"links" => [],
"idtype" => "",
"limit" => ""
], $attr);
$attr["class"] = !empty($attr["class"]) ? $attr["class"] . " gallery" : "gallery";
if (!empty($attr["ids"]) && is_string($attr["ids"])) {
$attr["ids"] = explode(",", $attr["ids"]);
}
if (!empty($attr["links"]) && is_string($attr["links"])) {
$attr["links"] = array_map('trim', explode(",", $attr["links"]));
}
$limit = (int) $attr["limit"];
$data = array ();
foreach ($attr["ids"] as $id) {
try {
if($attr["idtype"] == "old") {
$media = $this->mediaHelper->getMediaByOldId($id);
}
else {
$media = $this->mediaHelper->getMediaById($id);
}
$data[] = $media;
} catch (\Exception $e) {
// ignore
}
}
if($limit && $limit < count($data)) {
$rand = $this->getUniqueRandomNumbers(0, count($data)-1, $limit);
$links = array();
$attr["data"] = array();
foreach($rand as $r) {
$attr["data"][] = $data[$r];
$links[] = $attr["links"][$r];
}
$attr["links"] = $links;
}
else {
$attr["data"] = $data;
}
$tmpl = $this->twig->load("modules/gallery-display.html.twig");
$html = $tmpl->render(array(
"module" => $attr,
));
return $html;
}
protected function getTweets ($attr = array ())
{
$page = empty($attr["page"]) ? "" : $attr["page"];
$limit = empty($attr["limit"]) ? "" : $attr["limit"];
$module = implode(" ", array (
"<a class='twitter-timeline'
href='https://twitter.com/{$page}'
data-tweet-limit='{$limit}'>
Tweets by @{$page}</a>",
"<script async src='https://platform.twitter.com/widgets.js'></script>",
));
return $module;
}
protected function getFBPost ($attr = array ())
{
$page = empty($attr["fbpage"]) ? "" : $attr["fbpage"];
$width = empty($attr["width"]) ? "408px" : $attr["width"];
$height = empty($attr["height"]) ? "1054px" : $attr["height"];
$rcs = "https%3A%2F%2Fwww.facebook.com%2Frooferscoffeeshop";
$aar = "https%3A%2F%2Fwww.facebook.com%2FAskARooferRCS";
$mcs = "https%3A%2F%2Fwww.facebook.com%2FMetalcoffeeshop";
$ccs = "https%3A%2F%2Fwww.facebook.com%2FCoatingsCoffeeShop";
switch ($page) {
case "rcs":
$fbPage = $rcs;
break;
case "aar":
$fbPage = $aar;
break;
case "mcs":
$fbPage = $mcs;
break;
case "ccs":
$fbPage = $ccs;
break;
default:
$fbPage = $rcs;
}
$module = implode(" ", array (
"<iframe id='FBiframe' src='https://www.facebook.com/plugins/page.php?href=$fbPage&tabs=timeline&small_header=true&adapt_container_width=true&width=$width&height=$height&hide_cover=true&show_facepile=true&appId=339799721874547' width=$width height=$height style='border:none;overflow:hidden' scrolling='no' frameborder='0' allowfullscreen='true' allow='autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share'></iframe>"
));
return $module;
}
protected function getPoll ($attr = array ())
{
$site_code = "";
$request = $this->request;
if($request) {
$session = $request->getSession();
if($session) {
$site_code = $session->get("site");
}
}
$id = empty($attr["id"]) ? "" : $attr["id"];
$directory = isset($attr["directory"]) ? (strtolower($attr["directory"]) === "yes") : false;
if($id) {
$poll = $this->pollHelper->getPollById($id);
}
else {
$poll = $this->pollHelper->getActivePoll();
}
if(!$poll) {
return "";
}
$id = $poll->getId();
$this->pollHelper->incrementPollImpressions($poll);
$allowSubmission = 0;
$userId = 0;
$signInForm = "";
$user = $this->security->getUser();
if($user) {
$userId = $user->getId();
$allowSubmission = 1;
}
elseif(!$poll->getRequiresLogin()) {
$allowSubmission = 1;
}
else {
$signInForm = implode(" ", [
"<div class='mod mod-sign-in'>",
"<form method='post' action='/catch-all'>",
"<input type='hidden' name='action' value='sign-in' />",
"<input type='hidden' name='redirectPath' value='/' />",
"<p>Please sign into your RoofersCoffeeShop Account to take the poll or see the results.</p>",
"<label class='btn-block'><span>Username</span>",
"<input",
"class='form-control'",
"type='text'",
"name='username'",
"placeholder='Your Username'",
"required",
"/>",
"</label>",
"<label class='btn-block'><span>Password</span>",
"<input",
"class='form-control'",
"type='password'",
"name='password'",
"placeholder='Your Password'",
"required",
"/>",
"</label>",
"<button",
"class='btn btn-secondary'",
"type='submit'",
">Sign In</button>",
"</form>",
"</div>",
"<hr />",
"<center><a href='/sign-up' style='color:#d11818;'>Need an account? Create one here.</a></center>",
]);
}
$ad = $poll->getAd();
$adHtml = "";
$useSlider = false;
$sliderHtml = "";
if($directory) {
$ad = $poll->getPopOutAd();
/*$adHtml = $ad->getDescription();
if($adHtml) {
$adHtml = $adHtml;
}
else {
$adHtml = "<h3>Thank you for your feedback!</h3>";
}*/
if($ad && $ad->getQuestionSlider()) {
$useSlider = true;
$sliderHtml = str_replace(array("\r", "\n"), '',
'<div class=\"col-md-7\">
<div id=\"part1\" style=\"margin-top:25px;\">
<p>How likely are you to recommend us to a friend or colleague?</p>
<p><input id=\"pi_input\" type=\"range\" class=\"slider\" min=\"1\" max=\"10\" step=\"1\" style=\"width:100%;\"/></p>
<div class=\"row\">
<div class=\"col-md-6\" style=\"font-size:16px;padding-left:40px;\">
Rating: <output id=\"value\"></output>
</div>
<div class=\"col-md-6\">
<input type=\"buttom\" class=\"button\" value=\"Submit\" id=\"popSubmit\" style=\"width:100px;\">
</div>
</div>
</div>
<div id=\"part2\" style=\"display:none\">
<div style=\"margin-top:50px;\">
<h3>Thank you for your feedback!</h3>
<p>Visit the <a href=\"/our-directory\">RCS Directory</a> to see more from our partners!</p>
</div>
</div>
</div>');
}
$adHtml = "Thank you for your feedback!";
$ad = $poll->getAd();
}
elseif($ad) {
//$adHtml .= "<div class='ad-sidebar'>";
//$adHtml .= "<div class='media-block'>";
$adHtml .= "<h3 class='module-title' style='margin: 0 0 0.8rem 0;text-transform: unset;'>" . strtoupper(SiteConfig::CONFIGS[$site_code]["site_code"]) . " brought to you by:</h3>";
$adHtml .= "<div style='text-align:center;'>";
$adHtml .= $ad->getMediaImageTag("", "");
$adHtml .= "</div>";
//$adHtml .= "</div>";
//$adHtml .= "</div>";
$adHtml = preg_replace( "/\r|\n/", "", $adHtml );
}
ob_start();
?>
<link href="/assets/css/surveyjs-custom.min.css?v=11-22-22" rel="stylesheet" />
<?php if(!$directory) : ?>
<h3 class="module-title" style="margin:0"><?php echo strtoupper(SiteConfig::CONFIGS[$site_code]["site_code"]) ?> Poll</h3>
<?php endif; ?>
<div id="poll-image-container" class="poll-image-container">
<?php
$afterPollHtml = "";
if($poll->getMedia()) {
if($poll->getInfoUrl()) {
$afterPollHtml = "<a href='{$poll->getInfoUrl()}' class='button poll-button text-white' target='_blank'>Continue the Conversation</a>";
echo "<a href='{$poll->getInfoUrl()}' target='_blank'>";
}
echo $poll->getMedia()->getImageTag();
if($poll->getInfoUrl()) {
echo "</a>";
}
}
?>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js" integrity="sha512-d9xgZrVZpmmQlfonhQUvTR7lMPtO7NkZMkA0ABN3PHCbKA5nqylQ/yWlFAyY6hYgdF1Qh6nYiuADWwKB4C2WSw==" crossorigin="anonymous"></script>
<script>
function renderPoll(data) {
var adHtml = "<?=$adHtml?>";
var directory = "<?=$directory?>";
var useSlider = "<?=$useSlider?>";
if(adHtml) {
if(directory) {
$("#home-poll").html($("#pollReplacementAd").html());
$('#poa-container').height($('#rc-center').height());
}
else {
setTimeout(function () {
$("#home-poll").fadeOut("500", function() {
$("#home-poll").html(adHtml);
$("#home-poll").fadeIn("500");
});
}, 5000);
}
}
$("#pollLoadingContainer").html("");
$("#poll-image-container").html("");
$("#beforePoll").html(<?=json_encode($poll->getTitle())?>);
$("#beforePoll").show();
$("#afterPoll").html("<?=$afterPollHtml?>");
$("#afterPoll").show();
$("#pollResults").show();
var keys = [];
var vals = [];
for(var k in data) {
keys.push(k);
vals.push(data[k]);
}
console.log("DATA");
console.log(data);
var ctx = document.getElementById('pollResults').getContext('2d');
var pollResults = new Chart(ctx, {
//type: 'bar',
type: 'horizontalBar',
data: {
//labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
labels: keys,
datasets: [{
label: '# of Votes',
//data: [12, 19, 3, 5, 2, 3],
data: vals,
backgroundColor: [
'rgba(255, 99, 132, 0.4)',
'rgba(54, 162, 235, 0.4)',
'rgba(255, 206, 86, 0.4)',
'rgba(75, 192, 192, 0.4)',
'rgba(153, 102, 255, 0.4)',
'rgba(255, 159, 64, 0.4)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
</script>
<?php
$module = ob_get_clean();
$responsesOpen = $this->pollHelper->areResponsesOpen($poll);
$userCompleted = $this->pollHelper->hasUserCompletedPoll($user, $poll);
$cookieCompleted = $this->request->cookies->get("poll" . $poll->getId());
if($userCompleted || !$responsesOpen || $cookieCompleted) {
//Instead of poll results, display an ad for some reason:
if($directory) {
$ad = $poll->getPopOutAd();
$adHtml = $ad->getDescription();
if($adHtml) {
return $adHtml;
}
return "<h3>Thank you for your feedback!</h3>";
}
elseif($ad) {
return $adHtml;
}
else {
$results = $this->pollHelper->getPollResults($poll->getId());
$results = json_encode($results);
$module .= "<div id='pollLoadingContainer'><div id='pollLoader'></div></div>";
$module .= "<div id='beforePoll'></div><canvas id='pollResults' width='400' height='300'></canvas><div id='afterPoll'></div>";
$module .= "<script>
console.log('RESULTS');
console.log($results);
renderPoll($results);</script>";
return $module;
}
}
$choicesJSArray = "[";
foreach($poll->getActivePollOptionsArray() as $key => $value) {
$value = addslashes($value);
$choicesJSArray .= "{'value': '{$key}', 'text': '{$value}'},";
}
$choicesJSArray .= "]";
ob_start();
?>
<!--<script src='https://unpkg.com/survey-jquery'></script>-->
<script src='https://unpkg.com/survey-jquery@1.9.120/survey.jquery.js'></script>
<!--<link href='https://unpkg.com/survey-jquery/survey.min.css' type='text/css' rel='stylesheet'/>-->
<link href='https://unpkg.com/survey-jquery@1.9.120/survey.min.css' type='text/css' rel='stylesheet'/>
<div id='surveyContainer'></div>
<script>
var useSlider = "<?=$useSlider?>";
/*var sliderHtml = "< ?=$sliderHtml?>";*/
//if(<?=$ad && $ad->getQuestionSlider()?>) {
if(useSlider) {
/*
Having issues with the slider:
var surveyJSON = {
showTitle: false,
completeText: 'Submit',
requiredText: '',
focusFirstQuestionAutomatic: false,
pages:
[
{
name:'page1',
questions:
[
{
type: 'html',
name: 'question',
html: sliderHtml
}
]
}
]
};
*/
var surveyJSON = {
showTitle: false,
completeText: 'Submit',
requiredText: '',
focusFirstQuestionAutomatic: false,
pages:
[
{
name:'page1',
questions:
[
{
type: 'rating',
autoGenerate: false,
rateCount: 10,
rateValues: <?=$choicesJSArray?>,
"rateMax": 10,
isRequired: true,
name: 'question',
title: <?=json_encode($poll->getTitle())?>
}
]
}
]
};
}
else {
var surveyJSON = {
showTitle: false,
completeText: 'Submit',
requiredText: '',
focusFirstQuestionAutomatic: false,
pages:
[
{
name:'page1',
questions:
[
{
type: 'radiogroup',
choices: <?=$choicesJSArray?>,
isRequired: true,
name: 'question',
title: <?=json_encode($poll->getTitle())?>
}
]
}
]
};
}
var survey = new Survey.Model(surveyJSON);
$('#surveyContainer').Survey({
model:survey,
//allowComplete: false,
//onCompleting:sendDataToServer,
onComplete:sendDataToServer,
showQuestionNumbers: 'off',
completedHtml: '<div id="pollLoadingContainer"><div id="pollLoader"></div></div><div id="beforePoll"></div><canvas id="pollResults" width="400" height="300" style="display:none;"></canvas><div id="afterPoll"></div>'
});
if(<?=$allowSubmission?> == 0) {
survey.onCompleting.add((result, options) => {
options.allowComplete = false;
$("#surveyContainer").html("<?=$signInForm?>");
});
}
function sendDataToServer(survey) {
//var resultAsString = JSON.stringify(survey.data);
//alert(resultAsString);
var pollOptionId = survey.data.question;
$.post("/ajax/pollResponse",
{
pollId: <?=$poll->getId()?>,
pollOptionId: pollOptionId,
userId: <?=$userId?>
},
function(data,status){
//survey.completedHtml = "Hooray!";
//survey.clear(true, true);
//survey.doComplete();
renderPoll(data);
});
//document.cookie = 'poll=' + $(this).val() + ";path=/";
document.cookie = "poll" + <?=$poll->getId()?> + "=1;path=/";
//$pollCookie = $this->request->cookies->set("poll", "1");
}
</script>
<?php
$module .= ob_get_clean();
return $module;
}
public function usd ($amount = "")
{
$amount = (int) $amount;
return "$" . number_format(($amount / 100), 2);
}
public function getUniqueRandomNumbers($min, $max, $quantity) {
$numbers = range($min, $max);
shuffle($numbers);
return array_slice($numbers, 0, $quantity);
}
public function tagShortcodes($pee) {
preg_match_all("/(\[([\w]+)[^\]]*\])(.*?)(\[\/\\2\])/", $pee, $matches, PREG_SET_ORDER);
//$again = false;
if (!empty($matches)) {
/*
Example:
<a href=howdy.html>click me</a>
$val[0] <a href=howdy.html>click me</a>
$val[1] <a href=howdy.html>
$val[2] a
$val[3] click me
$val[4] </a>
*/
foreach ($matches as $val) {
$type = $val[2];
switch ($type) {
case "img":
$pee = str_replace(
$val[0],
"<img src='$val[3]' loading='lazy' />",
$pee
);
break;
case "url":
if($val[1] == "[url]") {
$href = $val[3];
}
else {
$href = substr(substr($val[1], 0, -1), strpos($val[1], "=") + 1);
}
$pee = str_replace(
$val[0],
"<a href='$href' target='_blank'>".$val[3]."</a>",
$pee
);
break;
}
/*
if(!$again) {
preg_match_all("/(\[([\w]+)[^\]]*\])(.*?)(\[\/\\2\])/", $val[3], $matches2, PREG_SET_ORDER);
if (!empty($matches2)) {
$again = true;
}
}
*/
}
/*
if($again) {
$pee = $this->tagShortcodes($pee);
}
*/
//$pee = $this->tagShortcodes($pee);
}
return $pee;
}
}