/** * Determine if the project has been extended and set result in config * * @return $this */ private function _setProjectExtendedConfig() { $config = Container::config()->get('project'); $config->extended = !($this->getProjectPath() == __DIR__); if ($config->extended) { $config->extended_path = __DIR__; $config->extended_namespace = __NAMESPACE__; } return $this; }
public static function getAvailableLanguages() { $availableLanguages = []; $config = Container::config()->get("i18n"); if ($config != null) { $languages = $config->getArr('languages', []); foreach ($languages as $lang) { $availableLanguages[$lang] = $lang; } } return $availableLanguages; }
public static function getService($name = 'storage') { $sm = Container::get(Container::SERVICE_MANAGER); if ($sm instanceof ServiceManager) { $service = $sm->get($name); if ($service instanceof StorageService) { return $service; } else { throw new \Exception('Service not an instance of StorageService'); } } else { throw new \Exception('Error getting service manager'); } }
/** * Override this Views's Template directory * * @param $directory * * @return $this */ public function setTemplateDirectory($directory) { $config = Container::config()->get('project'); if ($config->extended) { $fullClassName = get_called_class(); $classNameSplit = explode("\\", $fullClassName); $className = end($classNameSplit); $templatePath = str_replace(array("Qubes\\Support", "\\Views\\", $className), array($config->path, "\\Templates", ""), $fullClassName); if (file_exists(sprintf('%s/%s.phtml', $templatePath, $className))) { $directory = $templatePath; } } $this->_baseDirectory = $directory; return $this; }
public function init($initialiser = null) { $config = Container::config()->get("rollbar", new Config()); $token = $config->getStr("post_server_item", null); $this->_logLevel = $config->getStr("log_level", LogLevel::WARNING); $config = ['access_token' => $token, 'environment' => CUBEX_ENV, 'root' => CUBEX_PROJECT_ROOT]; if (class_exists('\\Bundl\\Sidekix\\SidekixBundl')) { $info = SidekixBundl::getDiffuseVersionInfo(); if ($info && isset($info['version'])) { $config['code_version'] = $info['version']; } } // installs global error and exception handlers \Rollbar::init($config); EventManager::listen(EventManager::CUBEX_LOG, [$this, "log"]); }
public function projectPrepare() { $config = Container::config()->get("sidekix", new Config()); $security = $config->getStr("security_key", null); $request = Container::request(); if ($request === null) { return; } $version = $request->getVariables("DIFFUSE_VERSION", null); $secKey = $request->getVariables("SEC", null); if ($version !== null && $secKey === $security) { $cookie = new StandardCookie($config->getStr("diffuse_cookie", "CUBEX_VERSION"), $version); Cookies::set($cookie); $redirect = $config->getStr("diffuse_cookie_redirect", null); if ($redirect) { Redirect::to($redirect)->now(); } } }
protected static function _buildMultiInstanceSSHCommand($hostname, $instances) { $className = $_REQUEST['__path__']; $prjConf = Container::config()->get('project')->getData(); $namespace = $prjConf['namespace']; $scriptDir = CUBEX_PROJECT_ROOT; $commands = array(); foreach ($instances as $instance) { $reportFile = $scriptDir . '/logs/' . $className; if ($instance != "") { $reportFile .= '-' . $instance; } $reportFile .= '/stats.txt'; $pidFile = '/var/run/cubex/' . $namespace . '/' . $className; if ($instance != "") { $pidFile .= '.' . $instance; } $pidFile .= '.pid'; $commands[] = "echo; echo -n '" . $instance . "=|=' ;" . "ps ax | grep -v grep | " . "grep -e 'cubex \\(--cubex-env=production \\)\\?" . $className . "' | " . 'grep \\`cat "' . $pidFile . '"\\` >/dev/null && ' . "cat '" . $reportFile . "'"; } $command = 'ssh -oConnectTimeout=1 ' . $hostname . ' "' . implode(";", $commands) . '" 2>/dev/null'; return $command; }
public function getViewOptions() { if ($this instanceof RecordMapper) { $viewOptions = []; $project = Container::config()->get('project'); $mapperName = class_shortname($this); $viewPath = "/Applications/Front/" . $mapperName . "/Views/"; $viewDirs = []; $extended = []; $viewDirs[$project->namespace] = $project->path . $viewPath; $extended[$project->namespace] = false; if ($project->extended) { $viewDirs[$project->extended_namespace] = $project->extended_path . $viewPath; $extended[$project->extended_namespace] = true; } foreach ($viewDirs as $namespace => $viewDir) { if (file_exists($viewDir)) { $files = glob($viewDir . '*.php'); foreach ($files as $file) { $pathInfo = pathinfo($file); $className = basename($pathInfo['filename']); $fullClassName = $namespace . '\\Applications\\Front\\' . $mapperName . '\\Views\\' . $className; if (isset($extended[$namespace]) && $extended[$namespace]) { $className = $className . ' [Default]'; } $viewOptions[$fullClassName] = $className; } } } if (empty($viewOptions)) { throw new \Exception('No Views found'); } return $viewOptions; } else { throw new \Exception('ViewOptionTrait can only be used by a RecordMapper'); } }
/** * Helper method to handle create and update of campaigns. Will redirect to * the specific campaign on success with a message. If there are any * validation or CSRF errors we render the form again with information. * * @param null|int $id * * @return CampaignFormView */ private function _updateCampaign($id = null) { $form = $this->_buildCampaignForm($id); $form->hydrate($this->request()->postVariables()); if ($id == null) { $config = Container::config()->get("default_processors"); $processors = []; if ($config != null) { $processorKeys = $config->availableKeys(); foreach ($processorKeys as $key) { $processors[]['processorType'] = $key; } } $form->processors = $processors; } if ($form->isValid() && $form->csrfCheck(true)) { $form->saveChanges(); if ($form->sendAt == "X * * * *") { $campaign = new Campaign($id); if ($campaign->exists()) { $cronMinute = $id % 60; $campaign->sendAt = "{$cronMinute} * * * *"; $campaign->saveChanges(); } } $msg = "Campaign '{$form->name}'"; $msg .= $id ? " Updated" : " Created"; return Redirect::to("/campaigns/{$form->getMapper()->id()}")->with("msg", new TransportMessage("info", $msg)); } return $this->renderEdit($id, $form); }
/** * Set the default project theme * * @return \Cubex\Theme\ApplicationTheme|SidekickTheme */ public function getTheme() { if (Container::config()->get('project')->extended) { return $this->getProject()->getTheme($this); } return new SidekickTheme(); }
public function __construct() { $config = Container::config()->get("sidekix", new Config()); $this->_api = $config->getStr("translate_endpoint", null); $this->_projectId = $config->getStr("project_id", 0); }
public function translateString($string) { if (!empty($string)) { $this->prepTextForTranslate($string); // translate $config = Container::config()->get("i18n", new Config()); $translateClass = $config->getStr("translator", null); if (!$translateClass) { throw new \Exception('Missing \'translator\' in i18n section of the config'); } $translator = new $translateClass(); $translatedText = $translator->translate($string, 'en', $this->getStr('hl')); $string = $this->reversePlaceHolders($translatedText); } return $string; }
/** * @param string $serviceName * * @return IDatabaseService */ public function getConnection($serviceName) { if (!isset($this->_connections[$serviceName])) { $this->_connections[$serviceName] = Container::servicemanager()->getWithType($serviceName, '\\Cubex\\Database\\IDatabaseService'); $this->_connections[$serviceName]->query("SET NAMES 'utf8'"); } return $this->_connections[$serviceName]; }
/** * Add base project resources, JD, CSS etc * * @return $this */ private function _addProjectResources() { $config = Container::config()->get('project'); foreach ($config->css as $file) { $this->requireCss($file); } foreach ($config->js as $file) { $this->requireJs($file); } return $this; }
/** * @param int $campaignId * @param array[] $batch * * @return bool * @throws \Exception */ public static function pushMessageBatch($campaignId, array $batch) { if (!$batch) { return false; } $cacheId = 'DeferoQueueCampaign' . $campaignId; /** * @var Campaign $campaign * @var Contact $contact */ $campaign = ExpiringEphemeralCache::getCache($cacheId, __CLASS__); if ($campaign === null) { $campaign = new Campaign($campaignId); $campaign->reload(); ExpiringEphemeralCache::storeCache($cacheId, $campaign, __CLASS__, 60); } if (!$campaign || !$campaign->exists()) { throw new \Exception('Campaign does not exist'); } $campaignId = $campaign->id(); $processorsCacheId = $cacheId . ':processors'; $processors = ExpiringEphemeralCache::getCache($processorsCacheId, __CLASS__); if ($processors === null) { $processors = []; $processorsConfig = Container::get(Container::CONFIG)->get('processors'); if ($campaign->processors) { foreach ($campaign->processors as $processorData) { $config = new Config(); $config->hydrate($processorData); $configGroup = new ConfigGroup(); $configGroup->addConfig("process", $config); $process = new ProcessDefinition(); $process->setProcessClass($processorsConfig->getStr($processorData->processorType)); $process->setQueueName("defero"); $process->setQueueService("queue"); $process->configure($configGroup); $processors[] = $process; } } else { throw new \Exception("Cannot queue campaign No default processors found."); } ExpiringEphemeralCache::storeCache($processorsCacheId, $processors, __CLASS__, 60); } $blacklistDomains = []; foreach (Container::config()->get('blacklist')->getArr('domains', []) as $d) { $blacklistDomains[] = preg_quote($d, '/'); } $blacklistRegex = '/(' . implode('|', $blacklistDomains) . ')$/i'; //grab all user_ids from $batch, check SentEmailLog $logKeys = []; $keyedBatch = []; //use this to recover $batch $dedupe = true; foreach ($batch as $data) { if (isset($data['user_id'])) { $logKeys[] = $data['user_id'] . '-' . $campaignId; $keyedBatch[$data['user_id']] = $data; } if (isset($data['dedupe'])) { $dedupe = false; } } if ($logKeys && $dedupe) { try { //check if we sent this campaign to users today or the previous day $yesterday = date('Y-m-d', strtotime('-1 day')); $today = date('Y-m-d'); $result = SentEmailLog::cf()->multiGet($logKeys, [$yesterday, $today]); foreach ($result as $key => $column) { if (is_array($column) && (isset($column[$yesterday]) || isset($column[$today]))) { list($userId, $cId) = explode('-', $key); //remove user from keyedBatch because they have already // received this campaign unset($keyedBatch[$userId]); \Log::info("Skipping user because they already got this campaign: [user_id:" . $data['user_id'] . ', campaign_id: ' . $campaignId . "]"); } } $batch = array_values($keyedBatch); } catch (\Exception $e) { \Log::error("Email Deduping Failed: " . $e->getMessage()); } } $messages = []; foreach ($batch as $data) { $data = array_change_key_case($data); // check blacklist if ($blacklistDomains && preg_match($blacklistRegex, $data['email'])) { continue; } // move language here. $userLanguage = $data['language'] = !empty($data['language']) ? $data['language'] : 'en'; $active = isset($data['campaignactive']) ? $data['campaignactive'] : $campaign->active; $message = new ProcessMessage(); $message->setData('campaignId', $campaignId); $message->setData('campaignActive', $active); if (!$active) { $message->setData('emailService', 'email_test'); } elseif ($campaign->emailService) { $message->setData('emailService', $campaign->emailService); } else { $message->setData('emailService', 'email'); } if ($campaign->replyTo) { $message->setData('replyTo', $campaign->replyTo); } $message->setData('mailerTracking', $campaign->trackingType); $message->setData('data', $data); $languageCacheId = $cacheId . ':language:' . $userLanguage; $msg = ExpiringEphemeralCache::getCache($languageCacheId, __CLASS__); if ($msg === null) { $msg = $campaign->message(); $msg->setLanguage($userLanguage); $msg->reload(); if ($userLanguage !== 'en' && (!$msg->active || !$msg->subject || $campaign->sendType != SendType::PLAIN_TEXT && !$msg->htmlContent || $campaign->sendType != SendType::HTML_ONLY && !$msg->plainText)) { //for non eng if html and plain but no html we shouldn't default to english if ($campaign->sendType == SendType::HTML_AND_PLAIN && !$msg->htmlContent && $msg->plainText) { } else { $msg->setLanguage('en'); $msg->reload(); } } ExpiringEphemeralCache::storeCache($languageCacheId, $msg, __CLASS__, 60); } $contactId = $msg->contactId ?: $campaign->contactId; $contactCacheId = $cacheId . ':contact:' . $contactId; $contact = ExpiringEphemeralCache::getCache($contactCacheId, __CLASS__); if ($contact === null) { $contact = new Contact($contactId); ExpiringEphemeralCache::storeCache($contactCacheId, $contact, __CLASS__, 60); } $data['signature'] = $contact->signature; $message->setData('senderName', self::replaceData($contact->name, $data)); $message->setData('senderEmail', self::replaceData($contact->email, $data)); $message->setData('returnPath', self::replaceData($contact->returnPath, $data)); $message->setData('sendType', self::replaceData($campaign->sendType, $data)); $message->setData('subject', self::replaceData($msg->subject, $data)); $message->setData('plainText', self::replaceData($msg->plainText, $data)); $message->setData('htmlContent', self::replaceData($msg->htmlContent, $data, true)); foreach ($processors as $process) { $message->addProcess($process); } $messages[] = serialize($message); } // queue \Queue::setDefaultQueueProvider("messagequeue"); // prioritize if ($campaign->active) { $priority = (int) $campaign->priority; $priority = $priority < 0 ? 1 : $priority; } else { $priority = 99; } $queueName = 'mailer.defero_messages_priority_' . $priority; \Queue::pushBatch(new StdQueue($queueName), $messages); // stats try { $hour = time(); $hour -= $hour % 3600; $statsCf = MailStatistic::cf(); $statsCf->increment($campaignId, $hour . '|queued', count($messages)); } catch (\Exception $e) { \Log::error('Error writing stats for campaign ' . $campaignId . ' : ' . $e->getMessage()); } \Log::info('Queued ' . count($messages) . ' messages for Campaign ' . $campaignId); return true; }
public function emailServices() { $services = Container::servicemanager()->getAllWithType('\\Cubex\\Email\\IEmailService'); return array_combine($services, $services); }