Skip to content

Instantly share code, notes, and snippets.

@nathanfitzgerald
Last active August 29, 2015 14:01
Show Gist options
  • Save nathanfitzgerald/a3dd83e5ab82c176cd87 to your computer and use it in GitHub Desktop.
Save nathanfitzgerald/a3dd83e5ab82c176cd87 to your computer and use it in GitHub Desktop.
f9core.sample.php
<?php
class Frequency9 {
/**
* @var ahDebug A reference to the ahDebug object
*/
public $debug = null;
/**
* @var modX A reference to the modX object.
*/
public $modx = null;
/**
* @var cpanel The cpanel object.
*/
public $cpanel = null;
/**
* @var cpanel The infusionsoft object.
*/
public $is = null;
public $chargify = null;
/* Frequency9 constructor */
function __construct(modX &$modx, array $config = array()) {
$this->modx =& $modx;
$corePath = $this->modx->getOption('frequency9.core_path', $config, $this->modx->getOption('core_path').'components/frequency9/');
// configuration
$this->config = array_merge(array(
'corePath' => $corePath,
'modelPath' => $corePath.'model/',
), $config);
// load Aweber
require_once $this->config['modelPath'] . 'aweber/aweber_api.php';
// load AWS
require_once $this->config['modelPath'] . 'aws/sdk.class.php';
// load Chargify
require_once $this->config['modelPath'] . 'chargify/chargify.class.php';
// load Google
require_once $this->config['modelPath'] . 'google/src/Google_Client.php';
require_once $this->config['modelPath'] . 'google/src/contrib/Google_AnalyticsService.php';
require_once $this->config['modelPath'] . 'google/src/contrib/Google_PlusService.php';
// load Infusionsoft
require_once $this->modx->getOption('core_path') . 'model/isdk/isdk.php';
require_once $this->config['modelPath'] . 'infusionsoft/isdke.php';
require_once $this->config['modelPath'] . 'infusionsoft/infusionsoft.php';
// load Iron.io
require_once $this->config['modelPath'] . 'iron-io/IronCore.class.php';
require_once $this->config['modelPath'] . 'iron-io/IronCache.class.php';
require_once $this->config['modelPath'] . 'iron-io/IronMQ.class.php';
require_once $this->config['modelPath'] . 'iron-io/IronWorker.class.php';
// load Mixpanel
require_once $this->config['modelPath'] . 'mixpanel/mixpanel.php';
// load PayPal
require_once $this->modx->getOption('core_path').'model/paypal/ipnlistener.php';
// load PostAffiliatePro
require_once $this->config['modelPath'] . 'postaffiliatepro/PapApi.class.php';
// load Pwgen
require_once $this->config['modelPath'] . 'pwgen/pwgen.class.php';
// load validation classes
require_once $this->config['modelPath'] . 'validation/domains.php';
require_once $this->config['modelPath'] . 'validation/emails.php';
require_once $this->config['modelPath'] . 'validation/phones.php';
// load Zend
require_once $this->modx->getOption('core_path').'model/zend/library/Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
// load Frequency Core
$this->modx->addPackage('frequency9', $this->config['modelPath']);
}
/* Frequency9 destructor */
function __destruct() {
unset($this->config);
}
########################################################################
############################### LOGGING ################################
########################################################################
public function log(&$x, $folder, $data) {
date_default_timezone_set('US/Pacific');
$logFolder = $folder . '/';
if (empty($x->account->folder)) {
$x->account->folder = 'frequency9';
}
$logFile = date('Y-m-d H:i:s') . ' ' . $x->account->folder;
$log = print_r($data, true);
// save log file to S3
$s3 = new AmazonS3();
$response = $s3->create_object('frequency9-logs', $logFolder . $logFile . '.log', array(
'body' => $log,
'contentType' => 'text/plain',
'acl' => AmazonS3::ACL_PRIVATE,
'storage' => AmazonS3::STORAGE_REDUCED,
'headers' => array(
'Cache-Control' => 'max-age=' . 3600 * 24 * 365 . ', public',
'Expires' => date('D, d M Y H:m:i', time() + 3600 * 24 * 365) . ' GMT'
)
));
}
########################################################################
###################### SUBCLASS CONFIG FUNCTIONS #######################
########################################################################
public function cfgCpanel($host, $user, $password) {
require_once $this->config['modelPath'] . 'cpanel/xmlapi.php';
$this->cpanel = new xmlapi($host);
$this->cpanel->password_auth($user, $password);
$this->cpanel->set_output('json');
$this->cpanel->set_debug(1);
}
public function cfgInfusionsoft($accountId, $businessId) {
$integration = $this->modx->getObject('XIntegration', array(
'account_id' => $accountId,
'business_id' => $businessId,
'type' => 'infusionsoft'
));
$this->is = new infusionsoft;
return $this->is->cfgCon($integration->get('subdomain'), $integration->get('api_key'), $accountId, $businessId);
}
public function infusionsoft($x) {
$integration = $this->modx->getObject('XIntegration', array(
'account_id' => $x->account->id,
'business_id' => $x->business->id,
'type' => 'infusionsoft'
));
$this->is = new infusionsoft;
return $this->is->cfgCon($integration->get('subdomain'), $integration->get('api_key'), $x->account->id, $x->business->id);
}
########################################################################
########################## DOMAIN FUNCTIONS ############################
########################################################################
/* public function to get the http host */
public function getHttpHost() {
$http_host = $this->modx->getOption('http_host');
$http_host = str_replace(':80', '', $http_host);
$http_host = str_replace(':443', '', $http_host);
$http_host = str_replace('www.', '', $http_host);
return $http_host;
}
/* public function to get the base url */
public function getBaseUrl() {
$baseurl = $_SERVER['HTTP_HOST'];
if (empty($_SERVER['HTTPS'])) {
$baseurl = 'http://' . $baseurl;
}
else {
$baseurl = 'https://'. $baseurl;
}
return $baseurl;
}
/* public function to parse out the subdomain from a domain string */
public function getSubdomain($domain = '') {
if (empty($domain)) {
$domain = $_SERVER['HTTP_HOST'];
}
$labels = explode('.', $domain);
return $labels[count($labels)-3];
}
/* public function to get the domain */
public function getDomain($domain = '') {
if (empty($domain)) {
$domain = $_SERVER['HTTP_HOST'];
}
$domain = str_replace(':80', '', $domain);
$domain = str_replace(':443', '', $domain);
return $domain;
}
/* public function to parse out the root domain from a domain string */
public function getRootDomain($domain = '') {
if (empty($domain)) {
$domain = $_SERVER['HTTP_HOST'];
}
$labels = explode('.', $domain);
$root = $labels[count($labels)-2];
if ($root == 'frequency9') { // convert frequency9 domains to 'core' to simplify snippet names
$root = 'core';
}
return $root;
}
/* public function to get the request */
public function getRequest($request = '') {
if (empty($request)) {
$request = $_SERVER['REQUEST_URI'];
}
$parts = explode('?', $request);
$request = $parts[0];
if (substr($request, -1) != '/') {
$request .= '/';
}
if (substr($request, 0, 1) != '/') {
$request = '/' . $request;
}
return $request;
}
/* public function to get the querystring */
public function getQuerystring($querystring = '') {
if (empty($querystring)) {
$querystring = $_SERVER['REQUEST_URI'];
}
$parts = explode('?', $querystring);
if (!empty($parts[1])) {
$querystring = $parts[1];
}
else {
$querystring = '';
}
return $querystring;
}
/* public function to get the querystring and return as array */
public function getQuery($querystring = '') {
if (empty($querystring)) {
$querystring = $_SERVER['REQUEST_URI'];
}
$parts = explode('?', $querystring);
$querystring = $parts[1];
parse_str($querystring, $query);
return $query;
}
/* public function to get the current url */
public function getUrl() {
return $this->getBaseUrl() . $this->getRequest();
}
/* public function to split a url path */
public function splitPath($request = '') {
if (empty($request)) {
$request = $_SERVER['REQUEST_URI'];
}
$parts = explode('?', $request);
$parts = explode('/', $parts[0]);
$splitPath = array();
foreach ($parts as $part) {
if (!empty($part)) {
$splitPath[] = $part;
}
}
return $splitPath;
}
/* public function to build an alias */
public function getAlias($path, $pre = '', $post = '', $default = '') {
$alias = '';
if (reset($path) == $pre) {
array_shift($path);
}
if (end($path) == $post) {
array_pop($path);
}
$alias = implode('.', $path);
return $alias;
}
/* public function to build an alias - DEPRECATED */
public function alias($path, $pre = '', $post = '', $default = '') {
$alias = '';
foreach ($path as $part) {
if ($part[0] != '?') {
$alias .= $part . '.';
}
}
$alias = substr($alias, 0, -1);
if (count($path) == 1 && $default) {
$alias .= '.default';
}
if ($pre) {
$alias = $pre . '.' . $alias;
}
if ($post) {
$alias = $alias . '.' . $post;
}
return $alias;
}
/* public function to build a path from an alias */
public function aliasToPath($alias) {
if (substr($alias, 0, 5) == 'page.') {
$alias = substr($alias, 5);
}
if (substr($alias, -8) == '.default') {
$alias = substr($alias, 0, -8);
}
$parts = explode('.', $alias);
foreach ($parts as $part) {
$path .= $part . '/';
}
return $path;
}
/* public function to build a url from an alias */
public function urlFromAlias($domain, $alias, $mode = '') {
if ($mode == 'full') {
if (!empty($_SERVER['HTTPS'])) {
$url = 'https://';
}
else {
$url = 'http://';
}
$url .= $domain;
}
$url .= '/';
if (substr($alias, 0, 5) == 'page.') {
$alias = substr($alias, 5);
}
if (substr($alias, -8) == '.default') {
$alias = substr($alias, 0, -8);
}
$parts = explode('.', $alias);
foreach ($parts as $part) {
$url .= $part . '/';
}
return $url;
}
/* public function to validate a url - deprecated, use validateDomain instead */
public function validUrl($url) {
$v = "/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
return (bool)preg_match($v, $url);
}
/* DEPRECATED public function to split a request URI*/
public function splitRequest($request) {
$parts = explode('/', $request);
$splitRequest = array();
foreach ($parts as $part) {
if (!empty($part)) {
$splitRequest[] = $part;
}
}
return $splitRequest;
}
########################################################################
########################### REST FUNCTIONS #############################
########################################################################
/* public function to process a REST request - INCOMPLETE */
public function rest(&$x, $options, $type = 'json') {
// load options
$api = $options['api'];
$endpoint = $options['endpoint'];
$request = $options['request'];
$data = $options['data'];
$id = $options['id'];
// get the API url
$url = $this->modx->getOption('frequency9.' . $api . '_api_url');
// get the integration
if ($integration = $x->integration->{$api}) {
// set the subdomain
$subdomain = $integration->subdomain;
if (!empty($subdomain)) {
$url = str_replace('://', '://' . $subdomain . '.', $url);
}
// set the endpoint
$url .= $endpoint;
// add id
if ($id !== null) {
$url .= '/' . $id;
}
// request type
$url .= '.' . $type;
// encode data
if (!empty($data)) {
$json = json_encode($data);
}
}
// invalid integration
else {
return 'There is no ' . $api . ' integration configured';
}
}
########################################################################
##################### DATA MANIPULATION FUNCTIONS ######################
########################################################################
/* public function to convert EOL delimited string to array */
public function eolToArray($data) {
$array = explode("\n", $data);
return $array;
}
/* public function to convert an array to EOL delimited string */
public function arrayToEol($data) {
$string = implode("\n", $data);
return $string;
}
/* public function to decode JSON data */
public function decode($data, $assoc = true) {
$decoded = json_decode($data, $assoc);
if ($assoc == true && !is_array($decoded)) {
$decoded = array();
}
return $decoded;
}
/* public function to encode JSON data */
public function encode($data) {
return json_encode($data);
}
/* public function to convert a stdObject to an array */
public function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
*/
return array_map(array('Frequency9', 'objectToArray'), $d);
}
else {
// Return array
return $d;
}
}
/* public function to convert an array to a stdObject */
public function arrayToObject($d) {
if (is_array($d)) {
/*
* Return array converted to object
*/
return (object) array_map(array('Frequency9', 'arrayToObject'), $d);
}
else {
// Return object
return $d;
}
}
/* public function to flatten an array */
public function flattenArray($array, $return = array(), $level = 0, $prefix = '') {
$level++;
foreach ($array as $key => $value) {
if (is_array($value)) {
if (count($value) > 1 && $level > 1) {
$return = $this->flattenArray($value, $return, $level, $key . '_');
}
else {
$return = $this->flattenArray($value, $return, $level);
}
}
else {
if ($prefix) {
$return[$prefix . $key] = $value;
}
else {
$return[$key] = $value;
}
}
}
return $return;
}
/* public function to convert XML to an array */
public function xmlToArray($xml) {
if ($xml instanceof SimpleXMLElement) {
$children = $xml->children();
$return = null;
}
foreach ($children as $element => $value) {
if ($value instanceof SimpleXMLElement) {
$values = (array)$value->children();
if (count($values) > 0) {
$return[$element] = $this->xmlToArray($value);
}
else {
if (!isset($return[$element])) {
$return[$element] = (string)$value;
}
else {
if (!is_array($return[$element])) {
$return[$element] = array($return[$element], (string)$value);
} else {
$return[$element][] = (string)$value;
}
}
}
}
}
if (is_array($return)) {
return $return;
}
else {
return $false;
}
}
/* public function to convert XML to a flat array */
public function xmlToFlatArray($xml) {
return $this->flattenArray($this->xmlToArray($xml));
}
/* public function to implode an array to a space delimited string */
public function implode($array) {
return implode(' ', $array);
}
########################################################################
######################### MODX USER FUNCTIONS ##########################
########################################################################
private function getModxUserId() {
if (!empty($_SESSION['member_id'])) {
$userId = $_SESSION['member_id'];
}
else {
$userId = $this->modx->user->get('id');
}
if (empty($userId)) {
$userId = 0;
}
return $userId;
}
########################################################################
########################### TIME FUNCTIONS #############################
########################################################################
/* public function to output the current system time */
public function time() {
return date('Y-m-d H:i:s', time());
}
/* public function to merge created time */
public function createdTime($data) {
$userId = $this->getModxUserId();
$time['created_by'] = $userId;
$time['created'] = date('Y-m-d H:i:s', time());
$time['updated_by'] = $userId;
$time['updated'] = date('Y-m-d H:i:s', time());
return array_merge($data, $time);
}
/* public function to merge update time */
public function updatedTime($data) {
$userId = $this->getModxUserId();
$time['updated_by'] = $userId;
$time['updated'] = date('Y-m-d H:i:s', time());
return array_merge($data, $time);
}
/* public function to get the user or member's timezone offset */
public function timeOffset() {
if ($this->modx->user) {
if ($profile = $this->modx->user->getOne('Profile')) {
$extended = $profile->get('extended');
$timezone = $extended['timezone'];
}
}
if ($_SESSION['member_id']) {
if ($member = $this->modx->getObject('XMember', (int)$_SESSION['member_id'])) {
$timezone = $member->get('timezone');
}
}
if (empty($timezone) || $timezone == 'Please select') {
$timezone = 'PST';
}
$user_timezone = new DateTimeZone($timezone);
$gmt_timezone = new DateTimeZone('GMT');
$user_current_time = new DateTime('now', $user_timezone);
$gmt_current_time = new DateTime('now', $gmt_timezone);
$time_offset = $user_timezone->getOffset($user_current_time);
return $time_offset;
}
/* public function to convert time to user's timezone */
public function userTime($time) {
return strtotime($time) + $this->timeOffset();
}
/* convert time zone */
public function convertTimeZone($dateTime, $toTimezone, $fromTimezone = 'UTC', $format = 'Y-m-d H:i:s') {
$timeObject = new DateTime($dateTime, new DateTimeZone($fromTimezone));
$timeObject->setTimezone(new DateTimeZone($toTimezone));
return $timeObject->format($format);
}
########################################################################
######################### SECURITY FUNCTIONS ###########################
########################################################################
/* public function to get a real IP address */
public function getRealIP() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) { // check ip from share internet
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // check ip is passed from proxy
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
/* public function to generate a hash key */
public function hash($value, $salt = 'ap6dsjlhMsHc') {
return hash('md5', $value . $salt);
}
/* public function to generate an authentication token */
public function generateToken($authtype) {
return 'token'; // temporary deactivation
$authtype .= '_tokens';
$token = md5(microtime() . rand(100, 999));
if (!is_array($_SESSION[$authtype])) {
$_SESSION[$authtype] = array();
}
$_SESSION[$authtype][] = $token;
return $token;
}
/* public function to validate an authentication token */
public function validateToken($token, $authtype, $remove = true) {
return true; // temporary de-activation
$authtype .= '_tokens';
if (!is_array($_SESSION[$authtype])) {
$_SESSION[$authtype] = array();
}
if (($key = array_search($token, $_SESSION[$authtype], true)) !== false) {
if ($remove) {
unset($_SESSION[$authtype][$key]);
}
return true;
}
else {
return false;
}
}
/* public function to delete an authentication token */
public function deleteToken($token, $authtype) {
return true; // temporary deactivatino
$authtype .= '_tokens';
if (($key = array_search($token, $_SESSION[$authtype], true)) !== false) {
unset($_SESSION[$authtype][$key]);
return true;
}
else {
return false;
}
}
/* public function to generate an API key */
public function generateApiKey($length = 16) {
$charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$password = '';
$count = strlen($charset);
while ($length--) {
$password .= $charset[mt_rand(0, $count-1)];
}
return $password;
}
/* public function to generate a random password */
public function generatePassword($length = 8) {
$pwgen = new PWGen();
$password = $pwgen->generate();
return $password;
// deprecated
$charset = 'abcdefghijklmnopqrstuvwxyz0123456789';
$password = '';
$count = strlen($charset);
while ($length--) {
$password .= $charset[mt_rand(0, $count-1)];
}
return $password;
}
/* public function to validate an api key */
public function validateApiKey(&$x, $apiKey) {
//$accountId = $x->account->id;
$accountId = 0;
if (empty($accountId)) {
if ($account = $this->modx->getObject('XAccount', array('api_key' => $apiKey))) {
$x->account = $this->arrayToObject($account->toArray());
return true;
}
else if ($business = $this->modx->getObject('XBusiness', array('api_key' => $apiKey))) {
$x->business = $this->arrayToObject($business->toArray());
if ($account = $this->modx->getObject('XAccount', $x->business->account_id)) {
$x->account = $this->arrayToObject($account->toArray());
}
return true;
}
else {
return false;
}
}
else if ($account = $this->modx->getObject('XAccount', $accountId)) {
if ($account->get('api_key') == $apiKey) {
$x->account = $this->arrayToObject($account->toArray());
return true;
}
else if ($business = $this->modx->getObject('XBusiness', array('api_key' => $apiKey))) {
$x->business = $this->arrayToObject($business->toArray());
if ($account = $this->modx->getObject('XAccount', $x->business->account_id)) {
$x->account = $this->arrayToObject($account->toArray());
}
return true;
}
if ($_SESSION['token'] == $_GET['token']) {
return true;
}
}
return false;
}
/* public function to save a secure session token */
public function saveSessionToken($x) {
if (isset($_REQUEST['api_key'])) {
$_SESSION['token'] = md5($x->account->id . time() . $_REQUEST['api_key']);
}
}
########################################################################
######################## VALIDATION FUNCTIONS ##########################
########################################################################
/* public function to validate a domain name */
public function validateDomain($domain, $verify = false) {
$domains = new Domains;
if ($domains->validateDomain($domain, $verify)) {
return true;
}
else {
return 'Please enter a valid domain';
}
}
/* public function to validate an email address */
public function validateEmail($email, $verify = false) {
$emails = new Emails;
if ($emails->validateEmail($email, $verify)) {
return true;
}
else {
return 'Please enter a valid email address';
}
}
########################################################################
########################## FILTER FUNCTIONS ############################
########################################################################
/* public function to filter a domain name */
public function filterDomain($domain) {
if (substr($domain, 0, 4) != 'http') {
$domain = 'http://' . $domain;
}
$pieces = parse_url($domain);
$host = isset($pieces['host']) ? $pieces['host'] : '';
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $host, $regs)) {
$domain = $regs['domain'];
if ($domain == $host) {
$domain = 'www.' . $domain;
}
else {
$parts = explode('.', $host);
$domain = $parts[0] . '.' . $domain;
}
return $domain;
}
return false;
}
/* public function to filter an email address */
public function filterEmail($email) {
return trim(strtolower($email));
}
########################################################################
######################### FACEBOOK FUNCTIONS ###########################
########################################################################
private function fbBase64UrlDecode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
public function fbParseSignedRequest(&$x) {
$signed_request = $_POST['signed_request'];
$facebookAppId = $_GET['app'];
if ($facebookApp = $this->modx->getObject('XFacebookApp', $facebookAppId)) {
$secret = $facebookApp->get('secret');
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$sig = $this->fbBase64UrlDecode($encoded_sig);
$data = json_decode($this->fbBase64UrlDecode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
$this->modx->log(modX::LOG_LEVEL_ERROR,'[X::fbParseSignedRequest] Unknown algorithm. Expected HMAC-SHA256');
return null;
}
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
$this->modx->log(modX::LOG_LEVEL_ERROR,'[X::fbParseSignedRequest] Bad Signed JSON signature!');
return null;
}
$data['app_id'] = $facebookApp->get('app_id');
$data['facebook_app_id'] = $facebookApp->get('id');
$x->facebook = $this->arrayToObject($data);
return true;
}
else {
$this->modx->log(modX::LOG_LEVEL_ERROR,'[X::fbParseSignedRequest] Invalid Facebook app id ' . $facebookAppId);
return null;
}
}
########################################################################
########################### DATA FUNCTIONS #############################
########################################################################
public function getFeed($url, $limit = 0, $offset = 0, $totalVar = 'total') {
if (!defined('MAGPIE_OUTPUT_ENCODING')) {
$outputEncoding = $this->modx->getOption('outputEncoding',$scriptProperties,'UTF-8');
define('MAGPIE_OUTPUT_ENCODING',$outputEncoding);
}
$limit = isset($limit) ? (integer) $limit : 0;
$offset = isset($offset) ? (integer) $offset : 0;
$totalVar = !empty($totalVar) ? $totalVar : 'total';
$total = 0;
$output = array();
if (!empty($url) && $this->modx->getService('rss', 'xmlrss.modRSSParser')) {
$rss = $this->modx->rss->parse($url);
if (!empty($rss) && isset($rss->items)) {
$total = count($rss->items);
$itemIdx = 0;
$idx = 0;
while (list($itemKey, $item) = each($rss->items)) {
if ($idx >= $offset) {
$output[] = $item;
$itemIdx++;
if ($limit > 0 && $itemIdx+1 > $limit) break;
}
$idx++;
}
}
else {
$this->modx->log(modX::LOG_LEVEL_ERROR, "Error parsing RSS feed at {$url}", '', 'getFeed', __FILE__, __LINE__);
}
}
return $output;
}
########################################################################
########################### FILE FUNCTIONS #############################
########################################################################
/* public function to fix a file name */
public function filenameFix($filename) {
$filename = strtolower($filename);
$filename = preg_replace('/\%/', ' percentage',$filename);
$filename = preg_replace('/\@/', ' at ', $filename);
$filename = preg_replace('/\&/', ' and ', $filename);
$filename = preg_replace('/\s[\s]+/', '-', $filename); // Strip off multiple spaces
$filename = preg_replace('/[\s\W]+/', '-', $filename); // Strip off spaces and non-alpha-numeric
$filename = preg_replace('/^[\-]+/', '', $filename); // Strip off the starting hyphens
$filename = preg_replace('/[\-]+$/', '', $filename); // strip off the ending hyphens
return $filename;
}
/* public function to get the filename from a path */
public function getFilename($path) {
$parts = explode('/', $path);
$filename = end($parts);
return $filename;
}
/* public function to get the extension from a file name */
public function getFileExtension($filename) {
$parts = explode('.', $filename);
$extension = strtolower(end($parts));
return $extension;
}
/* public function to strip the extension from a file name */
public function stripFileExtension($filename, $extension) {
$filename = str_replace('.' . $extension, '', $filename);
return $filename;
}
########################################################################
###################### FREQUENCY9 SYSTEM X FUNCTIONS ###################
########################################################################
/* public function to print debugging data */
public function debug($data) {
if ($this->modx->user->isMember('Administrator')) {
echo '<pre>';
print_r($data);
exit;
}
}
/* public function to get the application */
public function getApp($http_host = '') {
if (empty($http_host)) {
$http_host = $this->getHttpHost();
}
$parts = explode('.', $http_host);
if ($parts[0] == 'app') {
return $parts[1];
}
return false;
}
/* public function to get the current application */
public function getApplication() {
if ($this->getRootDomain($_SERVER['HTTP_HOST']) == 'addonhub') {
return 'addonhub';
}
if ($this->getRootDomain($_SERVER['HTTP_HOST']) == 'eobsystems') {
return 'eob';
}
if ($this->getSubdomain() == 'losina') {
return 'losina';
}
if ($this->getRootDomain($_SERVER['HTTP_HOST']) == 'frequency9') {
return 'core';
}
}
/* public function to get the current account */
public function getAccount() {
if ($this->getRootDomain($_SERVER['HTTP_HOST']) == 'eobsystems') {
return $this->getSubdomain($_SERVER['HTTP_HOST']);
}
else {
return '';
}
}
/* public function to return a cached array of modx user names */
public function getUsernames() {
return include_once $this->config['corePath'].'includes/usernames.inc.php';
}
/* public function to retrieve schema xml */
public function getSchemaXml() {
$schema = file_get_contents($this->modx->getOption('core_path').'components/frequency9/model/frequency9/frequency9.mysql.schema.xml');
$xml = new SimpleXMLElement($schema);
return $xml;
}
/* public function to get a schema option list */
public function getSchemaOptions() {
$xml = $this->getSchemaXml();
$optionlist = 'None||';
foreach ($xml->object as $object) {
$optionlist .= substr($object['class'], 1) . '==' . $object['class'] . '||';
}
$optionlist = substr($optionlist, 0, -2);
return $optionlist;
}
/* public function to retrieve schema as array, indexed by both Class and Key (table) */
public function getSchema() {
$xml = $this->getSchemaXml();
$meta = $this->modx->getChunk('frequency9.schema.meta.xml');
$meta_xml = new SimpleXMLElement($meta);
$schema = array();
foreach ($xml->object as $object) {
$class = (string)$object['class'];
$key = substr($object['table'], 2);
$fields = array();
foreach ($object->field as $field) {
$field_key = (string)$field['key'];
$fields[$field_key] = array(
'dbtype' => (string)$field['dbtype'],
'precision' => (string)$field['precision'],
'phptype' => (string)$field['phptype']
);
//$field_meta = $meta_xml->xpath('/model/object[@class="' . $class . '"]/field[@key="' . $field['key'] . '"]');
//$field_meta = $field_meta[0];
/*if (is_object($field_meta)) {
foreach ($field_meta->attributes() as $attribute => $value) {
if ($attribute != 'key') {
$fields[$field_key][$attribute] = (string)$value;
}
}
}*/
}
$schema[$class] = array(
'key' => $key,
'fields' => $fields
);
$schema[$key] = array(
'class' => $class,
'fields' => $fields
);
}
return $schema;
}
/* public function to flatten an array into a placeholder array */
public function arrayToPlaceholders($array, $return = array(), $level = 0, $prefix = '') {
$level++;
foreach ($array as $key => $value) {
if (is_array($value)) {
$return = $this->arrayToPlaceholders($value, $return, $level, $key . '.');
}
else {
if ($prefix) {
$return[$prefix . $key] = $value;
}
else {
$return[$key] = $value;
}
}
}
return $return;
}
/* public function to convert a underscore delimited string to a label */
public function label($str) {
$label = str_replace('_id', '', $str);
$label = ucwords(str_replace('_', ' ', $label));
return $label;
}
/* public function to parse a button array */
public function parseButtons($buttons) {
$output = '';
foreach ($buttons as $button) {
if (is_array($button)) {
$key = $button[0];
$label = $this->label($button[0]);
$icon = $button[1];
$url = (empty($button[2])) ? '#' : $button[2];
$btnClass = (empty($button[3])) ? '' : ' ' . $button[3];
$iconClass = (empty($button[4])) ? '' : ' ' . $button[4];
$output .= '<a id="' . $key . '" class="btn' . $btnClass . '" href="' . $url . '"><i class="icon-' . $icon . $iconClass . '"></i> ' . $label . '</a>';
}
else if ($button == 'save') {
$output .= '<button type="submit" class="btn btn-success" id="save" name="save" value="save">' .
'<i class="icon-ok-sign icon-white"></i> Save</button>';
}
$output .= ' ';
}
return $output;
}
/* public function to make a URL */
public function makeUrl($resource_id, $data = '') {
$url = '/' . $this->modx->makeUrl($resource_id);
if (is_array($data)) {
$query = http_build_query($data, '', '&');
$url .= '?' . $query;
}
return $url;
}
/* public function to run a hook */
public function runHook(&$x, $hook) {
$hook = $x->app . '.' . $hook;
if ($snippet = $this->modx->getObject('modSnippet', array('name' => $hook))) {
$this->modx->setPlaceholder('x', $x);
$success = $this->modx->runSnippet($hook);
$x = $this->modx->getPlaceholder('x');
}
}
/* public function to run a prehook */
public function runPreHook(&$x, $hook) {
$hook = $x->app . '.' . $hook . '.prehook' . $x->dev;
$this->runHook($x, $hook);
}
/* public function to run a posthook */
public function runPostHook(&$x, $hook) {
$hook = $x->app . '.' . $hook . '.posthook' . $x->dev;
$this->runHook($x, $hook);
}
/* public function to process alert messages */
public function processAlerts($rawAlerts) {
$alerts = array();
foreach ($rawAlerts as $type => $alertMessages) {
if (is_array($alertMessages)) {
foreach ($alertMessages as $alertMessage) {
if (is_array($alertMessage)) {
$alerts[] = array_merge(array('type' => $type), $alertMessage);
}
else {
$alerts[] = array('type' => $type, 'message' => $alertMessage);
}
}
}
}
return $alerts;
}
/* public function to convert a url to a period-delimited key */
public function keyFromUrl($url) {
$key = str_replace('/', '.', $url);
if (substr($key, 0, 1) == '.') {
$key = substr($key, 1);
}
if (substr($key, -1) == '.') {
$key = substr($key, 0, -1);
}
return $key;
}
/* public function to load an object */
public function loadObject($class, $query, $exclude = array()) {
if ($object = $this->modx->getObject($class, $query)) {
$object_data = $object->toArray();
/*if (is_array($exclude)) {
foreach ($exclude as $key) {
unset($object_data[$key]);
}
}*/
foreach ($object_data as $key => &$value) {
if (!in_array($key, $exclude) && substr($key, 0, 5) == 'json_') {
$json_data = $this->decode($value);
foreach ($json_data as $json_key => $json_value) {
if (!empty($json_value)) {
$object_data[$json_key] = $json_value;
}
}
unset($object_data[$key]);
}
}
return $this->arrayToObject($object_data);
}
else {
return false;
}
}
/* public function to load object json */
public function loadObjectJson($objectData, $class, $id, $field) {
if ($object = $this->modx->getObject($class, $id)) {
$jsonData = $this->decode($object->get($field));
foreach ($jsonData as $jsonKey => $jsonValue) {
if (!empty($jsonValue) || $jsonValue === '0') {
$objectData->{$jsonKey} = $jsonValue;
}
}
return $objectData;
}
}
/* public function to parse an object into placeholders */
public function objectToPlaceholders($object) {
$array = $this->objectToArray($object);
$array = $this->arrayToPlaceholders($array);
return $array;
}
/* public function to set SystemX placeholders */
public function setPlaceholders($x) {
$this->modx->setPlaceholders($this->objectToPlaceholders($x));
}
/* public function to get a system setting */
public function getSetting($key) {
if ($setting = $this->modx->getObject('XSystem', array('setting' => $key))) {
$value = $setting->get('value');
}
return $value;
}
/* public function to save a system setting */
public function saveSetting($key, $value) {
if ($setting = $this->modx->getObject('XSystem', array('setting' => $key))) {
$setting->set('value', $value);
}
else {
$setting = $this->modx->newObject('XSystem');
$setting->set('setting', $key);
$setting->set('value', $value);
}
$setting->save();
}
/* public function to retrieve a MODX user name */
public function getModUserName($id) {
if (!empty($id)) {
$user = $this->modx->getObject('modUser', $id);
}
else {
return 'System';
}
if (is_object($user)) {
if ($profile = $user->getOne('Profile')) {
$fullname = $profile->get('fullname');
return $fullname;
}
}
else {
return 'System';
}
}
/* public function to retrieve the mod user or member */
public function getModName($id) {
if (isset($_SESSION['member_id'])) {
if ($member = $this->modx->getObject('XMember', $_SESSION['member_id'])) {
$name = $member->get('name');
if (empty($name)) {
$name = $member->get('first_name');
$name .= ' ' . $member->get('last_name');
}
}
else {
$name = 'System';
}
}
else {
$name = $this->getModUserName($id);
}
return $name;
}
/* public function to format the mod time */
public function getModTime($time) {
return date('l, F j, y g:i A', $this->userTime($time));
}
/* public function to parse a user-managed chunk */
public function parseUserChunk($chunk, $newlines = false) {
$chunk = str_replace('[{', '[[', $chunk);
$chunk = str_replace('}]', ']]', $chunk);
if ($newlines) {
$chunk = str_replace("\n", '<br>', $chunk);
}
return $chunk;
}
/* public function to inject a css link */
public function injectCssLink(&$x, $link) {
if (!empty($link)) {
$x->css_links[] = $link;
}
}
/* public function to inject css links */
public function injectCssLinks(&$x, $links) {
$linksEolArray = $this->eolToArray($links);
$linksPipeArray = explode('|', $links);
if (is_array($linksEolArray)) {
$links = $linksEolArray;
}
if (is_array($linksPipeArray)) {
$links = $linksPipeArray;
}
if (is_array($links)) {
foreach ($links as $link) {
if (!is_array($link) && !empty($link)) {
$x->css_links[] = $link;
}
}
}
}
/* public function to inject a javascript link */
public function injectJsLink(&$x, $link) {
if (!empty($link)) {
$x->javascript_links[] = $link;
}
}
/* public function to inject javascript links */
public function injectJsLinks(&$x, $links) {
$linksEolArray = $this->eolToArray($links);
$linksPipeArray = explode('|', $links);
if (is_array($linksEolArray)) {
$links = $linksEolArray;
}
if (is_array($linksPipeArray)) {
$links = $linksPipeArray;
}
if (is_array($links)) {
foreach ($links as $link) {
if (!is_array($link) && !empty($link)) {
$x->javascript_links[] = $link;
}
}
}
}
/* public function to inject css */
public function injectCss(&$x, $css) {
if (!empty($css)) {
$x->css[] = $css;
}
}
/* public function to inject javascript */
public function injectJs(&$x, $javascript) {
if (!empty($javascript)) {
$x->javascript[] = $javascript;
}
}
/* public function to inject javascript into document head */
public function injectJsHead(&$x, $javascript) {
if (!empty($javascript)) {
$x->javascript_head[] = $javascript;
}
}
/* public function to inject DataTables */
public function injectDatatables(&$x) {
}
/* public function to inject all page assets */
public function injectAssets(&$x, $mode = '') {
$x->page->css_links = '';
$x->page->javascript_links = '';
$x->page->css = '';
$x->page->javascript = '';
$x->page->javascript_head = '';
if ($mode == 'embed') {
$css_links_ph = 'css_links2';
$javascript_links_ph = 'javascript_links2';
$css_ph = 'css2';
$javascript_ph = 'javascript2';
$javascript_head_ph = 'javascript_head2';
}
else {
$css_links_ph = 'css_links';
$javascript_links_ph = 'javascript_links';
$css_ph = 'css';
$javascript_ph = 'javascript';
$javascript_head_ph = 'javascript_head';
}
if (is_array($x->css_links)) {
foreach ($x->css_links as $link) {
$x->page->{$css_links_ph} .= " \n" . '<link rel="stylesheet" href="' . $link . '" />';
}
}
if (is_array($x->javascript_links)) {
foreach ($x->javascript_links as $link) {
$x->page->{$javascript_links_ph} .= "\n " . '<script src="' . $link . '"></script>';
}
}
if (is_array($x->css)) {
foreach ($x->css as $css) {
$css = str_replace('<style type="text/css">', '', $css);
$css = str_replace('</style>', '', $css);
$x->page->{$css_ph} .= "\n" . '<style type="text/css">' . $css . '</style>';
}
}
if (is_array($x->javascript)) {
foreach ($x->javascript as $javascript) {
$javascript = str_replace('<script type="text/javascript">', '', $javascript);
$javascript = str_replace('</script>', '', $javascript);
$x->page->{$javascript_ph} .= "\n" . '<script type="text/javascript">' . $javascript . '</script>';
}
}
if (is_array($x->javascript_head)) {
foreach ($x->javascript_head as $javascript) {
$javascript = str_replace('<script type="text/javascript">', '', $javascript);
$javascript = str_replace('</script>', '', $javascript);
$x->page->{$javascript_head_ph} .= "\n" . '<script type="text/javascript">' . $javascript . '</script>';
}
}
}
/* public function to decode object json */
public function decodeObjectJson(&$x, $key, $json) {
$data = $this->decode($json);
if (is_array($data)) {
foreach ($data as $field => $value) {
if (!empty($value)) {
$x->{$key}->{$field} = $value;
echo $value;
}
}
}
}
/* public function to check for reserved alias names */
public function checkReservedAliasNames($alias) {
switch($alias) {
case 'affiliatecenter':
case 'dashboard':
case 'profile':
case 'capturepage':
case 'clients':
case 'css':
case 'error':
case 'form':
case 'funnel':
case 'landingpage':
case 'pages':
case 'project':
case 'affiliates':
case 'filebox':
case 'service':
case 'subscribe':
case 'ref':
case 'reset-password':
case 'rpc':
case 'webservice':
return true;
break;
case 'members':
return false;
break;
default:
return false;
}
}
/* public function to build a website url */
public function websiteUrl($website_id, $page_id = 0, $preview = 0, $suffix = '', $forceMtsUrl = 0) {
$website = $this->modx->getObject('XWebsite', $website_id);
$prefix = '';
$path = '';
if ($page_id) {
$page = $this->modx->getObject('XPage', $page_id);
$path = $this->aliasToPath($page->get('alias'));
$type = $page->get('type');
if ($type == 'capture' || $type == 'funnel' || $type == 'thankyou' || $type == 'value') {
$prefix = '';
}
else if ($type == 'landing') {
$prefix = '';
}
else if ($type == 'members') {
$prefix = $website->get('membersite_prefix') . '/';
}
else if ($type == 'member') {
$prefix = '';
}
else if ($type == 'page') {
$prefix = '';
}
else {
$prefix = $type . '/';
}
if (!empty($suffix)) {
$path = substr($path, 0, -1);
$path .= '-' . $suffix . '/';
}
}
if ($preview) {
$domain = $website->get('subdomain');
$domain .= '.websitepreviewer.com';
}
else if ($suffix == 'subscribe') {
$domain = $website->get('subdomain');
$domain .= '.marketingtimesaver.com';
}
else {
$domain = $website->get('domain');
if (empty($domain) || $forceMtsUrl) {
$domain = $website->get('subdomain');
$domain .= '.marketingtimesaver.com';
}
}
$url = 'http://' . $domain . '/' . $prefix . $path;
if ($page_id == 110) {
//echo $url; exit;
}
return $url;
}
/* private function to generate an integration link */
private function integrationLink($integration, $field, $value) {
switch($field) {
case 'inf_contact_id':
$url = 'https://' . $integration->infusionsoft->subdomain . '.infusionsoft.com/Contact/manageContact.jsp?view=edit&ID=' . $value;
$link = 'Edit Contact';
break;
case 'inf_company_id':
$url = 'https://' . $integration->infusionsoft->subdomain . '.infusionsoft.com/Compoany/manageCompany.jsp?view=edit&ID=' . $value;
$link = 'Edit Company';
break;
case 'inf_order_id':
$url = 'https://' . $integration->infusionsoft->subdomain . '.infusionsoft.com/Job/manageJob.jsp?view=edit&ID=' . $value;
$link = 'Edit Order';
break;
}
return '<a href="' . $url . '" target="_blank">' . $link . '</a>';
}
/* private function to parse field options */
private function parseOptions($options) {
$options = explode('||', $options);
$fieldOptions = array();
foreach ($options as $option) {
$optionArray = explode('==', $option);
if ($optionArray[0] != $option) {
$optionKey = $optionArray[0];
$optionLabel = $optionArray[1];
}
else {
$optionKey = $option;
$optionLabel = $this->label($option);
}
$optionLabel = str_replace('-', '&#8209;', $optionLabel);
$optionLabel = str_replace(' ', '&nbsp;', $optionLabel);
$fieldOptions[$optionKey] = $optionLabel;
}
return $fieldOptions;
}
/* public function to format a field value */
public function formatField(&$x, $field, $value, $objectId, $fieldData, $classKey = '', $action = '') {
$action = (empty($action)) ? $x->action : $action;
$classKey = (empty($classKey)) ? $x->object->key : $classKey;
if ($action == 'summary') {
$fieldData = $fieldData[$field];
}
if (!empty($fieldData['options'])) {
$options = $fieldData['options'];
}
if (!empty($fieldData['admin_options'])) {
$options = $fieldData['admin_options'];
}
if (!empty($options)) {
$fieldOptions = $this->parseOptions($options);
}
if ($field == 'name' && $action == 'list') {
$value = str_replace(' ', '&nbsp;', $value);
$value = '<a data-id="' . $objectId . '" data-name="' . $value . '" href="' . $x->object->link . $objectId . '/edit/">' . $value . '</a>';
}
else if ($field == 'name' && $action == 'summary') {
$objectLink = $x->object->edit_link;
$objectLink = str_replace('edit', '', $objectLink);
$classKey = str_replace('_', '-', $classKey);
$value = '<a data-id="' . $objectId . '" data-name="' . $value . '" href="' . $objectLink . $classKey . 's/' . $objectId . '/edit/">' . $value . '</a>';
$value = str_replace('//', '/', $value);
}
else if ($options) {
$value = $fieldOptions[$value];
}
else if ($fieldData['type'] == 'yesno') {
if ($value == 1) {
$value = 'Yes';
}
else {
$value = 'No';
}
}
else if ($fieldData['type'] == 'url' && $action == 'list') {
$value = '<a href="http://' . $value . '" target="_blank">' . $value . '</a>';
}
else if ($fieldData['type'] == 'integration_link') {
$value = $this->integrationLink($x->integration, $field, $value);
}
else if ($fieldData['type'] == 'time') {
if ($value != '00:00:00') {
$value = date($fieldData['dateformat'], strtotime($value));
}
}
else if ($fieldData['phptype'] == 'date') {
if ($value != '-1-11-30' && !empty($value)) {
$value = date('n/j/y', strtotime($value));
}
else {
$value = '';
}
}
else if ($fieldData['phptype'] == 'datetime') {
$value = date('n/j/y g:i A', strtotime($value));
$value = str_replace(' ', '&nbsp;', $value);
}
return $value;
}
/* #### public function to format an object field value - ### this one is deprecated?? ### */
public function formatValue(&$x, $value, $field, $fieldData) {
/* options */
if ($fieldData['options']) {
$options = explode('||', $fieldData['options']);
$fieldOptions = array();
foreach ($options as $option) {
$optionArray = explode('==', $option);
if ($optionArray[0] != $option) {
$optionKey = $optionArray[0];
$optionLabel = $optionArray[1];
}
else {
$optionKey = $option;
$optionLabel = $this->label($option);
}
$optionLabel = str_replace('-', '&#8209;', $optionLabel);
$optionLabel = str_replace(' ', '&nbsp;', $optionLabel);
$fieldOptions[$optionKey] = $optionLabel;
}
$value = $fieldOptions[$value];
}
else if ($fieldData['phptype'] == 'date') {
$value = date('n/j/y', strtotime($value));
}
else if ($fieldData['dbtype'] == 'datetime') {
$value = date('n/j/y g:i:s A', strtotime($value));
$value = str_replace(' ', '&nbsp;', $value);
}
return $value;
}
/* public function to format object field interface */
public function buildField(&$x, $field, $fieldData, $delimiter, $value = '', $tab = '') {
$action = $x->action;
$classKey = $x->object->key;
$id = $classKey . '_' . $field;
$name = $classKey . $delimiter . $field;
$label = $fieldData['label'];
$classes = array('x_field');
$controlClasses = array();
$tooltip = (empty($fieldData['tooltip'])) ? '': ' rel="tooltip" data-original-title="' . $fieldData['tooltip'] . '"';
$field_class = (empty($fieldData['class'])) ? array() : explode(',', $fieldData['class']);
$toggledBy = (empty($fieldData['toggledby'])) ? '' : ' data-toggled-by="' . $fieldData['toggledby'] . '_toggle"';
/* get value options */
if (!empty($fieldData['options'])) {
$options = $fieldData['options'];
}
if (!empty($fieldData['admin_options']) && $this->modx->user->isMember('Administrator')) {
$options = $fieldData['admin_options'];
}
if ($this->modx->user->isMember('Administrator') && !empty($fieldData['admin_options'])) {
$options = $fieldData['admin_options'];
}
/* set a default value */
if ($x->object->updated == $x->object->created && isset($fieldData['default']) && empty($value)) {
if (substr($fieldData['default'], 0, 3) == 'x::') {
$x_field = str_replace('x::', '', $fieldData['default']);
$x_pair = explode('.', $x_field);
$value = $x->{$x_pair[0]}->{$x_pair[1]};
}
else {
$value = $fieldData['default'];
}
}
/* hide fields from users */
if ($action == 'read' && $fieldData['edit'] == 'hide') {
$hideField = true;
}
/* date/time */
if ($fieldData['dbtype'] == 'date' || $fieldData['dbtype'] == 'datetime') {
$classes[] = 'date';
}
if ($fieldData['dbtype'] == 'time') {
$classes[] = 'time';
}
/* required fields */
if ($fieldData['required'] == 'yes') {
$controlClasses[] = 'required';
$requiredLabel = ' *';
}
/* readonly fields */
if ($action == 'read' && $fieldData['readonly'] == 'yes' && !$this->modx->user->isMember('Administrator')) {
$readonly = ' readonly="readonly"';
$tooltip = '';
}
else {
$readonly = '';
}
/* check for blank date fields */
if ($fieldData['phptype'] == 'date' && $value == '-1-11-30') {
$value = '';
}
if ($fieldData['phptype'] == 'datetime' && $value == '-1-11-30 00:00:00') {
$value = '';
}
if ($fieldData['phptype'] == 'datetime' && empty($value)) {
$value = date('m/d/Y H:i:00');
}
/* class */
$classes = array_merge($classes, $field_class);
$class = ' class="' . implode(' ', $classes) . '"';
/* label */
if ($fieldData['type'] != 'hidden' && !$hideField) {
$labelOutput = '<label id="' . $id . '_label"' . $toggledBy . '>' . $label . $requiredLabel . '</label>';
}
/* same as checkbox */
if ($sameas = $fieldData['sameas']) {
$output .= '<label style="font-size: 11px;"><input type="checkbox" class="sameas" id="' . $field . '_sameas" /> Same as ' .
$this->label($sameas) . '</label>';
$this->injectJs($x, "$('#". $field . "_sameas').click(function() { if ($(this).attr('checked') == 'checked') { $('#" . $id . "').val($('#" . $classKey . "_" . $sameas . "').val()); } } );");
}
/* hide fields */
if ($hideField) {
$output .= '<input type="hidden" id="' . $id . '" name="' . $name . '" value="' . $value . '" />';
}
/* options */
else if (!empty($options) && $fieldData['type'] != 'pretty') {
// custom override
if ($classKey == 'page' && $field == 'type' && !$this->modx->user->isMember('Administrator')) {
if ($this->modx->user->isMember('Unlimited') || $this->modx->user->isMember('Mts-Level-OnlineProducts')) {
$options .= '||member==Online Product';
}
}
$options = explode('||', $options);
if (empty($value) && !empty($fieldData['default_option'])) {
$value = $fieldData['default_option'];
}
foreach ($options as $option) {
$optionArray = explode('==', $option);
if ($optionArray[0] != $option) {
$optionKey = $optionArray[0];
$optionLabel = $optionArray[1];
}
else {
$optionKey = $option;
$optionLabel = $this->label($option);
}
$optionList[$optionLabel] = array(
'key' => $optionKey,
'label' => $optionLabel
);
}
$optionOutput = '<option></option>';
sort($optionList);
foreach ($optionList as $option) {
$selected = '';
if ($value == $option['key']) {
$selected = ' selected="selected"';
$hasSelection = true;
}
$optionOutput .= '<option value="' . $option['key'] . '"' . $selected . '>' . $option['label'] . '</option>';
}
if (!empty($value) && !$hasSelection && !$this->modx->user->isMember('Administrator')) {
$classes[] = 'readonly';
$readonly = ' readonly="readonly"';
$class = ' class="' . implode(' ', $classes) . '"';
$output .= '<input type="text" name="' . $name . '" id="' . $id . '" ' . $class . $readonly . $tooltip . ' value="' . $value . '"></input>';
}
else {
$output .= '<select name="' . $name . '" id="' . $id . '" ' . $class . $readonly . $tooltip . '>' . $optionOutput . '</select>';
}
}
/* related object options */
else if ($fieldData['type'] == 'related') {
$option_list = '';
$c = $this->modx->newQuery($fieldData['related']);
$filter = array();
if ($field == 'business_id') {
$c->where(array('account_id' => $x->account->id));
}
elseif ($field != 'account_id') {
$c->where(array('account_id' => $x->account->id, 'business_id' => $x->business->id));
}
if ($fieldData['relatedfilter']) {
$parts = explode('&', $fieldData['relatedfilter']); // deprecated
if (strpos($fieldData['relatedfilter'], '||') !== false) {
$parts = explode('||', $fieldData['relatedfilter']);
}
foreach ($parts as $part) {
$f = explode('::', $part);
if (strpos($f[1], '.') !== false) {
$xField = explode('.', $f[1]);
$filter = array($f[0] => $x->{$xField[0]}->{$xField[1]});
}
else {
$filter = array($f[0] => $f[1]);
}
if ($f[2] == 'OR') {
$c->where($filter, xPDOQuery::SQL_OR);
}
else {
$c->where($filter);
}
}
}
$c->sortby('name');
$options = $this->modx->getIterator($fieldData['related'], $c);
$option_list = '<option></option>';
if ($fieldData['related_usename'] == 'yes') {
if ($relatedObject = $this->modx->getObject($fieldData['related'], array('name' => $value))) {
$value = $relatedObject->get('id');
}
}
foreach ($options as $option) {
$selected = '';
$currentId = $option->get('id');
if ($currentId == $value) {
$selected = ' selected="selected"';
}
$option_list .= '<option value="' . $currentId . '"' . $selected . '>' . $option->get('name') . '</option>';
}
$output .= '<select name="' . $name . '" id="' . $id . '" ' . $class . $readonly . $tooltip . '>' . $option_list . '</select>';
}
/* pretty options */
else if ($fieldData['type'] == 'pretty') {
$prettyOptions = array('value' => $value, 'selected.' . $value => 'selected');
$output .= $this->modx->parseChunk('x.' . $classKey . '.' . $field . '.pretty_options', $prettyOptions, '[[+');
}
/* file links */
else if ($fieldData['type'] == 'file_link') {
$website = $this->modx->getObject('XWebsite', $x->x_file->website_id);
$folder = str_replace('www.', '', $website->get('domain'));
$link = 'http://marketingtimesaver.s3-us-west-2.amazonaws.com/' . $folder . '/filebox/' . $value;
$output .= '<p class="help-block"><a href="' . $link . '" target="_blank">' . $value . '</a></p>';
}
/* file fields */
else if ($fieldData['type'] == 'files') {
$output .= '<input class="x_file_field" type="hidden" name="' . $name . '" id="' . $id . '" value="' . $value . '" />';
$output .= '<input id="' . $id . '_upload" name="' . $name . '_upload" class="x_file_uploadify" type="file" multiple="true" />';
$output .= '<p><a class="x_fbrowser_btn" data-toggle="modal" data-input-field="' . $id . '" href="#x_file_browser">Select Existing Files</a></p>';
$output .= '<div class="x_file_attachments" id="' . $id . '_files"></div>';
}
/* image fields */
else if ($fieldData['type'] == 'image') {
$output .= '<input type="hidden" name="' . $name . '" id="' . $id . '" value="' . $value . '" />';
$output .= '<input id="' . $id . '_upload" name="' . $name . '_upload" type="file" multiple="true" />';
if (!empty($value)) {
$output .= '<div class="attachment" id="' . $id . '_image"><a href="' . $value . '" target="_blank"><img src="' . $value . '" /></a></div>';
}
else {
$output .= '<div class="attachment" id="' . $id . '_image"></div>';
}
}
/* video fields */
else if ($fieldData['type'] == 'video') {
$output .= '<input class="x_video_field" type="hidden" name="' . $name . '" id="' . $id . '" value="' . $value . '" />';
$output .= '<input id="' . $id . '_upload" name="' . $name . '_upload" type="file" multiple="true" />';
$output .= '<p><a class="x_vbrowser_btn" data-toggle="modal" data-input-field="' . $id . '" href="#x_video_browser">Select Existing Video</a></p>';
$output .= '<div class="x_video_attachment" id="' . $id . '_image" style="display: none;"></div>';
/*
if (!empty($value)) {
$output .= '<div class="x_video_attachment" id="' . $id . '_image">' .
'<a href="' . $value . '" target="_blank"><img src="' . $value . '" /></a></div>';
}
else {
$output .= '<div class="x_video_attachment" id="' . $id . '_image"></div>';
}*/
}
/* yes/no toggles */
else if ($fieldData['type'] == 'yesno') {
$output .= '<input type="hidden" id="' . $id . '_toggle" name="' . $name . '" value="' . $value . '" />';
$output .= '<div class="btn-group x_toggle" data-toggle-name="' . $id . '_toggle" data-toggle="buttons-radio" autocomplete="off"><button type="button" class="btn" value="1">Yes</button><button type="button" class="btn" value="0">No</button></div>';
}
/* integration links */
else if ($fieldData['type'] == 'integration_link') {
$output .= $this->integrationLink($x->integration, $field, $value);
}
/* hidden fields */
else if ($fieldData['type'] == 'hidden') {
$output .= '<input type="hidden" id="' . $id . '" name="' . $name . '" value="' . $value . '" />';
}
/* default mysql fields */
else {
switch ($fieldData['dbtype']) {
case 'datetime':
$value = $this->convertTimeZone($value, $x->account->timezone);
$this->injectJs($x, "$('#". $id . "__time').timepicker({'timeFormat': '" . $fieldData['timeformat'] . "'});");
$output .= '<div style="float:left; margin-right:6px;"><input type="text" name="' . $name . '[date]" id="' . $id . '__date" class="date" value="' . date('Y-m-d', strtotime($value)) . '"></div>';
$output .= '<input type="text" name="' . $name . '[time]" id="' . $id . '__time" class="time" value="' . date('H:i', strtotime($value)) . '">';
$output .= '<span class="help-inline" style="margin-bottom: 10px;">' . $x->account->timezone . '</span>';
//echo $output;
//exit;
break;
case 'time':
$value = date($fieldData['dateformat'], strtotime($value));
$this->injectJs($x, "$('#". $id . "').timepicker({'timeFormat': '" . $fieldData['dateformat'] . "'});");
$output .= '<input type="text" name="' . $name . '" id="' . $id . '" ' . $class . $readonly . $tooltip . $maxlength . $toggledBy . ' value="' . $value . '" />';
break;
case 'text':
case 'mediumtext':
case 'longtext':
$output .= '<textarea name="' . $name . '" id="' . $id . '" ' . $class. $readonly . $tooltip . $toggledBy . '>' . $value . '</textarea>';
break;
case 'int':
case 'double':
case 'varchar':
case 'date':
case 'datetime':
$maxlength = ' maxlength="' . $field_data['precision'] . '"';
$output .= '<input type="text" name="' . $name . '" id="' . $id . '" ' . $class . $readonly . $tooltip . $maxlength . $toggledBy . ' value="' . $value . '" />';
break;
}
}
/* append to input */
if ($fieldData['type'] == 'time') {
$output = '<div class="input-append">' . $output . '<span class="add-on">' . $x->account->timezone . '</span></div>';
}
/* control group wrapper */
$controlClass = implode(' ', $controlClasses);
if ($fieldData['type'] == 'datetime') {
$output = '<div class="control-group controls-row ' . $controlClass . '" id="' . $id . '-control">' . $labelOutput . '<div class="controls">' . $output . '</div></div>';
}
else {
$output = '<div class="control-group ' . $controlClass . '" id="' . $id . '-control">' . $labelOutput . '<div class="controls">' . $output . '</div></div>';
}
/* help text */
if (!empty($fieldData['helptext'])) {
if (substr($fieldData['helptext'], 0, 5) == 'chunk') {
$chunk_name = str_replace('chunk=', '', $fieldData['helptext']);
$output .= $this->modx->getChunk($chunk_name);
}
else {
$output .= '<p class="help-block">' . $fieldData['helptext'] . '</p>';
}
}
/* a few custom output functions */
if ($action == 'read' && $x->object->class == 'XPage' && $field == 'alias') {
$url = $this->websiteUrl($x->x_page->website_id, $x->object->id);
$previewUrl = $this->websiteUrl($x->x_page->website_id, $x->object->id, 1);
$output .= '<p class="x_page_url" style="margin-top: 0px; font-size: 11px;">Live Url: <a href="' . $url . '" target="_blank">' . $url . '</a></p>';
//$output .= '<p class="x_page_preview_url" style="margin-top: 0px; font-size: 11px; margin-bottom: 16px;">Preview Url: <a href="' . $previewUrl . '" target="_blank">' . $previewUrl . '</a></p>';
}
if ($action == 'read' && $x->object->class == 'XPage' && $field == 'json_capture_autoresponder') {
$url = $this->websiteUrl($x->x_page->website_id, $x->object->id, 0, 'subscribe');
$output = '<p class="x_page_link" style="margin-top: 0px; font-size: 11px;">Integration Url: <a href="' . $url . '" target="_blank">' . $url . '</a></p>' . $output;
}
if ($action == 'read' && $x->object->class == 'XFacebookApp' && $field == 'x_facebook_app_id') {
$appUrl = 'https://developers.facebook.com/apps/' . $value . '/summary/';
$output .= '<p style="margin-top: 0px; font-size: 11px;"><a href="' . $appUrl . '" target="_blank">' . $appUrl . '</a></p>';
}
return $output;
}
/* public function to generate a folder name */
public function folder($string) {
$string = strtolower($string);
$folder = preg_replace('/[^a-z\d]/i', '', $string);
return $folder;
}
/* public function to generate a folder from a domain name */
public function domainFolder($domain) {
$domain = strtolower($domain);
$folder = str_replace('www.', '', $domain);
return $folder;
}
/* public function to convert a domain to a folder */
public function domainToFolder($domain) {
$folder = strtolower($domain);
$folder = str_replace('http://', '', $folder);
$folder = str_replace('https://', '', $folder);
$folder = str_replace('www.', '', $folder);
$folder = str_replace('/', '', $folder);
return $folder;
}
/* public function to output a file icon */
public function fileIcon($type, $width = 48, $height = 48) {
switch ($type) {
case 'pdf':
$thumb = 'apps/adobe-acrobat-reader.png';
break;
case 'doc':
case 'docx':
$thumb = 'office/word.png';
break;
case 'csv':
case 'xls':
case 'xlsx':
$thumb = 'office/excel.png';
break;
case 'ppt':
case 'pptx':
$thumb = 'office/powerpoint.png';
break;
default:
$thumb = 'os/downloads.png';
break;
}
$thumbnail_url = $this->modx->getOption('frequency9.icon_url') . $thumb;
$thumbnail = '[[phpthumbof? &input=`' . $thumbnail_url . '` &options=`&w=' . $width . '&h=' . $height . '`]]';
return $thumbnail;
}
/* public function to output alerts */
public function setAlerts(&$x) {
if (is_array($_SESSION['alerts']) || is_array($x->alerts) || isset($_GET['success'])) {
$alerts = array_merge((array)$_SESSION['alerts'], (array)$x->alerts);
$x->alerts = '';
if (!empty($_GET['success'])) {
$alerts[] = array('type' => 'success', 'message' => $_GET['success']);
}
foreach ($alerts as $alert) {
if ($alert['type'] == 'error' && !isset($alert['title'])) {
$alert['title'] = 'Whoops, we found an error!';
}
if ($alert['type'] == 'info' && !isset($alert['title'])) {
$alert['title'] = 'Tip!';
}
if ($alert['type'] == 'success' && !isset($alert['title'])) {
$alert['title'] = 'Success!';
}
if ($alert['type'] == 'warning' && !isset($alert['title'])) {
$alert['title'] = 'Warning!';
}
$x->page->alerts .= $this->modx->parseChunk('alert.' . $alert['type'], $alert, '[[+');
}
unset($_SESSION['alerts']);
}
}
########################################################################
############################ PEOPLE FUNCTIONS ##########################
########################################################################
/* public function to create an email address */
/* public function to create a contact */
/* public function to create a website member */
public function createMember($memberData, $password = '', $memberPageData = '') {
// load member data
$account = $this->modx->getObject('XAccount', $memberData['account_id']);
$website = $this->modx->getObject('XWebsite', $memberData['website_id']);
$websiteOptions = $this->decode($website->get('json_options'));
$memberData['name'] = $memberData['first_name'] . ' ' . $memberData['last_name'];
$memberData['email'] = $this->filterEmail($memberData['email']);
$memberData['timezone'] = $account->get('timezone');
$memberData['join_date'] = $this->time();
// search filter to find pre-existing member
$filter = array(
'account_id' => $memberData['account_id'],
'business_id' => $memberData['business_id'],
'website_id' => $memberData['website_id'],
'email' => $memberData['email']
);
// create a new member
if (!($member = $this->modx->getObject('XMember', $filter))) {
$member = $this->modx->newObject('XMember');
$memberData = $this->createdTime($memberData);
if (empty($password)) {
$password = $this->generatePassword();
}
$memberData['password'] = $this->hash($password);
$newMember = true;
}
// update existing member
else {
$existingMemberData = $member->toArray();
$existingMemberData['name'] = $memberData['name'];
$existingMemberData['first_name'] = $memberData['first_name'];
$existingMemberData['last_name'] = $memberData['last_name'];
if (!empty($memberData['inf_contact_id'])) {
$existingMemberData['inf_contact_id'] = $memberData['inf_contact_id'];
}
if (!empty($memberData['inf_company_id'])) {
$existingMemberData['inf_company_id'] = $memberData['inf_company_id'];
}
$memberData = $existingMemberData;
if (!empty($password)) {
$memberData['password'] = $this->hash($password);
}
$newMember = false;
}
// save member
$member->fromArray($memberData);
$member->save();
// send the welcome email
if ($newMember || is_array($memberPageData)) {
// password message
if (empty($password)) {
$password = 'Please continue using your existing ' . $website->get('title') . ' password.';
}
// tech support email
$techEmail = strtolower(preg_replace("/\s+/", " ", $account->get('name')));
$techEmail = str_replace(' ', '.', $techEmail) . '@onlineproductsupport.com';
if ($memberData['website_id'] == 468) {
$techEmail = '[email protected]';
}
// new member placeholders
$ph = array(
'website.title' => $website->get('title'),
'website.url' => 'http://' . $website->get('domain') . '/' . $website->get('membersite_prefix') . '/',
'member.email' => $memberData['email'],
'member.password' => $password,
'website.support_name' => $websiteOptions['support_name'],
'website.support_email' => $websiteOptions['support_email'],
'website.tech_support_email' => $techEmail
);
if (is_array($memberPageData)) {
$ph['website.url'] = 'http://' . $website->get('domain') . '/' . $memberPageData['alias'] . '/';
}
if ($memberData['website_id'] == 582) {
$ph['website.url'] = 'http://successsquad.marketingtimesaver.com/members/';
}
if ($memberData['website_id'] == 468) {
$ph['website.url'] = 'http://members.powerovercravings.com/training/';
}
// welcome email subject
$subject = '[' . $website->get('title') . '] Login Details Email';
/*if (!empty($websiteOptions['welcome_email_subject'])) {
$subject = $this->parseUserChunk($websiteOptions['welcome_email_subject']);
}*/
// welcome email options
//$mailer = strtolower(str_replace(' ', '', $websiteOptions['support_name']));
//$mailer .= '@marketingtimesaver.com';
$options = array(
'account_id' => $memberData['account_id'],
'business_id' => $memberData['business_id'],
'website_id' => $memberData['website_id'],
'type' => 'login_details',
'mailer' => $account->get('mailer'),
'from' => $websiteOptions['support_name'],
'reply_to' => $websiteOptions['support_email'],
'recipients' => array(array(
'email' => $memberData['email'],
'name' => $memberData['first_name'] . ' ' . $memberData['last_name'],
'member_id' => $member->get('id')
)),
'email' => $memberData['email'],
'subject' => 'Your login details',
'ph' => $ph
);
// welcome email body
if (empty($websiteOptions['welcome_email_body'])) {
$options['template'] = 'x.email.member_welcome';
}
else {
$options['message'] = $this->parseUserChunk($websiteOptions['welcome_email_body'], true);
}
$x->account->folder = 'frequency9';
$this->log($x, 'debug', $options);
// send new member welcome email
$this->modx->runSnippet('x.ses', $options);
}
// update Infusionsoft
if (!empty($memberData['inf_contact_id']) && is_object($this->is)) {
$this->is->updateCon($memberData['inf_contact_id'], array('Password' => $password));
}
return $member->get('id');
}
/* public function to add a membership */
public function addMemberAccess($x, $memberId, $membershipId, $options = array()) {
$filter = array(
'website_id' => $x->website->id,
'member_id' => $memberId,
'membership_id' => $membershipId
);
if (!($memberAccess = $this->modx->getObject('XMemberAccess', $filter))) {
$member = $this->modx->getObject('XMember', $memberId);
if ($membership = $this->modx->getObject('XMembership', $membershipId)) {
$memberAccess = $this->modx->newObject('XMemberAccess');
$memberAccessData = array(
'account_id' => $x->account->id,
'business_id' => $x->business->id,
'website_id' => $x->website->id,
'member_id' => $memberId,
'membership_id' => $membershipId,
'name' => $membership->get('name')
);
if (!empty($options)) {
$memberAccessData = array_merge($memberAccessData, $options);
}
$memberAccessData = $this->createdTime($memberAccessData);
$memberAccess->fromArray($memberAccessData);
$memberAccess->save();
}
}
}
/* public function to generate a gravatar hash */
public function gravatarHash($email) {
$hash = md5(strtolower(trim($email)));
return $hash;
}
/* public function to get a gravatar image */
public function gravatar($email) {
$url = '//www.gravatar.com/avatar/' . $this->gravatarHash($email);
$image = '<img class="gravatar" src="' . $url . '.jpg" />';
return $image;
}
/* public function to load a website member */
public function loadMember(&$x) {
if (!empty($_COOKIE['member_id'])) {
$_SESSION['member_id'] = $_COOKIE['member_id'];
}
$member_id = $_SESSION['member_id'];
if ($member = $this->modx->getObject('XMember', array('id' => $member_id, 'website_id' => $x->website->id))) {
$x->member = $this->arrayToObject($member->toArray());
$x->member->name = $x->member->first_name . ' ' . $x->member->last_name;
$x->member->gravatar = $this->gravatarHash($x->member->email);
unset($x->member->password);
$x->website->profilenav = $this->modx->getChunk('website.profilenav');
/* load associated contact and company data */
$contact_id = $member->get('contact_id');
$inf_contact_id = $member->get('inf_contact_id');
if ($contact = $this->modx->getObject('XContact', $contact_id)) {
$x->contact = $this->arrayToObject($contact->toArray());
}
else if ($contact = $this->modx->getObject('XContact', array('inf_contact_id' => $inf_contact_id))) {
$x->contact = $this->arrayToObject($contact->toArray());
}
if (is_object($contact)) {
$company_id = $contact->get('company_id');
}
if (!empty($_SESSION['company_id'])) {
$company_id = $_SESSION['company_id'];
}
if ($company = $this->modx->getObject('XCompany', $company_id)) {
$x->company = $this->arrayToObject($company->toArray());
}
}
else {
$x->member->member_nav = 'hide';
}
}
########################################################################
######################### ENCODING.COM FUNCTIONS #######################
########################################################################
/* public function to process an encoding.com response */
public function encodingResponseOk($result) {
try {
$response = new SimpleXMLElement($result);
if (isset($response->errors[0]->error[0])) {
$error = $response->errors[0]->error[0] . '';
$this->modx->log(modX::LOG_LEVEL_ERROR,'[X::processEncodingResponse] ' . $e->getMessage());
return false;
}
}
catch (Exception $e) {
$this->modx->log(modX::LOG_LEVEL_ERROR,'[X::processEncodingResponse] ' . $e->getMessage());
return false;
}
return $response;
}
########################################################################
########################### CHARGIFY FUNCTIONS #########################
########################################################################
public function configChargify($x, $domain, $apiKey) {
$this->chargify = new chargify;
return $this->chargify->config($domain, $apiKey);
}
public function sendRequest($x, $uri, $data = '', $method = 'GET', $format = 'JSON') {
try {
$result = $this->chargify->sendRequest($uri, $data, $method, $format);
if ($result->code == 200 || $result->code == 201) {
return json_decode($result->response);
}
else {
$this->log($x, 'chargify', $result);
$response = $this->decode($result->response);
foreach ($response['errors'] as $error) {
$alerts[] = array('type' => 'error', 'message' => $error);
}
$_SESSION['alerts'] = $alerts;
return false;
}
}
catch (Exception $e) {
$this->log($x, 'chargify', $e->getMessage());
}
}
########################################################################
########################### LOADING FUNCTIONS #########################
########################################################################
/* public function to load x */
public function loadX(&$x) {
}
/* public function to load JSON into object */
public function loadJson($objectData, $json) {
$jsonData = $this->decode($json);
foreach ($jsonData as $jsonKey => $jsonValue) {
if (!empty($jsonValue) || $jsonValue === '0') {
$objectData->{$jsonKey} = $jsonValue;
}
}
return $objectData;
}
/* public function to load an account */
public function loadAccount(&$x) {
}
/* public function to load a business */
public function loadBusiness(&$x) {
}
/* public function to load a website */
public function loadWebsite(&$x, $cache = '') {
/* redirect uppercase urls to lowercase */
$request = $this->getRequest();
$querystring = $this->getQuerystring();
if (strlen(preg_replace('![^A-Z]+!', '', $request))) {
$redirect = strtolower($this->getBaseUrl() . $request) . $querystring;
header('Location: ' . $redirect, true, 301);
exit(0);
}
/* get domain */
$domain = $this->getDomain();
$x->root_domain = $this->getRootDomain();
$subdomain = $this->getSubdomain();
/* redirect to www */
if (empty($subdomain)) {
$domain = 'www.' . $domain;
$redirect = 'http://' . $domain . $_SERVER['REQUEST_URI'];
header('Location: ' . $redirect);
exit;
}
/* load from session - maybe load from cache instead? */
if (!empty($_SESSION['x.website']) && $cache != 'uncached') {
$x->website = $_SESSION['x.website'];
}
/* load from database */
else {
$c = $this->modx->newQuery('XWebsite');
if ($x->root_domain == 'marketingtimesaver' || $x->root_domain == 'websitepreviewer') {
$c->where(array('subdomain' => $subdomain));
}
else {
$c->where(array('domain' => $domain));
}
if (!($x->website = $this->loadObject('XWebsite', $c))) {
return '<h1>Domain ' . $domain . ' is not set up.</h1>';
exit(0);
}
/* set website url */
if (!empty($x->website->domain)) {
$x->website->url = 'http://' . $x->website->domain;
}
else {
$x->website->url = 'http://' . $x->website->subdomain . '.marketingtimesaver.com';
$x->website->domain = $x->website->subdomain . '.' . $x->root_domain . '.com';
}
$x->website->options = json_decode($x->website->options_json);
$_SESSION['x.website'] = $x->website;
}
/* website redirect */
if (!empty($x->website->redirect_url)) {
header('Location: ' . $x->website->redirect_url);
exit(0);
}
/* load the account */
if (empty($_SESSION['x.account'])) {
$x->account = $this->loadObject('XAccount', $x->website->account_id);
$_SESSION['x.account'] = $x->account;
}
else {
$x->account = $_SESSION['x.account'];
}
/* load the business */
if (empty($_SESSION['x.business'])) {
$x->business = $this->loadObject('XBusiness', $x->website->business_id);
$_SESSION['x.business'] = $x->business;
}
else {
$x->business = $_SESSION['x.business'];
}
/* preview mode */
if ($x->root_domain == 'websitepreviewer') {
$x->preview_notice = $modx->getChunk('x.layout.preview-notice');
}
else {
$x->preview_notice = '';
}
}
/* public function to load a page */
public function loadPage(&$x) {
$path = $this->splitPath();
/* init the page query */
$c = $this->modx->newQuery('XPage');
$filter = array('website_id' => $x->website->id);
/* get the prefix */
$prefix = $path[0];
/* get the alias */
if (!($page = $this->modx->getObject('XPage', array('website_id' => $x->website->id, 'alias' => 'members')))) {
$member_page = true;
$filter['type'] = 'members';
$x->alias = $this->getAlias($path, $prefix);
}
else {
$x->alias = $this->getAlias($path);
}
/* default alias */
if (empty($x->alias)) {
$x->alias = 'default';
}
/* set the page query filter */
$filter['alias'] = $x->alias;
$c->where($filter);
/* load page from database */
if ($x->page = $this->loadObject('XPage', $c, array('json_capture', 'json_value', 'json_options'))) {
header('HTTP/1.0 200 OK');
$x->page->link = $this->urlFromAlias($x->website->domain, $x->alias);
$x->page->url = $this->urlFromAlias($x->website->domain, $x->alias, 'full');
$x->page = $this->loadJson($x->page, $x->page->json_options);
if (empty($x->page->theme)) {
$x->page->theme = 'basic';
}
if (empty($x->page->template)) {
$x->page->template = $x->website->template;
}
if (empty($x->page->color)) {
$x->page->color = $x->website->color;
}
$x->page->{'active_nav_' . $x->page->alias} = 'active';
$x->page->{'show_nav_' . $x->page->alias} = 'show';
$x->nav->{'active_' . $x->page->alias} = 'active';
if ($x->page->show_banner != 0) {
$x->page->masthead = '<div id="masthead"><img src="' . $x->website->banner . '" /></div>';
}
if ($x->page->show_title != 0) {
$x->page->title_content = '<div class="headline"><h1>' . $x->page->title . '</h1></div>';
}
if ($x->page->layout) {
$x->page = $this->loadJson($x->page, $x->page->{'json_' . $x->page->type . 'layout'});
}
}
/* page not found */
else {
header('HTTP/1.0 404 Not Found');
$x->system_page = 'error';
$x->page->content = $this->modx->getChunk('x.website.error.404');
$x->page->type = 'error';
$x->page->template = 'modern';
$x->page->theme = 'basic';
$x->page->id = 0;
}
/* set page classes */
$pageBodyClasses = array('page', $x->system_page, $x->page->type, $x->page->template, $x->page->theme, $x->page->color);
if ($x->mobile) {
$pageBodyClasses[] = 'mobile';
}
$pageBodyClasses = array_filter($pageBodyClasses);
$x->page->body_classes = $this->implode($pageBodyClasses);
}
/* public function to load page assets */
public function loadAssets(&$x) {
$x->css_version = $this->getSetting('css_version');
$this->injectCsslinks($x, $x->website->css_links);
$this->injectCss($x, $x->website->css);
$this->injectJsHead($x, $x->website->javascript_head);
$this->injectJsLinks($x, $x->website->javascript_links);
$this->injectJs($x, $x->website->javascript);
if ($x->facebook) {
$this->injectCss($x, 'html { overflow: hidden; }');
$this->injectJsLinks($x, '//connect.facebook.net/en_US/all.js');
$this->injectJs($x, 'FB.init(); FB.Canvas.setAutoGrow();');
}
$this->injectJs($x, $this->modx->getChunk('facebook.connect.js'));
$this->injectCssLinks($x, $x->page->css_links);
$this->injectCss($x, $x->page->css);
$this->injectJsHead($x, $x->page->javascript_head);
$this->injectJsLinks($x, $x->page->javascript_links);
$this->injectJs($x, $x->page->javascript);
$this->injectAssets($x);
}
/* public function to load metadata */
public function loadMetadata(&$x) {
$x->website->meta_title = $x->website->title;
$metadata = $this->decode($x->website->meta_json);
if ($page_title = $x->page->title) {
$default_page = $x->page->default;
if (($x->page->type == 'members' || $x->page->type == 'page') && !$default_page) {
$x->website->meta_title .= ' | ' . $page_title;
}
else {
$x->website->meta_title = $page_title;
}
}
if ($x->page->meta_title) {
$x->website->meta_title = $x->page->meta_title;
}
if ($x->page->meta_description) {
$metadata['description'] = $x->page->meta_description;
}
$metadata['og:url'] = $x->page->url;
$metadata['og:type'] = 'website';
if ($x->page->og_title) {
$metadata['og:title'] = $x->page->og_title;
}
elseif ($x->page->meta_title) {
$metadata['og:title'] = $x->page->meta_title;
}
else {
$metadata['og:title'] = $x->website->meta_title;
}
if ($x->page->og_description) {
$metadata['og:description'] = $x->page->og_description;
}
elseif ($x->page->meta_description) {
$metadata['og:description'] = $x->page->meta_description;
}
$metadata['og:locale'] = 'en_us';
if ($x->page->og_image) {
$metadata['og:image'] = $x->page->og_image;
}
if ($x->page->fb_app_id) {
$metadata['fb:app_id'] = $x->page->fb_app_id;
}
if ($x->page->fb_admins) {
$metadata['fb:admins'] = $x->page->fb_admins;
}
foreach ($metadata as $name => $content) {
$x->page->meta .= "\n" . ' <meta name="' . $name . '" content="' . $content . '">';
}
}
/* private function to parse the page */
private function parseContent(&$x) {
$x->content = str_replace('&lt;', '<', $x->content);
$x->content = str_replace('&gt;', '>', $x->content);
$x->content = str_replace('[{', '[[', $x->content);
$x->content = str_replace('}]', ']]', $x->content);
$x->page->content = str_replace('[{', '[[', $x->page->content);
$x->page->content = str_replace('}]', ']]', $x->page->content);
}
/* public function to load page content */
public function loadContent(&$x) {
$x->content = $x->page->content;
if ($x->page->layout) {
$x->content = $this->runHook($x, 'layout.' . $x->page->type. $x->dev);
}
else {
$templateChunk = 'template.' . $x->page->type . '.' . $x->page->template;
if ($chunk = $this->modx->getObject('modChunk', array('name' => $templateChunk))) {
$x->content = $this->modx->parseChunk($templateChunk, $this->objectToPlaceholders($x), '[[+');
}
}
$this->parseContent($x);
}
/* public function to publish a website */
public function publishWebsite($websiteId) {
if ($website = $this->modx->getObject('XWebsite', $websiteId)) {
if ($account = $this->modx->getObject('XAccount', $website->get('account_id'))) {
$modUserId = $account->get('mod_user_id');
}
else {
$modUserId = 0;
}
$alias = str_replace('www.', '', $website->get('domain'));
if (empty($alias)) {
$alias = $website->get('subdomain') . '.marketingtimesaver.com';
}
if ($resource = $this->modx->getObject('modResource', $website->get('mod_resource_id'))) {
$resourceData = array(
'id' => $resource->get('id'),
'pagetitle' => $alias,
'longtitle' => $website->get('name'),
'alias' => $alias,
'menutitle' => $website->get('subdomain'),
'context_key' => 'published',
'tvs' => 1,
'tv53' => $modUserId,
'tv51' => $website->get('account_id'),
'tv52' => $website->get('business_id'),
'tv54' => $website->get('id')
);
$response = $this->modx->runProcessor('resource/update', $resourceData);
}
else {
$resourceData = array(
'type' => 'document',
'contentType' => 'text/html',
'pagetitle' => $alias,
'longtitle' => $website->get('name'),
'alias' => $alias,
'menutitle' => $website->get('subdomain'),
'context_key' => 'published',
'tvs' => 1,
'tv53' => $modUserId,
'tv51' => $website->get('account_id'),
'tv52' => $website->get('business_id'),
'tv54' => $website->get('id'),
'published' => 1,
'parent' => 0,
'isfolder' => 1,
'richtext' => 1,
'template' => 52,
'menuindex'=> 1,
'searchable' => 1,
'cacheable' => 1
);
$response = $this->modx->runProcessor('resource/create', $resourceData);
}
if ($response->isError()) {
return $response->getMessage();
}
else {
$resourceData = $response->getObject();
$this->modx->runProcessor('resource/publish', array('id' => $resourceData['id']));
$website->set('mod_resource_id', $resourceData['id']);
$website->save();
}
}
else {
return 'Invalid website';
}
return $resourceData['id'];
}
/* private function to prep css for publishing */
/* private function to prep page content for publishing */
private function prepareContent($content) {
$content = str_replace(' x-', ' mts-', $content);
$content = str_replace('"x-', '"mts-', $content);
$content = str_replace('&lt;', '<', $content);
$content = str_replace('&gt;', '>', $content);
return $content;
}
/* public function to publish a page */
public function publishPage($pageId) {
return;
if ($page = $this->modx->getObject('XPage', $pageId)) {
$type = $page->get('type');
if ($page->get('website_id') != 73) {
return;
}
if ($account = $this->modx->getObject('XAccount', $page->get('account_id'))) {
$modUserId = $account->get('mod_user_id');
}
else {
$modUserId = 0;
}
if ($website = $this->modx->getObject('XWebsite', $page->get('website_id'))) {
$parentId = $website->get('mod_resource_id');
}
else {
return 'Invalid website';
}
if (empty($parentId)) {
$parentId = $this->publishWebsite($website->get('id'));
}
$alias = str_replace('.', '/', $page->get('alias'));
$isFolder = 0;
$default = $page->get('default');
if ($default) {
$menuIndex = 0;
}
else {
$menuIndex = 1;
}
switch ($type) {
case 'members':
if ($alias == 'default') {
$alias = $website->get('membersite_prefix');
}
else {
$membersiteHomePage = $modx->getObject('XPage', array('website_id' => $website->get('id'), 'alias' => 'default'));
$parentId = $membersiteHomePage->get('mod_resource_id');
}
break;
}
$url = $this->websiteUrl($page->get('website_id'), $page->get('id'));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_USERAGENT, 'Marketing Timesaver Publisher');
$content = curl_exec($ch);
curl_close($ch);
if ($resource = $this->modx->getObject('modResource', $page->get('mod_resource_id'))) {
$resourceData = array(
'id' => $resource->get('id'),
'pagetitle' => $alias,
'longtitle' => $website->get('name'),
'alias' => $alias,
'menutitle' => $page->get('title'),
'context_key' => 'published',
'content' => $content,
'tvs' => 1,
'tv53' => $modUserId,
'tv51' => $page->get('account_id'),
'tv52' => $page->get('business_id'),
'tv17' => $page->get('id'),
'parent' => $parentId,
'menuindex'=> $menuIndex
);
$response = $this->modx->runProcessor('resource/update', $resourceData);
}
else {
$resourceData = array(
'type' => 'document',
'contentType' => 'text/html',
'pagetitle' => $alias,
'longtitle' => $page->get('name'),
'alias' => $alias,
'menutitle' => $page->get('title'),
'context_key' => 'published',
'content' => $content,
'tvs' => 1,
'tv18' => $page->get('hash'),
'tv53' => $modUserId,
'tv51' => $page->get('account_id'),
'tv52' => $page->get('business_id'),
'tv17' => $page->get('id'),
'published' => 1,
'parent' => $parentId,
'isfolder' => $isFolder,
'richtext' => 1,
'template' => 58,
'menuindex'=> $menuIndex,
'searchable' => 1,
'cacheable' => 1
);
$response = $this->modx->runProcessor('resource/create', $resourceData);
}
if ($response->isError()) {
return $response->getMessage();
}
else {
$resourceData = $response->getObject();
$this->modx->runProcessor('resource/publish', array('id' => $resourceData['id']));
$page->set('mod_resource_id', $resourceData['id']);
$page->save();
if ($menuIndex == 0) {
$resources = $this->modx->getIterator('modResource', array('id:!=' => $resourceData['id'], 'parent' => $parentId, 'menuindex' => 0));
foreach ($resources as $resource) {
$resourceData = array('id' => $resource->get('id'), 'menuindex' => 1);
$response = $this->modx->runProcessor('resource/update', $resourceData);
$response = $this->modx->runProcessor('resource/publish', array('id' => $resourceData['id']));
}
}
}
}
else {
return 'Invalid page';
}
return $resourceData['id'];
}
/* website debugging */
public function debugWebsite(&$x) {
if ($_GET['debug'] == 'on') {
$_SESSION['debug'] = 'on';
}
else if ($_GET['debug'] == 'off') {
$_SESSION['debug'] = '';
}
if ($_GET['debug'] == 'on' || ($_SESSION['debug'] == 'on' && $_GET['debug'] != 'off')) {
$page_data = $x;
unset($page_data->page->meta);
unset($page_data->content);
$debugging_data = '<pre>Request ' . print_r($_REQUEST, true) . "\nPage " . print_r($page_data, true) . "\nSession" . print_r($_SESSION, true) . "\n</pre>";
$x->content = $debugging_data . $x->content;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment