/** * Run right at the end of the form processing * form needs to be set to record in database for this to hook to be called * * @param object $params plugin params * @param object &$formModel form model * * @return bool */ public function onAfterProcess($params, &$formModel) { $w = new FabrikWorker(); $config_userpass = $params->get('username') . ':' . $params->get('password'); $endpoint = $params->get('endpoint'); $headers = array('Content-Type: application/xml', 'Accept: application/xml'); // Set where we should post the REST request to $endpoint = $w->parseMessageForPlaceholder($endpoint); $endpoint = $w->parseMessageForPlaceholder($endpoint); // What is the root node for the xml data we are sending $xmlParent = $params->get('xml_parent', 'ticket'); $xmlParent = $w->parseMessageForPlaceholder($xmlParent); $xml = new SimpleXMLElement('<' . $xmlParent . '></' . $xmlParent . '>'); // Set up CURL object $chandle = curl_init(); // Set which fields should be included in the XML data. $include = $w->parseMessageForPlaceholder($params->get('include_list', 'milestone-id, status, summary')); $include = explode(',', $include); foreach ($include as $i) { if (array_key_exists($i, $formModel->_formData)) { $xml->addChild($i, $formModel->_formData[$i]); } elseif (array_key_exists($i, $formModel->_fullFormData, $i)) { $xml->addChild($i, $formModel->_fullFormData[$i]); } } $output = $xml->asXML(); $curl_options = array(CURLOPT_URL => $endpoint, CURLOPT_RETURNTRANSFER => 1, CURLOPT_HTTPHEADER => $headers, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $output, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_USERPWD => $config_userpass, CURLOPT_CUSTOMREQUEST => 'POST'); foreach ($curl_options as $key => $value) { curl_setopt($chandle, $key, $value); } $output = curl_exec($chandle); $httpCode = curl_getinfo($chandle, CURLINFO_HTTP_CODE); switch ($httpCode) { case '400': echo "Bad Request"; break; case '401': echo "Unauthorized"; break; case '404': echo "Not found"; break; case '405': echo "Method Not Allowed"; break; case '406': echo "Not Acceptable"; break; case '415': echo "Unsupported Media Type"; break; case '500': echo "Internal Server Error"; break; } if (curl_errno($chandle)) { die("ERROR: " . curl_error($chandle)); } curl_close($chandle); }
/** * Run right at the end of the form processing * form needs to be set to record in database for this to hook to be called * * @throws Exception * * @return bool */ public function onAfterProcess() { $params = $this->getParams(); $api_AUP = JPATH_SITE . '/components/com_alphauserpoints/helper.php'; if (JFile::exists($api_AUP)) { $w = new FabrikWorker(); $this->data = $this->getProcessData(); require_once $api_AUP; $aup = new AlphaUserPointsHelper(); // Define which user will receive the points. $userId = $params->get('user_id', ''); $userId = (int) $w->parseMessageForPlaceholder($userId, $this->data, false); $aupId = $aup->getAnyUserReferreID($userId); // Replace these if you want to show a specific reference for the attributed points - doesn't seem to effect anything $keyReference = ''; // Shown in the user details page - description of what the point is for $dataReference = $params->get('data_reference', ''); $dataReference = $w->parseMessageForPlaceholder($dataReference, $this->data, false); // Override the plugin default points $randomPoints = $params->get('random_points', 0); if ($params->get('random_points_eval', '0') == '1') { if (!empty($randomPoints)) { $randomPoints = $w->parseMessageForPlaceholder($randomPoints, $this->data, false); $randomPoints = @eval($randomPoints); FabrikWorker::logEval($randomPoints, 'Caught exception on eval in aup plugin : %s'); } $randomPoints = (double) $randomPoints; } else { $randomPoints = (double) $w->parseMessageForPlaceholder($randomPoints, $this->data, false); } // If set to be greater than $randompoints then this is the # of points assigned (not sure when this would be used - commenting out for now) $referralUserPoints = 0; $aupPlugin = $params->get('aup_plugin', 'plgaup_fabrik'); $aupPlugin = $w->parseMessageForPlaceholder($aupPlugin, $this->data, false); if (!$aup->checkRuleEnabled($aupPlugin, 0, $aupId)) { throw new Exception('Alpha User Points plugin not published'); } $aup->userpoints($aupPlugin, $aupId, $referralUserPoints, $keyReference, $dataReference, $randomPoints); } }
/** * Set the axis label * * @return void */ protected function setAxisLabels() { $worker = new FabrikWorker(); $params = $this->getParams(); $this->axisLabels = (array) $params->get('fusionchart_axis_labels'); foreach ($this->axisLabels as $axis_key => $axis_val) { $this->axisLabels[$axis_key] = $worker->parseMessageForPlaceholder($axis_val, null, false); } }
/** * Get the email to name and email address * * @param array $data Placeholder replacement data * * @since 3.3.2 * * @return array ($emailFrom, $fromName) */ private function _fromEmailName($data = array()) { $w = new FabrikWorker(); $params = $this->getParams(); $fromUser = $params->get('emailtable_from_user'); if ($fromUser) { $emailFrom = $this->user->get('email'); $fromName = $this->user->get('name'); } else { $emailFrom = $params->get('email_from', $this->config->get('mailfrom')); @(list($emailFrom, $fromName) = explode(':', $w->parseMessageForPlaceholder($emailFrom, $data, false), 2)); } return array($emailFrom, $fromName); }
/** * perform log * * @param object $params * @param object form model * @param string message type * @returns bool */ protected function log($params, $formModel, $messageType) { $this->formModel = $formModel; $app = JFactory::getApplication(); $db = FabrikWorker::getDBO(); $query = $db->getQuery(true); $rowid = JRequest::getVar('rowid', ''); $loading = strstr($messageType, 'form.load'); $http_referrer = JRequest::getVar('HTTP_REFERER', 'no HTTP_REFERER', 'SERVER'); $user = JFactory::getUser(); $userid = $user->get('id'); $username = $user->get('username'); // Generate random filename if ($params->get('logs_random_filename') == 1) { function generate_filename($length) { $key = ""; $possible = "0123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRTVWXYZ"; $i = 0; while ($i < $length) { $char = substr($possible, mt_rand(0, strlen($possible) - 1), 1); $key .= $char; $i++; } return $key; } $random_filename = '_' . generate_filename($params->get('logs_random_filename_length')); } else { $random_filename = ''; } $w = new FabrikWorker(); $logs_path = $w->parseMessageForPlaceHolder($params->get('logs_path')); if (strpos($logs_path, DS) !== 0) { $logs_path = JPATH_ROOT . DS . $logs_path; } $logs_path = rtrim($logs_path, DS); if (!JFolder::exists($logs_path)) { if (!JFolder::create($logs_path)) { return; } } $ext = $params->get('logs_file_format'); $sep = $params->get('logs_separator'); // Making complete path + filename + extension $w = new FabrikWorker(); $logs_file = $logs_path . DS . $w->parseMessageForPlaceHolder($params->get('logs_file')) . $random_filename . '.' . $ext; $logs_mode = $params->get('logs_append_or_overwrite'); $date_element = $params->get('logs_date_field'); $date_now = $params->get('logs_date_now'); // COMPARE DATA $result_compare = ''; if ($params->get('compare_data')) { if ($ext == 'csv') { $sep_compare = ''; $sep_2compare = '/ '; } else { if ($ext == 'txt') { $sep_compare = "\n"; $sep_2compare = "\n"; } else { if ($ext == 'htm') { $sep_compare = '<br/>'; $sep_2compare = '<br/>'; } } } if ($loading) { $result_compare = JText::_('COMPARE_DATA_LOADING') . $sep_2compare; } else { $data = $this->getEmailData(); $newData = $this->getNewData($formModel); if (!empty($data)) { $post = JRequest::get('post'); $elementModel = JModel::getInstance('element', 'FabrikModel'); $element = $elementModel->getElement(true); $tableModel = $formModel->getTable(); $origDataCount = count(array_keys(JArrayHelper::fromObject($formModel->_origData[0]))); if ($origDataCount > 0) { $c = 0; $origData = $formModel->_origData; $log_elements = explode(',', str_replace(' ', '', $params->get('logs_element_list', ''))); $groups = $formModel->getGroupsHiarachy(); foreach ($groups as $groupModel) { $group = $groupModel->getGroup(); $elementModels = $groupModel->getPublishedElements(); foreach ($elementModels as $elementModel) { $element = $elementModel->getElement(); $fullName = $elementModel->getFullName(false, true, false); if (empty($log_elements) || in_array($fullName, $log_elements)) { if ($newData[$c]->{$fullName} != $origData[$c]->{$fullName}) { $result_compare .= JText::_('COMPARE_DATA_CHANGE_ON') . ' ' . $element->label . ' ' . $sep_compare . JText::_('COMPARE_DATA_FROM') . ' ' . $origData[0]->{$fullName} . ' ' . $sep_compare . JText::_('COMPARE_DATA_TO') . ' ' . $newData[$c]->{$fullName} . ' ' . $sep_2compare; } } } } if (empty($result_compare)) { $result_compare = JText::_('COMPARE_DATA_NO_DIFFERENCES'); } } else { $result_compare .= "New record:" . $sep_2compare; foreach ($data as $key => $val) { if (isset($val) && substr($key, -4, 4) != '_raw') { $result_compare .= "{$key} : {$val}" . $sep_2compare; } } } } else { $result_compare = "No data to compare!"; } } } // Defining the date to use - Not used anymore as logs should really only record the current time_date if ($date_now != '') { $date = date("{$date_now}"); } else { $date = date("Y-m-d H:i:s"); } // Custom Message if ($params->get('custom_msg') != '') { $rep_add_edit = $messageType == 'form.add' ? JText::_('REP_ADD') : ($messageType == 'form.edit' ? JText::_('REP_EDIT') : JText::_('DETAILS')); $custom_msg = $params->get('custom_msg'); $custom_msg = preg_replace('/{Add\\/Edit}/', $rep_add_edit, $custom_msg); $custom_msg = preg_replace('/{DATE}/', $date, $custom_msg); $excl_clabels = preg_replace('/([-{2}| |"][0-9a-zA-Z.:$_>]*)/', '', $custom_msg); $split_clabels = preg_split('/[+]{1,}/', $excl_clabels); $clabels = preg_replace('/[={2}]+[a-zA-Z0-9_-]*/', '', $split_clabels); $ctypes = preg_replace('/[a-zA-Z0-9_-]*[={2}]/', '', $split_clabels); $labtyp = array_combine($clabels, $ctypes); $w = new FabrikWorker(); $custom_msg = $w->parseMessageForPlaceHolder($custom_msg); $excl_cdata = preg_replace('/((?!("[^"]*))([ |\\w|+|.])+(?=[^"]*"\\b)|(?!\\b"[^"]*)( +)+(?=([^"]*)$)|(?=\\b"[^"]*)( +)+(?=[^"]*"\\b))/', '', $custom_msg); $cdata = preg_split('/["]{1,}/', $excl_cdata); // Labels for CSV & for DB $clabels_csv_imp = implode("\",\"", $clabels); $clabels_csv_p1 = preg_replace('/^(",)/', '', $clabels_csv_imp); $clabels_csv = ''; $clabels_csv .= preg_replace('/(,")$/', '', $clabels_csv_p1); if ($params->get('compare_data') == 1) { $clabels_csv .= ', "' . JText::_('PLG_FORM_LOG_COMPARE_DATA_LABEL_CSV') . '"'; } $clabels_createdb_imp = ''; foreach ($labtyp as $klb => $vlb) { $klb = $db->quoteName($klb); if ($vlb == 'varchar') { $clabels_createdb_imp .= $klb . ' ' . $vlb . '(255) NOT NULL, '; } else { if ($vlb == 'int') { $clabels_createdb_imp .= $klb . ' ' . $vlb . '(11) NOT NULL, '; } else { if ($vlb == 'datetime') { $clabels_createdb_imp .= $klb . ' ' . $vlb . ' NOT NULL, '; } } } } $clabels_createdb = substr_replace($clabels_createdb_imp, '', -2); if ($params->get('compare_data') == 1) { $clabels_createdb .= ', ' . $db->quoteName(JText::_('COMPARE_DATA_LABEL_DB')) . ' text NOT NULL'; } // @todo - what if we use differnt db driver which doesnt name quote with `?? $clabels_db_imp = implode("`,`", $clabels); $clabels_db_p1 = preg_replace('/^(`,)/', '', $clabels_db_imp); $clabels_db = preg_replace('/(,`)$/', '', $clabels_db_p1); if ($params->get('compare_data') == 1) { $clabels_db .= ', ' . $db->quoteName(JText::_('PLG_FORM_LOG_COMPARE_DATA_LABEL_DB')); } // data for CSV & for DB $cdata_csv_imp = implode("\",\"", $cdata); $cdata_csv_p1 = preg_replace('/^(",)/', '', $cdata_csv_imp); $cdata_csv = preg_replace('/(,")$/', '', $cdata_csv_p1); $cdata_csv = preg_replace('/={1,}",/', '', $cdata_csv); $cdata_csv = preg_replace('/""/', '"', $cdata_csv); if ($params->get('compare_data') == 1) { $cdata_csv .= ', "' . $result_compare . '"'; } $cdata_db_imp = implode("','", $cdata); $cdata_db_p1 = preg_replace("/^(',)/", '', $cdata_db_imp); $cdata_db = preg_replace("/(,')\$/", '', $cdata_db_p1); $cdata_db = preg_replace("/={1,}',/", '', $cdata_db); $cdata_db = preg_replace("/''/", "'", $cdata_db); if ($params->get('compare_data') == 1 && !$loading) { $result_compare = preg_replace('/<br\\/>/', '- ', $result_compare); $result_compare = preg_replace('/\\n/', '- ', $result_compare); $cdata_db .= ", '" . $result_compare . "'"; } $custom_msg = preg_replace('/([++][0-9a-zA-Z.:_]*)/', '', $custom_msg); $custom_msg = preg_replace('/^[ ]/', '', $custom_msg); $custom_msg = preg_replace('/ /', ' ', $custom_msg); $custom_msg = preg_replace('/"/', '', $custom_msg); if ($params->get('compare_data') == 1 && !$loading) { $custom_msg .= '<br />' . $result_compare; } } else { $clabelsCreateDb = array(); $clabelsDb = array(); $cdataDb = array(); $clabelsCreateDb[] = $db->quoteName('date') . " datetime NOT NULL"; $clabelsDb[] = $db->quoteName('date'); $cdataDb[] = "NOW()"; $clabelsCreateDb[] = $db->quoteName('ip') . " varchar(32) NOT NULL"; $clabelsDb[] = $db->quoteName('ip'); $cdataDb[] = $params->get('logs_record_ip') == '1' ? $db->Quote($_SERVER['REMOTE_ADDR']) : $db->Quote(''); $clabelsCreateDb[] = $db->quoteName('referer') . " varchar(255) NOT NULL"; $clabelsDb[] = $db->quoteName('referer'); $cdataDb[] = $params->get('logs_record_referer') == '1' ? $db->Quote($http_referrer) : $db->Quote(''); $clabelsCreateDb[] = $db->quoteName('user_agent') . " varchar(255) NOT NULL"; $clabelsDb[] = $db->quoteName('user_agent'); $cdataDb[] = $params->get('logs_record_useragent') == '1' ? $db->Quote($_SERVER['HTTP_USER_AGENT']) : $db->Quote(''); $clabelsCreateDb[] = $db->quoteName('data_comparison') . " TEXT NOT NULL"; $clabelsDb[] = $db->quoteName('data_comparison'); $cdataDb[] = $params->get('compare_data') == '1' ? $db->Quote($result_compare) : $db->Quote(''); $clabelsCreateDb[] = $db->quoteName('rowid') . " INT(11) NOT NULL"; $clabelsDb[] = $db->quoteName('rowid'); $cdataDb[] = $db->Quote((int) $rowid); $clabelsCreateDb[] = $db->quoteName('userid') . " INT(11) NOT NULL"; $clabelsDb[] = $db->quoteName('userid'); $cdataDb[] = $db->Quote((int) $userid); $clabelsCreateDb[] = $db->quoteName('tableid') . " INT(11) NOT NULL"; $clabelsDb[] = $db->quoteName('tableid'); $cdataDb[] = $db->Quote($formModel->getTableModel()->getId()); $clabelsCreateDb[] = $db->quoteName('formid') . " INT(11) NOT NULL"; $clabelsDb[] = $db->quoteName('formid'); $cdataDb[] = $db->Quote($formModel->getId()); $clabels_createdb = implode(", ", $clabelsCreateDb); $clabels_db = implode(", ", $clabelsDb); $cdata_db = implode(", ", $cdataDb); } /* For CSV files * If 'Append' method is used, you don't want to repeat the labels (Date, IP, ...) * each time you add a line in the file */ $labels = !JFile::exists($logs_file) || $logs_mode == 'w' ? 1 : 0; $buffer = $logs_mode == 'a' && JFile::exists($logs_file) ? JFile::read($logs_file) : ''; $send_email = $params->get('log_send_email') == '1'; $make_file = $params->get('make_file') == '1'; if ($send_email && !$make_file) { $ext = 'txt'; } $email_msg = ''; //@TODO redo all this with JFile API and only writing a string once - needless overhead doing fwrite all the time if ($make_file || $send_email) { // Opening or creating the file if ($params->get('custom_msg') != '') { if ($send_email) { $email_msg = $custom_msg; } if ($make_file) { $custMsg = $buffer; if ($ext != 'csv') { JFile::write($logs_file, $buffer . $custom_msg . "\n" . $sep . "\n"); } else { // Making the CSV file // If the file already exists, do not add the 'label line' if ($labels == 1) { $custMsg .= $clabels_csv; } // Inserting data in CSV with actual line break as row separator $custMsg .= "\n" . $cdata_csv; JFile::write($logs_file, $custMsg); } } } else { // Making HTM File if ($ext == 'htm') { $htmlMsg = "<b>Date:</b> " . $date . "<br/>"; if ($params->get('logs_record_ip') == 1) { $htmlMsg .= "<b>IP Address:</b> " . $_SERVER['REMOTE_ADDR'] . "<br/>"; } if ($params->get('logs_record_referer') == 1) { $htmlMsg .= "<b>Referer:</b> " . $http_referrer . "<br/>"; } if ($params->get('logs_record_useragent') == 1) { $htmlMsg .= "<b>UserAgent: </b>" . $_SERVER['HTTP_USER_AGENT'] . "<br/>"; } $htmlMsg .= $result_compare . $sep . "<br/>"; if ($send_email) { $email_msg = $htmlMsg; } if ($make_file) { $htmlMsg = $buffer . $htmlMsg; $res = JFile::write($logs_file, $htmlMsg); if (!$res) { JError::raiseNotice(E_NOTICE, "error writing html to log file: " . $logs_file); } } } else { if ($ext == 'txt') { $txtMsg = "Date: " . $date . "\n"; $txtMsg .= "Form ID: " . $formModel->getId() . "\n"; $txtMsg .= "Table ID: " . $formModel->getListModel()->getId() . "\n"; $txtMsg .= "Row ID: " . (int) $rowid . "\n"; $txtMsg .= "User ID: {$userid} ({$username})\n"; if ($params->get('logs_record_ip') == 1) { $txtMsg .= "IP Address: " . $_SERVER['REMOTE_ADDR'] . "\n"; } if ($params->get('logs_record_referer') == 1) { $txtMsg .= "Referer: " . $http_referrer . "\n"; } if ($params->get('logs_record_useragent') == 1) { $txtMsg .= "UserAgent: " . $_SERVER['HTTP_USER_AGENT'] . "\n"; } $txtMsg .= $result_compare . $sep . "\n"; if ($send_email) { $email_msg = $txtMsg; } if ($make_file) { $txtMsg = $buffer . $txtMsg; JFile::write($logs_file, $txtMsg); } } else { // Making the CSV file if ($ext == 'csv') { $csvMsg = array(); // If the file already exists, do not add the 'label line' if ($labels == 1) { $csvMsg[] = "Date"; if ($params->get('logs_record_ip') == 1) { // Putting some "" around the label to avoid two different fields $csvMsg[] = "\"IP Address\""; } if ($params->get('logs_record_referer') == 1) { $csvMsg[] = "Referer"; } if ($params->get('logs_record_useragent') == 1) { $csvMsg[] = "UserAgent"; } if ($params->get('compare_data') == 1) { $csvMsg[] = "\"" . JText::_('COMPARE_DATA_LABEL_CSV') . "\""; } } // Inserting data in CSV with actual line break as row separator $csvMsg[] = "\n\"" . $date . "\""; if ($params->get('logs_record_ip') == 1) { $csvMsg[] = "\"" . $_SERVER['REMOTE_ADDR'] . "\""; } if ($params->get('logs_record_referer') == 1) { $csvMsg[] = "\"" . $http_referrer . "\""; } if ($params->get('logs_record_useragent') == 1) { $csvMsg[] = "\"" . $_SERVER['HTTP_USER_AGENT'] . "\""; } if ($params->get('compare_data') == 1) { $csvMsg[] = "\"" . $result_compare . "\""; } $csvMsg = implode(",", $csvMsg); if ($send_email) { $email_msg = $csvMsg; } if ($make_file) { if ($buffer !== '') { $csvMsg = $buffer . $csvMsg; } JFile::write($logs_file, $csvMsg); } } } } } } if ($params->get('logs_record_in_db') == 1) { // In which table? if ($params->get('record_in') == '') { $rdb = '#__fabrik_log'; } else { $db_suff = $params->get('record_in'); $form = $formModel->getForm(); $fid = $form->id; $db->setQuery("SELECT " . $db->quoteName('db_table_name') . " FROM " . $db->quoteName('#__fabrik_lists') . " WHERE " . $db->quoteName('form_id') . " = " . (int) $fid); $tname = $db->loadResult(); $rdb = $db->quoteName($tname . $db_suff); } // Making the message to record if ($params->get('custom_msg') != '') { $message = preg_replace('/<br\\/>/', ' ', $custom_msg); } else { $message = $this->makeStandardMessage($params, $result_compare); } // $$$ hugh - FIXME - not sure about the option driven $create_custom_table stuff, as this won't work // if they add an option to an existing log table. We should probably just create all the optional columns // regardless. if ($params->get('record_in') == '') { $in_db = "INSERT INTO {$rdb} (" . $db->quoteName('referring_url') . ", " . $db->quoteName('message_type') . ", " . $db->quoteName('message') . ") VALUES (" . $db->Quote($http_referrer) . ", " . $db->Quote($messageType) . ", " . $db->Quote($message) . ");"; $db->setQuery($in_db); $db->query(); } else { $create_custom_table = "CREATE TABLE IF NOT EXISTS {$rdb} (" . $db->quoteName('id') . " int(11) NOT NULL auto_increment PRIMARY KEY, {$clabels_createdb});"; $db->setQuery($create_custom_table); $db->query(); $in_db = "INSERT INTO {$rdb} ({$clabels_db}) VALUES ({$cdata_db});"; $db->setQuery($in_db); if (!$db->query()) { // $$$ changed to always use db fields even if not selected // so logs already created may need optional fields added. // try adding every field we should have, don't care if query fails. foreach ($clabelsCreateDb as $insert) { $db->setQuery("ALTER TABLE ADD {$insert} AFTER `id`"); $db->query(); } // ... and try the insert query again $db->setQuery($in_db); $db->query(); } } } if ($send_email) { jimport('joomla.mail.helper'); $config =& JFactory::getConfig(); $email_from = $config->getValue('mailfrom'); $email_to = explode(',', $w->parseMessageForPlaceholder($params->get('log_send_email_to', ''))); $subject = strip_tags($w->parseMessageForPlaceholder($params->get('log_send_email_subject', 'log event'))); foreach ($email_to as $email) { $email = trim($email); if (empty($email)) { continue; } if (JMailHelper::isEmailAddress($email)) { $res = JUtility::sendMail($email_from, $email_from, $email, $subject, $email_msg, true); } else { JError::raiseNotice(500, JText::sprintf('DID_NOT_SEND_EMAIL_INVALID_ADDRESS', $email)); } } } return true; }
function getFusionchart() { $document =& JFactory::getDocument(); $params =& $this->getParams(); $worker = new FabrikWorker(); $fc_version = $params->get('fusionchart_version', 'free_old'); if ($fc_version == 'free_22') { require_once $this->pathBase . 'fusionchart' . DS . 'lib' . DS . 'FusionChartsFree' . DS . 'Code' . DS . 'PHPClass' . DS . 'Includes' . DS . 'FusionCharts_Gen.php'; $document->addScript($this->srcBase . "fusionchart/lib/FusionChartsFree/JSClass/FusionCharts.js"); $fc_swf_path = COM_FABRIK_LIVESITE . $this->srcBase . "fusionchart/lib/FusionChartsFree/Charts/"; } else { if ($fc_version == 'pro_30') { require_once $this->pathBase . 'fusionchart' . DS . 'lib' . DS . 'FusionCharts' . DS . 'Code' . DS . 'PHPClass' . DS . 'Includes' . DS . 'FusionCharts_Gen.php'; $document->addScript($this->srcBase . "fusionchart/lib/FusionCharts/Charts/FusionCharts.js"); $fc_swf_path = COM_FABRIK_LIVESITE . $this->srcBase . "fusionchart/lib/FusionCharts/Charts/"; } else { require_once $this->pathBase . 'fusionchart' . DS . 'lib' . DS . 'FCclass' . DS . 'FusionCharts_Gen.php'; $document->addScript($this->srcBase . "fusionchart/lib/FCcharts/FusionCharts.js"); $fc_swf_path = COM_FABRIK_LIVESITE . $this->srcBase . "fusionchart/lib/FCcharts/"; } } $calc_prefixes = array('sum___', 'avg___', 'med___', 'cnt___'); $calc_prefixmap = array('sum___' => 'sums', 'avg___' => 'avgs', 'med___' => 'medians', 'cnt___' => 'count'); $w = $params->get('fusionchart_width'); $h = $params->get('fusionchart_height'); $chartType = $params->get('fusionchart_type'); // Create new chart $FC = new FusionCharts("{$chartType}", "{$w}", "{$h}"); //$FC->JSC["debugmode"]=true; // Define path to FC's SWF $FC->setSWFPath($fc_swf_path); $this->setChartMessages($FC); // Setting Param string $strParam = $this->getChartParams(); $label_step_ratios = (array) $params->get('fusion_label_step_ratio'); $x_axis_label = (array) $params->get('fusion_x_axis_label'); $chartElements = (array) $params->get('fusionchart_elementList'); $chartColours = (array) $params->get('fusionchart_colours'); $listid = (array) $params->get('fusionchart_table'); $axisLabels = (array) $params->get('fusionchart_axis_labels'); foreach ($axisLabels as $axis_key => $axis_val) { //$worker->replaceRequest($axis_val); $axisLabels[$axis_key] = $worker->parseMessageForPlaceholder($axis_val, null, false); } $dual_y_parents = $params->get('fusionchart_dual_y_parent'); $measurement_units = (array) $params->get('fusion_x_axis_measurement_unit'); $legends = $params->get('fusiongraph_show_legend', ''); $chartWheres = (array) $params->get('fusionchart_where'); $c = 0; $gdata = array(); $glabels = array(); $gcolours = array(); $gfills = array(); $max = array(); $min = array(); $calculationLabels = array(); $calculationData = array(); $calcfound = false; $tmodels = array(); $labelStep = 0; foreach ($listid as $tid) { $min[$c] = 0; $max[$c] = 0; if (!array_key_exists($tid, $tmodels)) { $listModel = null; $listModel = JModel::getInstance('list', 'FabrikFEModel'); $listModel->setId($tid); $tmodels[$tid] = $listModel; } else { $listModel = $tmodels[$tid]; } $table = $listModel->getTable(); $form = $listModel->getForm(); // $$$ hugh - adding plugin query, 2012-02-08 if (array_key_exists($c, $chartWheres) && !empty($chartWheres[$c])) { $chartWhere = $this->_replaceRequest($chartWheres[$c]); $listModel->setPluginQueryWhere('fusionchart', $chartWhere); } else { // if no where clause, explicitly clear any previously set clause $listModel->unsetPluginQueryWhere('fusionchart'); } // $$$ hugh - remove pagination BEFORE calling render(). Otherwise render() applies // session state/defaults when it calls getPagination, which is then returned as a cached // object if we call getPagination after render(). So call it first, then render() will // get our cached pagination, rather than vice versa. $nav = $listModel->getPagination(0, 0, 0); $listModel->render(); //$listModel->doCalculations(); $alldata = $listModel->getData(); $cals = $listModel->getCalculations(); $column = $chartElements[$c]; //$measurement_unit = $measurement_units[$c]; $measurement_unit = JArrayHelper::getValue($measurement_units, $c, ''); $pref = substr($column, 0, 6); $label = JArrayHelper::getValue($x_axis_label, $c, ''); $tmpgdata = array(); $tmpglabels = array(); $colour = array_key_exists($c, $chartColours) ? str_replace("#", '', $chartColours[$c]) : ''; $gcolours[] = $colour; if (in_array($pref, $calc_prefixes)) { // you shouldnt mix calculation elements with normal elements when creating the chart // so if ONE calculation element is found we use the calculation data rather than normal element data // this is because a calculation element only generates one value, if want to compare two averages then //they get rendered as tow groups of data and on bar charts this overlays one average over the other, rather than next to it $calcfound = true; $column = substr($column, 6); $calckey = $calc_prefixmap[$pref]; $caldata = JArrayHelper::getValue($cals[$calckey], $column . '_obj'); if (is_array($caldata)) { foreach ($caldata as $k => $o) { $calculationData[] = (double) $o->value; $calculationLabels[] = trim(strip_tags($o->label)); } } if (!empty($calculationData)) { $max[$c] = max($calculationData); $min[$c] = min($calculationData); } $gdata[$c] = implode(',', $tmpgdata); $glabels[$c] = implode('|', $tmpglabels); // $$$ hugh - playing around with pie charts //$gsums[$c] = array_sum($tmpgdata); $gsums[$c] = array_sum($calculationData); } else { $origColumn = $column; $column = $column . "_raw"; //_raw fields are most likely to contain the value foreach ($alldata as $group) { foreach ($group as $row) { if (!array_key_exists($column, $row)) { //didnt find a _raw column - revent to orig $column = $origColumn; if (!array_key_exists($column, $row)) { JError::raiseWarning(E_NOTICE, $column . ': NOT FOUND - PLEASE CHECK IT IS PUBLISHED'); continue; } } if (trim($row->{$column}) == '') { $tmpgdata[] = -1; } else { $tmpgdata[] = (double) $row->{$column}; } $tmpglabels[] = !empty($label) ? strip_tags($row->{$label}) : ''; } if (!empty($tmpgdata)) { $max[$c] = max($tmpgdata); $min[$c] = min($tmpgdata); } $gdata[$c] = implode(',', $tmpgdata); $glabels[$c] = implode('|', $tmpglabels); // $$$ hugh - playing around with pie charts $gsums[$c] = array_sum($tmpgdata); } } $c++; } if ($calcfound) { $calculationLabels = array_reverse($calculationLabels); // $$$ rob implode with | and not ',' as : //$labels = explode('|',$glabels[0]); is used below //$glabels = array(implode(',', array_reverse($calculationLabels))); $glabels = array(implode('|', array_reverse($calculationLabels))); // $$$ rob end $gdata = array(implode(',', $calculationData)); } // $$$ hugh - pie chart data has to be summed - the API only takes a // single dataset for pie charts. And it doesn't make sense trying to // chart individual row data for multiple elements in a pie chart. // Also, labels need to be axisLabels, not $glabels switch ($chartType) { // Single Series Charts case 'AREA2D': case 'BAR2D': case 'COLUMN2D': case 'COLUMN3D': case 'DOUGHNUT2D': case 'DOUGHNUT3D': case 'LINE': // $$$ tom - for now I'm enabling Pie charts here so that it displays // something until we do it properly as you said hugh // Well maybe there's something I don't get but in fact FC already draw // the pies by "percenting" the values of each data... if you know what I mean Hugh;) // $$$ tom - for now I'm enabling Pie charts here so that it displays // something until we do it properly as you said hugh // Well maybe there's something I don't get but in fact FC already draw // the pies by "percenting" the values of each data... if you know what I mean Hugh;) case 'PIE2D': case 'PIE3D': case 'SCATTER': // Adding specific params for Pie charts if ($chartType == 'PIE2D' || $chartType == 'PIE3D') { $strParam .= ';pieBorderThickness=' . $params->get('fusionchart_borderthick', ''); $strParam .= ';pieBorderAlpha=' . $params->get('fusionchart_cnvalpha', ''); $strParam .= ';pieFillAlpha=' . $params->get('fusionchart_elalpha', ''); } if ($c > 1) { $arrCatNames = array(); foreach ($axisLabels as $alkey => $al) { $arrCatNames[] = $al; } $arrData = array(); $i = 0; foreach ($gsums as $gd) { $arrData[$i][0] = $axisLabels[$i]; $arrData[$i][1] = $gd; $i++; } $FC->addChartDataFromArray($arrData, $arrCatNames); } else { // single table/elements, so use the row data $labels = explode('|', $glabels[0]); $gsums = explode(',', $gdata[0]); // scale to percentages $tot_sum = array_sum($gsums); $arrData = array(); $labelStep = 0; $label_step_ratio = (int) JArrayHelper::getValue($label_step_ratios, 0, 1); if ($label_step_ratio > 1) { $labelStep = (int) (count($gsums) / $label_step_ratio); $strParam .= ";labelStep={$labelStep}"; } //$$$tom: inversing array_combine as identical values in gsums will be // dropped otherwise. Should I do that differently? // $$$ hugh - can't use array_combine, as empty labels end up dropping values //$arrComb = array_combine($labels, $gsums); //foreach ($arrComb as $key => $value) { $data_count = 0; foreach ($gsums as $key => $value) { $data_count++; if ($value == '-1') { $value = null; } $label = $labels[$key]; $str_params = "name={$label}"; if ($labelStep) { if ($data_count != 1 && $data_count % $labelStep != 0) { $str_params .= ";showName=0"; } } $FC->addChartData("{$value}", $str_params); } } break; case 'MSBAR2D': case 'MSBAR3D': case 'MSCOLUMN2D': case 'MSCOLUMN3D': case 'MSLINE': case 'MSAREA2D': case 'MSCOMBIDY2D': case 'MULTIAXISLINE': //case 'PIE2D': //case 'PIE3D': //case 'PIE2D': //case 'PIE3D': case 'STACKEDAREA2D': case 'STACKEDBAR2D': case 'STACKEDCOLUMN2D': case 'STACKEDCOLUMN3D': case 'SCROLLAREA2D': case 'SCROLLCOLUMN2D': case 'SCROLLLINE2D': case 'SCROLLSTACKEDCOLUMN2D': /*$chd = implode('|', $gdata); if (!empty($chds_override)) { $chds = $chds_override; } else if ($c > 1 && !$calcfound) { $minmax = $this->_getMinMax($gsums); $chds = $minmax['min'] . ',' . $minmax['max']; } else { $chds = $min.','.$max; } if ($calcfound) { $glabels = array(implode('|', $calculationLabels)); } // $$$ hugh - we have to reverse the labels for horizontal bar charts $glabels[0] = implode('|',array_reverse(explode('|',$glabels[0]))); if (empty($chxl_override)) { $chxl = '0:|'.$min.'|'.$max.$measurement_unit.'|'.'1:|'.$glabels[0]; } else { $chxl = '0:|'.$chxl_override.'|'.'1:|'.$glabels[0]; } break; */ if ($c > 1) { if ($chartType == 'SCROLLAREA2D' || $chartType == 'SCROLLCOLUMN2D' || $chartType == 'SCROLLLINE2D') { $strParam .= ';numVisiblePlot=' . $params->get('fusionchart_scroll_numvisible', 0); } // $$$ hugh - Dual-Y types if ($chartType == 'MSCOMBIDY2D' || $chartType == 'MULTIAXISLINE') { //var_dump($axisLabels); /* $strParam .= ';PYAxisName='.$axisLabels[0]; $strParam .= ';SYAxisName='.$axisLabels[1]; */ $p_parents = array(); $s_parents = array(); foreach ($dual_y_parents as $dual_y_key => $dual_y_parent) { if ($dual_y_parent == "P") { $p_parents[] = $axisLabels[$dual_y_key]; } else { $s_parents[] = $axisLabels[$dual_y_key]; } } $strParam .= ';PYAxisName=' . implode(' ', $p_parents); $strParam .= ';SYaxisName=' . implode(' ', $s_parents); } //$$$tom: This is a first attempt at integrating Trendlines but it's not actually working... :s $eltype = $params->get('fusionchart_element_type', 'dataset'); for ($nbe = 0; $nbe < $c; $nbe++) { if ($eltype[$nbe] != 'dataset') { // Trendline Start & End values $trendstart = $params->get('fusionchart_trendstartvalue', ''); $trendend = $params->get('fusionchart_trendendvalue', ''); if ($trendstart) { $startval = $trendstart; $endval = $trendend; } else { if ($eltype[$nbe] == 'trendline') { // If Start & End values are not specifically defined, use the element's min & max values $startval = $min[$nbe]; $endval = $max[$nbe]; } } $strAddTrend = "startValue={$startval};endValue={$endval}"; // Label $displayval = $params->get('fusionchart_trendlabel', ''); $showontop = $params->get('fusionchart_trendshowontop', '1'); $iszone = $params->get('fusionchart_trendiszone', '0'); $elcolour = $params->get('fusionchart_elcolour', ''); $elalpha = $params->get('fusionchart_elalpha', ''); //$strAddTrend .= ";displayvalue=".$displayval; $strAddTrend .= ";displayvalue=" . $axisLabels[$nbe]; $strAddTrend .= ";showOnTop=" . $showontop; if ($startval < $endval) { $strAddTrend .= ";isTrendZone=" . $iszone; } $strAddTrend .= ";color=" . $elcolour[$nbe]; $strAddTrend .= ";alpha=" . $elalpha[$nbe]; $strAddTrend .= ";thickness=3"; //var_dump($strAddTrend); $FC->addTrendLine("{$strAddTrend}"); unset($axisLabels[$nbe]); unset($gdata[$nbe]); } } // end for loop /*------------------------------------------ * $$$tom: I'm trying something else, as per http://www.fusioncharts.com/free/docs/Contents/PHPClassAPI/MultiSeriesChart.html * A MS Chart should use for example 2 elements from the same table and have Categories * (the colored legend below the chart, e.g. "This month", "Previous month"). * Then different Datasets must be defined (e.g. one by row in the table: "Week 1", "Week 2", ...) * And finally some Data for each Dataset (e.g. Sales: "40200", "38350", ...) * Of course I kept what you made Hugh, I commented out between this comment and what I've added. ------------------------------------------*/ /*if ($calcfound) { $glabels = array(implode('|', $calculationLabels)); } $arrCatNames = array(); foreach ($axisLabels as $alkey => $al) { $arrCatNames[] = $al; } $arrData = array(); $i = 0; foreach ($gdata as $gdkey => $gd) { $arrData[$i][0] = $glabels[$i]; $arrData[$i][1] = ''; $arrData[$i] = array_merge($arrData[$i], explode(',', $gd)); $i++; } $FC->addChartDataFromArray($arrData, $arrCatNames);*/ $label_step_ratio = (int) JArrayHelper::getValue($label_step_ratios, 0, 1); if ($label_step_ratio > 1) { $labelStep = (int) (count(explode(',', $gdata[0])) / $label_step_ratio); $strParam .= ";labelStep={$labelStep}"; } // Start tom's changes $labels = explode('|', $glabels[0]); $data_count = 0; foreach ($labels as $catLabel) { $data_count++; $catParams = ''; if ($labelStep) { if ($data_count == 1 || $data_count % $labelStep == 0) { $catParams = "ShowLabel=1"; } else { $catParams = "ShowLabel=0"; $catLabel = ''; } } $FC->addCategory($catLabel, $catParams); } foreach ($gdata as $key => $chartdata) { $cdata = explode(',', $chartdata); $dataset = $axisLabels[$key]; $extras = "parentYAxis=" . $dual_y_parents[$key]; //var_dump($dual_y_parents, $dataset, $extras); $FC->addDataset("{$dataset}", $extras); $data_count = 0; foreach ($cdata as $key => $value) { $data_count++; if ($value == '-1') { $value = null; } $FC->addChartData("{$value}"); } } // End tom's changes } else { //$foo = $foo; } /* default: $chd = implode('|', $gdata); $chxl = '0:|'.$glabels[0].'|'.'1:|'.$min.'|'.$max; if ($c > 1 && !$calcfound) { $minmax = $this->_getMinMax($gsums); $chds = $minmax['min'] . ',' . $minmax['max']; } else { $chds = $min.','.$max; } break; */ } $colours = implode($calcfound ? '|' : ',', $gcolours); /*$return = '<img src="' . $this->_url . '?'; $qs = 'chs='.$w.'x'.$h; $qs .= '&chd=t:'.$chd; $qs .= '&cht='.$graph; $qs .= '&chco='.$colours; $qs .= '&chxt=x,y'; $qs .= '&chxl='.$chxl; $qs .= '&chds='.$chds; if ($fillGraphs) { $qs .= '&chm=' . implode('|', $gfills); } if ($legends) { $qs .= '&chdl=' . implode('|', $axisLabels); } if (!empty($chg_override)) { $qs .= '&chg=' . $chg_override; } if (!empty($chm_override)) { $qs .= '&chm=' . $chm_override; } else if ($fillGraphs) { $qs .= '&chm=' . implode('|', $gfills); } $return .= $qs . '" alt="'.$this->_row->label.'" />'; $this->image = $return;*/ # Set chart attributes if ($params->get('fusionchart_custom_attributes', '')) { $strParam .= ';' . trim($params->get('fusionchart_custom_attributes')); } $strParam = "{$strParam}"; $FC->setChartParams($strParam); # Render Chart if ($chartType == 'MULTIAXISLINE') { // Nasty, nasty hack for MULTIAXIS, as the FC class doesn't support it. So need to get the chart XML, // split out the <dataset>...</dataset> and wrap them in <axis>...</axis> $axis_attrs = (array) $params->get('fusionchart_mx_attributes'); $dataXML = $FC->getXML(); $matches = array(); if (preg_match_all('#(<\\s*dataset[^>]*>.*?<\\s*/dataset\\s*>)#', $dataXML, $matches)) { $index = 0; foreach ($gdata as $key => $chartdata) { $axis = "<axis " . $axis_attrs[$index] . ">" . $matches[0][$index] . "</axis>"; $dataXML = str_replace($matches[0][$index], $axis, $dataXML); $index++; } } return $FC->renderChartFromExtXML($dataXML); } else { return $FC->renderChart(false, false); } }
/** * Do the plug-in action * * @param object $params plugin parameters * @param object &$model list model * @param array $opts custom options * * @return bool */ public function process($params, &$model, $opts = array()) { $db = $model->getDb(); $user = JFactory::getUser(); $update = json_decode($params->get('update_col_updates')); if (!$update) { return false; } // $$$ rob moved here from bottom of func see http://fabrikar.com/forums/showthread.php?t=15920&page=7 $dateCol = $params->get('update_date_element'); $userCol = $params->get('update_user_element'); $item = $model->getTable(); // Array_unique for left joined table data $ids = array_unique(JRequest::getVar('ids', array(), 'method', 'array')); JArrayHelper::toInteger($ids); $this->_row_count = count($ids); $ids = implode(',', $ids); $model->reset(); $model->_pluginQueryWhere[] = $item->db_primary_key . ' IN ( ' . $ids . ')'; $data = $model->getData(); // $$$servantek reordered the update process in case the email routine wants to kill the updates $emailColID = $params->get('update_email_element', ''); if (!empty($emailColID)) { $w = new FabrikWorker(); jimport('joomla.mail.helper'); $message = $params->get('update_email_msg'); $subject = $params->get('update_email_subject'); $eval = $params->get('eval', 0); $config = JFactory::getConfig(); $from = $config->getValue('mailfrom'); $fromname = $config->getValue('fromname'); $elementModel = FabrikWorker::getPluginManager()->getElementPlugin($emailColID); $emailElement = $elementModel->getElement(true); $emailField = $elementModel->getFullName(false, true, false); $emailColumn = $elementModel->getFullName(false, false, false); $emailFieldRaw = $emailField . '_raw'; $emailWhich = $emailElement->plugin == 'user' ? 'user' : 'field'; $tbl = array_shift(explode('.', $emailColumn)); $db = JFactory::getDBO(); $aids = explode(',', $ids); // If using a user element, build a lookup list of emails from #__users, // so we're only doing one query to grab all involved emails. if ($emailWhich == 'user') { $userids_emails = array(); $query = $db->getQuery(); $query->select('#__users.id AS id, #__users.email AS email')->from('#__users')->join('LEFT', $tbl . ' ON #__users.id = ' . $emailColumn)->where(_primary_key . ' IN (' . $ids . ')'); $db->setQuery($query); $results = $db->loadObjectList(); foreach ($results as $result) { $userids_emails[(int) $result->id] = $result->email; } } foreach ($aids as $id) { $row = $model->getRow($id); if ($emailWhich == 'user') { $userid = (int) $row->{$emailFieldRaw}; $to = JArrayHelper::getValue($userids_emails, $userid); } else { $to = $row->{$emailField}; } if (JMailHelper::cleanAddress($to) && JMailHelper::isEmailAddress($to)) { // $tofull = '"' . JMailHelper::cleanLine($toname) . '" <' . $to . '>'; // $$$servantek added an eval option and rearranged placeholder call $thissubject = $w->parseMessageForPlaceholder($subject, $row); $thismessage = $w->parseMessageForPlaceholder($message, $row); if ($eval) { $thismessage = @eval($thismessage); FabrikWorker::logEval($thismessage, 'Caught exception on eval in updatecol::process() : %s'); } $res = JUtility::sendMail($from, $fromname, $to, $thissubject, $thismessage, true); if ($res) { $this->_sent++; } else { ${$this}->_notsent++; } } else { $this->_notsent++; } } } // $$$servantek reordered the update process in case the email routine wants to kill the updates if (!empty($dateCol)) { $date = JFactory::getDate(); $this->_process($model, $dateCol, $date->toSql()); } if (!empty($userCol)) { $this->_process($model, $userCol, (int) $user->get('id')); } foreach ($update->coltoupdate as $i => $col) { $this->_process($model, $col, $update->update_value[$i]); } $this->msg = $params->get('update_message', ''); if (empty($this->msg)) { $this->msg = JText::sprintf('PLG_LIST_UPDATE_COL_UPDATE_MESSAGE', $this->_row_count, $this->_sent); } else { $this->msg = JText::sprintf($this->msg, $this->_row_count, $this->_sent); } // Clean the cache. $cache = JFactory::getCache(JRequest::getCmd('option')); $cache->clean(); return true; }
/** * do the plugin action * @param object parameters * @param object table model */ function process(&$params, &$model, $opts = array()) { $db =& $model->getDb(); $user =& JFactory::getUser(); $updateTo = $params->get('update_value'); $updateCol = $params->get('coltoupdate'); $updateTo_2 = $params->get('update_value_2'); $updateCol_2 = $params->get('coltoupdate_2'); // $$$ rob moved here from bottom of func see http://fabrikar.com/forums/showthread.php?t=15920&page=7 $tbl = array_shift(explode('.', $updateCol)); $dateCol = $params->get('update_date_element'); $userCol = $params->get('update_user_element'); $table =& $model->getTable(); // array_unique for left joined table data $ids = array_unique(JRequest::getVar('ids', array(), 'method', 'array')); JArrayHelper::toInteger($ids); $this->_row_count = count($ids); $ids = implode(',', $ids); $model->_pluginQueryWhere[] = $table->db_primary_key . ' IN ( ' . $ids . ')'; $data =& $model->getData(); //$$$servantek reordered the update process in case the email routine wants to kill the updates $emailColID = $params->get('update_email_element', ''); if (!empty($emailColID)) { $w = new FabrikWorker(); jimport('joomla.mail.helper'); $message = $params->get('update_email_msg'); $subject = $params->get('update_email_subject'); $eval = $params->get('eval', 0); $config =& JFactory::getConfig(); $from = $config->getValue('mailfrom'); $fromname = $config->getValue('fromname'); $elementModel =& JModel::getInstance('element', 'FabrikModel'); $elementModel->setId($emailColID); $emailElement =& $elementModel->getElement(true); $emailField = $elementModel->getFullName(false, true, false); $emailColumn = $elementModel->getFullName(false, false, false); $emailFieldRaw = $emailField . '_raw'; $emailWhich = $emailElement->plugin == 'fabrikuser' ? 'user' : 'field'; $db =& JFactory::getDBO(); $aids = explode(',', $ids); // if using a user element, build a lookup list of emails from jos_users, // so we're only doing one query to grab all involved emails. if ($emailWhich == 'user') { $userids_emails = array(); $query = 'SELECT #__users.id AS id, #__users.email AS email FROM #__users LEFT JOIN ' . $tbl . ' ON #__users.id = ' . $emailColumn . ' WHERE ' . $table->db_primary_key . ' IN (' . $ids . ')'; $db->setQuery($query); $results = $db->loadObjectList(); foreach ($results as $result) { $userids_emails[(int) $result->id] = $result->email; } } foreach ($aids as $id) { $row = $model->getRow($id); if ($emailWhich == 'user') { $userid = (int) $row->{$emailFieldRaw}; $to = $userids_emails[$userid]; } else { $to = $row->{$emailField}; } if (JMailHelper::cleanAddress($to) && JMailHelper::isEmailAddress($to)) { //$tofull = '"' . JMailHelper::cleanLine($toname) . '" <' . $to . '>'; //$$$servantek added an eval option and rearranged placeholder call $thissubject = $w->parseMessageForPlaceholder($subject, $row); $thismessage = $w->parseMessageForPlaceholder($message, $row); if ($eval) { $thismessage = @eval($thismessage); FabrikWorker::logEval($thismessage, 'Caught exception on eval in updatecol::process() : %s'); } $res = JUtility::sendMail($from, $fromname, $to, $thissubject, $thismessage, true); if ($res) { $this->_sent++; } else { ${$this}->_notsent++; } } else { $this->_notsent++; } } } //$$$servantek reordered the update process in case the email routine wants to kill the updates if (!empty($dateCol)) { $date =& JFactory::getDate(); $this->_process($model, $dateCol, $date->toMySQL()); } if (!empty($userCol)) { $this->_process($model, $userCol, (int) $user->get('id')); } $this->_process($model, $updateCol, $updateTo); if (!empty($updateCol_2)) { $this->_process($model, $updateCol_2, $updateTo_2); } // $$$ hugh - this stuff has to go in process_result() //$msg = $params->get( 'update_message' ); //return JText::sprintf( $msg, count($ids)); $this->msg = $params->get('update_message', ''); if (empty($this->msg)) { $this->msg = JText::sprintf('%d ROWS UPDATED, %d EMAILS SENT', $this->_row_count, $this->_sent); } else { $this->msg = JText::sprintf($this->msg, $this->_row_count, $this->_sent); } return true; }
/** * Update the form models data with data from CURL request * * @param Joomla\Registry\Registry $params Parameters * @param array $responseBody Response body * @param array $data Data returned from CURL request * * @return void */ protected function updateFormModelData($params, $responseBody, $data) { $w = new FabrikWorker(); $dataMap = $params->get('put_include_list', ''); $include = $w->parseMessageForPlaceholder($dataMap, $responseBody, true); $formModel = $this->getModel(); if (FabrikWorker::isJSON($include)) { $include = json_decode($include); $keys = $include->put_key; $values = $include->put_value; $defaults = $include->put_value; for ($i = 0; $i < count($keys); $i++) { $key = $keys[$i]; $default = $defaults[$i]; $localKey = FabrikString::safeColNameToArrayKey($values[$i]); $remoteData = FArrayHelper::getNestedValue($data, $key, $default, true); if (!is_null($remoteData)) { $formModel->_data[$localKey] = $remoteData; } } } }
/** * process the plugin, called when form is submitted * * @param object $params * @param object form model * @returns bol */ function onAfterProcess($params, &$formModel) { jimport('joomla.mail.helper'); $user =& JFactory::getUser(); $config =& JFactory::getConfig(); $db =& JFactory::getDBO(); $this->formModel =& $formModel; $formParams = $formModel->getParams(); $ftpTemplate = JPath::clean(JPATH_SITE . DS . 'components' . DS . 'com_fabrik' . DS . 'plugins' . DS . 'form' . DS . 'fabrikftp' . DS . 'tmpl' . DS . $params->get('ftp_template', '')); $this->data = array_merge($formModel->_formData, $this->getEmailData()); if (!$this->shouldProcess('ftp_conditon')) { return; } $contentTemplate = $params->get('ftp_template_content'); if ($contentTemplate != '') { $content = $this->_getConentTemplate($contentTemplate); } else { $content = ''; } if (JFile::exists($ftpTemplate)) { if (JFile::getExt($ftpTemplate) == 'php') { $message = $this->_getPHPTemplateFtp($ftpTemplate); } else { $message = $this->_getTemplateFtp($ftpTemplate); } $message = str_replace('{content}', $content, $message); } else { if ($contentTemplate != '') { $message = $content; } else { $message = $this->_getTextFtp(); } } $cc = null; $bcc = null; $w = new FabrikWorker(); // $$$ hugh - test stripslashes(), should be safe enough. $message = stripslashes($message); $editURL = COM_FABRIK_LIVESITE . "index.php?option=com_fabrik&view=form&fabrik=" . $formModel->get('id') . "&rowid=" . JRequest::getVar('rowid'); $viewURL = COM_FABRIK_LIVESITE . "index.php?option=com_fabrik&view=details&fabrik=" . $formModel->get('id') . "&rowid=" . JRequest::getVar('rowid'); $editlink = "<a href=\"{$editURL}\">" . JText::_('EDIT') . "</a>"; $viewlink = "<a href=\"{$viewURL}\">" . JText::_('VIEW') . "</a>"; $message = str_replace('{fabrik_editlink}', $editlink, $message); $message = str_replace('{fabrik_viewlink}', $viewlink, $message); $message = str_replace('{fabrik_editurl}', $editURL, $message); $message = str_replace('{fabrik_viewurl}', $viewURL, $message); $ftp_filename = $params->get('ftp_filename', ''); $ftp_filename = $w->parseMessageForPlaceholder($ftp_filename, $this->data, false); $ftp_eval_filename = (int) $params->get('ftp_eval_filename', '0'); if ($ftp_eval_filename) { $ftp_filename = @eval($ftp_filename); FabrikWorker::logEval($email_to_eval, 'Caught exception on eval in ftp filename eval : %s'); } if (empty($ftp_filename)) { JError::raiseNotice(500, JText::sprintf('PLG_FTP_NO_FILENAME', $email)); } $ftp_host = $w->parseMessageForPlaceholder($params->get('ftp_host', ''), $this->data, false); $ftp_port = $w->parseMessageForPlaceholder($params->get('ftp_port', '21'), $this->data, false); $ftp_chdir = $w->parseMessageForPlaceholder($params->get('ftp_chdir', ''), $this->data, false); $ftp_user = $w->parseMessageForPlaceholder($params->get('ftp_user', ''), $this->data, false); $ftp_password = $w->parseMessageForPlaceholder($params->get('ftp_password', ''), $this->data, false); $config =& JFactory::getConfig(); $tmp_dir = rtrim($config->getValue('config.tmp_path'), DS); if (empty($tmp_dir) || !JFolder::exists($tmp_dir)) { JError::raiseError(500, 'PLG_FORM_FTP_NO_JOOMLA_TEMP_DIR'); return false; } $tmp_file = $tmp_dir . DS . 'fabrik_ftp_' . md5(uniqid()); $message = $w->parseMessageForPlaceholder($message, $this->data, true, false); if (JFile::write($tmp_file, $message)) { $conn_id = ftp_connect($ftp_host, $ftp_port); if ($conn_id) { if (@ftp_login($conn_id, $ftp_user, $ftp_password)) { if (!empty($ftp_chdir)) { if (!ftp_chdir($conn_id, $ftp_chdir)) { JError::raiseNotice(500, JText::_('PLG_FORM_FTP_COULD_NOT_CHDIR')); JFile::delete($tmp_file); return false; } } if (!ftp_put($conn_id, $ftp_filename, $tmp_file, FTP_ASCII)) { JError::raiseNotice(500, JText::_('PLG_FORM_FTP_COULD_NOT_SEND_FILE')); JFile::delete($tmp_file); return false; } } else { JError::raiseNotice(500, JText::_('PLG_FORM_FTP_COULD_NOT_LOGIN')); JFile::delete($tmp_file); return false; } } else { JError::raiseError(500, 'PLG_FORM_FTP_COULD_NOT_CONNECT'); JFile::delete($tmp_file); return false; } } else { JError::raiseError(500, 'PLG_FORM_FTP_COULD_NOT_WRITE_TEMP_FILE'); JFile::delete($tmp_file); return false; } JFile::delete($tmp_file); return true; }
/** * Add attachments to the email * * @return void */ protected function addAttachments() { $params = $this->getParams(); $data = $this->getProcessData(); /** @var FabrikFEModelForm $formModel */ $formModel = $this->getModel(); $groups = $formModel->getGroupsHiarachy(); foreach ($groups as $groupModel) { $elementModels = $groupModel->getPublishedElements(); foreach ($elementModels as $elementModel) { $elName = $elementModel->getFullName(true, false); if (array_key_exists($elName, $this->data)) { if (method_exists($elementModel, 'addEmailAttachement')) { if (array_key_exists($elName . '_raw', $data)) { $val = $data[$elName . '_raw']; } else { $val = $data[$elName]; } if (is_array($val)) { if (is_array(current($val))) { // Can't implode multi dimensional arrays $val = json_encode($val); $val = FabrikWorker::JSONtoData($val, true); } } else { $val = array($val); } foreach ($val as $v) { $file = $elementModel->addEmailAttachement($v); if ($file !== false) { $this->attachments[] = $file; if ($elementModel->shouldDeleteEmailAttachment($v)) { $this->deleteAttachments[] = $file; } } } } } } } // $$$ hugh - added an optional eval for adding attachments. // Eval'd code should just return an array of file paths which we merge with $this->attachments[] $w = new FabrikWorker(); $emailAttachEval = $w->parseMessageForPlaceholder($params->get('email_attach_eval', ''), $this->data, false); if (!empty($emailAttachEval)) { $email_attach_array = @eval($emailAttachEval); FabrikWorker::logEval($email_attach_array, 'Caught exception on eval in email email_attach_eval : %s'); if (!empty($email_attach_array)) { $this->attachments = array_merge($this->attachments, $email_attach_array); } } }
/** * Send notification emails * * @param string $ids csv list of row ids. * * @return void */ protected function sendEmails($ids) { $params = $this->getParams(); $model = $this->getModel(); // Ensure that yesno exports text and not bootstrap icon. $model->setOutputFormat('csv'); $emailColID = $params->get('update_email_element', ''); $emailTo = $params->get('update_email_to', ''); if (!empty($emailColID) || !empty($emailTo)) { $w = new FabrikWorker(); jimport('joomla.mail.helper'); $aids = explode(',', $ids); $message = $params->get('update_email_msg'); $subject = $params->get('update_email_subject'); $eval = $params->get('eval', 0); $from = $this->config->get('mailfrom'); $fromName = $this->config->get('fromname'); $emailWhich = $this->emailWhich(); foreach ($aids as $id) { $row = $model->getRow($id, true); /** * hugh - hack to work around this issue: * https://github.com/Fabrik/fabrik/issues/1499 */ $this->params = $params; $to = trim($this->emailTo($row, $emailWhich)); $tos = explode(',', $to); $cleanTo = true; foreach ($tos as &$email) { $email = trim($email); if (!(JMailHelper::cleanAddress($email) && FabrikWorker::isEmail($email))) { $cleanTo = false; } } if ($cleanTo) { if (count($tos) > 1) { $to = $tos; } $thisSubject = $w->parseMessageForPlaceholder($subject, $row); $thisMessage = $w->parseMessageForPlaceholder($message, $row); if ($eval) { $thisMessage = @eval($thisMessage); FabrikWorker::logEval($thisMessage, 'Caught exception on eval in updatecol::process() : %s'); } $mail = JFactory::getMailer(); $res = $mail->sendMail($from, $fromName, $to, $thisSubject, $thisMessage, true); if ($res) { $this->sent++; } else { $this->notsent++; } } else { $this->notsent++; } } } }
function onAfterProcess(&$params, &$formModel) { $w = new FabrikWorker(); $config_userpass = $params->get('username') . ':' . $params->get('password'); $endpoint = $params->get('endpoint'); $headers = array('Content-Type: application/xml', 'Accept: application/xml'); $endpoint = $params->get('endpoint'); $endpoint = $w->parseMessageForPlaceholder($endpoint); // Here we set up CURL to grab the data from Unfuddle $chandle = curl_init(); $ticket = new SimpleXMLElement("<ticket></ticket>"); $ignore = array('trkr_tickets___id'); if ($formModel->_origRowId == 0) { $ingore[] = 'id'; } /*foreach($formModel->_formData as $key => $val){ if ($formModel->hasElement($key) && !in_array($key, $ignore)) { if (is_array($val)) { $val = implode(',', $val); } $ticket->addChild($key, $val); } } */ /* * $ticket = new SimpleXMLElement("<ticket></ticket>"); //$ticket->addChild('assignee-id', $this->config['default_assignee']); //$ticket->addChild('component-id', $data['component']); //$ticket->addChild('description', $data['description']); $ticket->addChild('milestone-id', 47420); //$ticket->addChild('priority', $data['priority']); //$ticket->addChild('severity-id', $data['severity']); $ticket->addChild('status', 'new'); $ticket->addChild('summary', 'test REST API from fabrik'); */ $include = array('milestone-id', 'status', 'summary'); foreach ($include as $i) { echo "{$i} = " . $formModel->_formData[$i] . "<br>"; $ticket->addChild($i, $formModel->_formData[$i]); } $output = $ticket->asXML(); $curl_options = array(CURLOPT_URL => $endpoint, CURLOPT_RETURNTRANSFER => 1, CURLOPT_HTTPHEADER => $headers, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $output, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_USERPWD => $config_userpass, CURLOPT_CUSTOMREQUEST => 'POST'); foreach ($curl_options as $key => $value) { curl_setopt($chandle, $key, $value); } $output = curl_exec($chandle); $httpCode = curl_getinfo($chandle, CURLINFO_HTTP_CODE); echo $httpCode . " : "; switch ($httpCode) { case '400': echo "Bad Request"; break; case '401': echo "Unauthorized"; break; case '404': echo "Not found"; break; case '405': echo "Method Not Allowed"; break; case '406': echo "Not Acceptable"; break; case '415': echo "Unsupported Media Type"; break; case '500': echo "Internal Server Error"; break; } if (curl_errno($chandle)) { die("ERROR: " . curl_error($chandle)); } curl_close($chandle); exit; }
/** * Get fields to update/insert * * @param bool $upsertRowExists * * @return array */ protected function upsertData($upsertRowExists = false) { $params = $this->getParams(); $w = new FabrikWorker(); $upsertDb = $this->getDb(); $upsert = json_decode($params->get('upsert_fields')); $fields = array(); /** @var FabrikFEModelForm $formModel */ $formModel = $this->getModel(); if ($formModel->isNewRecord() || !$upsertRowExists) { if ($params->get('upsert_pk_or_fk', 'pk') == 'fk') { $row_value = $params->get('row_value', ''); if ($row_value == '{origid}') { $fk = FabrikString::safeColName($params->get('primary_key')); $rowId = $formModel->getInsertId(); $fields[] = $fk . ' = ' . $upsertDb->q($rowId); } } } for ($i = 0; $i < count($upsert->upsert_key); $i++) { $k = FabrikString::shortColName($upsert->upsert_key[$i]); $k = $upsertDb->qn($k); $v = $upsert->upsert_value[$i]; $v = $w->parseMessageForPlaceholder($v, $this->data); if ($upsert->upsert_eval_value[$i] === '1') { $res = FabrikHelperHTML::isDebug() ? eval($v) : @eval($v); FabrikWorker::logEval($res, 'Eval exception : upsert : ' . $v . ' : %s'); $v = $res; } if ($v == '') { $v = $w->parseMessageForPlaceholder($upsert->upsert_default[$i], $this->data); } /* * $$$ hugh - permit the use of expressions, by putting the value in parens, with option use * of double :: to provide a default for new row (rowid is empty). This default is seperate from * the simple default used above, which is predicated on value being empty. So simple usage * might be .. * * (counter+1::0) * * ... if you want to increment a 'counter' field. Or you might use a subquery, like ... * * ((SELECT foo FROM other_table WHERE fk_id = {rowid})::'foo default') */ if (!preg_match('#^\\((.*)\\)$#', $v)) { $v = $upsertDb->q($v); } else { $matches = array(); preg_match('#^\\((.*)\\)$#', $v, $matches); $v = $matches[1]; $v = explode('::', $v); if (count($v) == 1) { $v = $v[0]; } else { if ($formModel->isNewRecord()) { $v = $v[1]; } else { $v = $v[0]; } } } $fields[] = $k . ' = ' . $v; } return $fields; }
public function doEmail($tableModel) { $app =& JFactory::getApplication(); jimport('joomla.mail.helper'); if (!$this->_upload()) { return false; } $tableModel->setId(JRequest::getInt('id', 0)); $w = new FabrikWorker(); $config =& JFactory::getConfig(); $this->_type = 'table'; $params =& $tableModel->getParams(); $to = JRequest::getVar('email_to'); $renderOrder = JRequest::getInt('renderOrder'); $merge_emails = $params->get('emailtable_mergemessages', 0); if (is_array($merge_emails)) { $merge_emails = (int) JArrayHelper::getValue($merge_emails, $renderOrder, 0); } $toHow = $params->get('emailtable_to_how', 'single'); if (is_array($toHow)) { $toHow = JArrayHelper::getValue($toHow, $renderOrder, 'single'); } $toType = $params->get('emailtable_to_type', 'list'); if (is_array($toType)) { $toType = JArrayHelper::getValue($toType, $renderOrder, 'list'); } if ($toType == 'list') { $to = str_replace('.', '___', $to); } else { if (is_array($to)) { // $$$ hugh - if using a table selection type, allow specifying a default in // the "emailtable_to" field. if ($toType != 'field') { $emailtable_to = $params->get('emailtable_to', ''); if (is_array($emailtable_to)) { $emailtable_to = JArrayHelper::getValue($emailtable_to, $renderOrder, ''); } if (!empty($emailtable_to)) { if (!in_array($emailtable_to, $to)) { $to[] = $emailtable_to; } } } $to = implode(',', $to); } } $fromUser = $params->get('emailtable_from_user'); if (is_array($fromUser)) { $fromUser = JArrayHelper::getValue($fromUser, $renderOrder, ''); } $emailTemplate = $params->get('emailtable_template', ''); if (is_array($emailTemplate)) { $emailTemplate = JArrayHelper::getValue($emailTemplate, $renderOrder, ''); } if (!empty($emailTemplate)) { $emailTemplate = JPath::clean(JPATH_SITE . DS . 'components' . DS . 'com_fabrik' . DS . 'plugins' . DS . 'table' . DS . 'emailtable' . DS . 'tmpl' . DS . $emailTemplate); } $contentTemplate = $params->get('emailtable_template_content', ''); if (is_array($contentTemplate)) { $contentTemplate = JArrayHelper::getValue($contentTemplate, $renderOrder, ''); } if ($contentTemplate != '') { $content = $this->_getConentTemplate($contentTemplate); } else { $content = ''; } $php_msg = false; if (JFile::exists($emailTemplate)) { if (JFile::getExt($emailTemplate) == 'php') { // $message = $this->_getPHPTemplateEmail($emailTemplate); $message = ''; $php_msg = true; } else { $message = $this->_getTemplateEmail($emailTemplate); } $message = str_replace('{content}', $content, $message); } else { if ($contentTemplate != '') { $message = $content; } else { $message = ''; } } $subject = JRequest::getVar('subject'); $cover_message = JRequest::getVar('message', '', 'post', 'string', 4); $old_style = false; if (empty($message) && !$php_msg) { $old_style = true; //$message = $cover_message; } $recordids = explode(',', JRequest::getVar('recordids')); $data = $this->getRecords('recordids', true); if ($fromUser) { $my =& JFactory::getUser(); $email_from = $my->get('email'); // $$$ rob - erm $ ema isn't used anywhere - do we need it????? $fromname = $my->get('name'); } else { $config =& JFactory::getConfig(); $email_from = $config->getValue('mailfrom'); $fromname = $config->getValue('fromname'); } $cc = null; $bcc = null; $sent = 0; $notsent = 0; $updated = array(); $merged_msg = ''; $first_row = array(); foreach ($data as $group) { foreach ($group as $row) { if ($merge_emails) { if (empty($first_row)) { $first_row = $row; // used for placeholders in subject when merging mail } $thismsg = ''; if ($old_style) { $thismsg = $w->parseMessageForPlaceHolder($cover_message, $row); } else { if ($php_msg) { $thismsg = $this->_getPHPTemplateEmail($emailTemplate, $row, $tableModel); } else { $thismsg = $w->parseMessageForPlaceHolder($message, $row); } } $merged_msg .= $thismsg; $updated[] = $row->__pk_val; } else { if ($toType == 'list') { $process = isset($row->{$to}); $mailto = $row->{$to}; } else { $process = true; $mailto = $to; } if ($process) { $res = false; $mailtos = explode(',', $mailto); if ($toHow == 'single') { foreach ($mailtos as $tokey => $thisto) { $thisto = $w->parseMessageForPlaceholder($thisto, $row); if (!JMailHelper::isEmailAddress($thisto)) { unset($mailtos[$tokey]); $notsent++; } else { $mailtos[$tokey] = $thisto; } } if ($notsent > 0) { $mailtos = array_values($mailtos); } $sent = sizeof($mailtos); if ($sent > 0) { $thissubject = $w->parseMessageForPlaceholder($subject, $row); $thismsg = ''; $thismsg = $cover_message; if (!$old_style) { if ($php_msg) { $thismsg .= $this->_getPHPTemplateEmail($emailTemplate, $row, $tableModel); } else { $thismsg .= $message; } } $thismsg = $w->parseMessageForPlaceholder($thismsg, $row); $res = JUtility::sendMail($email_from, $fromname, $mailtos, $thissubject, $thismsg, 1, $cc, $bcc, $this->filepath); } } else { foreach ($mailtos as $mailto) { $mailto = $w->parseMessageForPlaceholder($mailto, $row); if (JMailHelper::isEmailAddress($mailto)) { $thissubject = $w->parseMessageForPlaceholder($subject, $row); $thismsg = ''; $thismsg = $cover_message; if (!$old_style) { if ($php_msg) { $thismsg .= $this->_getPHPTemplateEmail($emailTemplate, $row, $tableModel); } else { $thismsg .= $message; } } $thismsg = $w->parseMessageForPlaceholder($thismsg, $row); $res = JUtility::sendMail($email_from, $fromname, $mailto, $thissubject, $thismsg, 1, $cc, $bcc, $this->filepath); if ($res) { $sent++; } else { $notsent++; } } else { $notsent++; } } } if ($res) { $updated[] = $row->__pk_val; } } else { $notsent++; } } } } if ($merge_emails) { // arbitrarily use first row for placeholders if ($toType == 'list') { $mailto = $first_row->{$to}; } else { $mailto = $to; } $thistos = explode(',', $w->parseMessageForPlaceHolder($mailto, $first_row)); $thissubject = $w->parseMessageForPlaceHolder($subject, $first_row); $preamble = $params->get('emailtable_message_preamble', ''); $preamble = is_array($preamble) ? JArrayHelper::getValue($preamble, $renderOrder, '') : $preamble; $postamble = $params->get('emailtable_message_postamble', ''); $postamble = is_array($postamble) ? JArrayHelper::getValue($postamble, $renderOrder, '') : $postamble; $merged_msg = $preamble . $merged_msg . $postamble; if (!$old_style) { $merged_msg = $cover_message . $merged_msg; } if ($toHow == 'single') { foreach ($thistos as $tokey => $thisto) { $thisto = $w->parseMessageForPlaceholder($thisto, $first_row); if (!JMailHelper::isEmailAddress($thisto)) { unset($thistos[$tokey]); $notsent++; } else { $mailtos[$tokey] = $thisto; } } if ($notsent > 0) { $thistos = array_values($thistos); } $sent = sizeof($thistos); if ($sent > 0) { $res = JUTility::sendMail($email_from, $fromname, $thistos, $thissubject, $merged_msg, true, $cc, $bcc, $this->filepath); } } else { foreach ($thistos as $thisto) { if (JMailHelper::isEmailAddress($thisto)) { $res = JUTility::sendMail($email_from, $fromname, $thisto, $thissubject, $merged_msg, true, $cc, $bcc, $this->filepath); if ($res) { $sent++; } else { $notsent++; } } else { $notsent++; } } } } $updateField = $params->get('emailtable_update_field'); $updateField = is_array($updateField) ? JArrayHelper::getValue($updateField, $renderOrder, '') : $updateField; if (!empty($updateField) && !empty($updated)) { $updateVal = $params->get('emailtable_update_value'); $updateVal = is_array($updateVal) ? JArrayHelper::getValue($updateVal, $renderOrder, '') : $updateVal; $tableModel->updateRows($updated, $updateField, $updateVal); } // $$$ hugh - added second update field for Bea $updateField = $params->get('emailtable_update_field2'); $updateField = is_array($updateField) ? JArrayHelper::getValue($updateField, $renderOrder, '') : $updateField; if (!empty($updateField) && !empty($updated)) { $updateVal = $params->get('emailtable_update_value2'); $updateVal = is_array($updateVal) ? JArrayHelper::getValue($updateVal, $renderOrder, '') : $updateVal; $tableModel->updateRows($updated, $updateField, $updateVal); } $app->enqueueMessage(JText::sprintf('%s emails sent', $sent)); if ($notsent != 0) { JError::raiseWarning(E_NOTICE, JText::sprintf('%s emails not sent', $notsent)); } }
private function _render($watch, $data = array(), $format = 'table', $repeatCounter = 0) { // http://www.google.com/ig/api?weather=,,,34739300,-86624100 $id = $this->getHTMLId($repeatCounter); $params =& $this->getParams(); $watch_type = $params->get('fabrikweather_watch_type', 'map'); $temp_scale = $params->get('fabrikweather_temp_scale', 'f'); $w = new FabrikWorker(); $city = $params->get('fabrikweather_city', ''); $city = $w->parseMessageForPlaceholder($city, $data); $language = $params->get('fabrikweather_language', 'en'); $is_night = false; if ($watch_type == 'map') { $o = $this->_strToCoords($watch); $lat = (double) trim($o->coords[0]); $glat = sprintf("%8d", $lat * 1000000); $lon = (double) trim($o->coords[1]); $glon = sprintf("%8d", $lon * 1000000); $weather = "{$glat},{$glon}"; $is_night = $this->_isNight($lat, $lon); } else { $weather = $city; } $custom_slug = $params->get('fabrikweather_class_prefix', 'fabrikweather'); if (!empty($custom_slug) && JFile::exists(COM_FABRIK_FRONTEND . DS . 'components/com_fabrik/plugins/element/fabrikweather/assets/' . $custom_slug . '/weather.css')) { FabrikHelperHTML::stylesheet('weather.css', 'components/com_fabrik/plugins/element/fabrikweather/assets/' . $custom_slug . '/'); } else { FabrikHelperHTML::stylesheet('weather.css', 'components/com_fabrik/plugins/element/fabrikweather/assets/fabrikweather/'); } if (!empty($custom_slug) && JFile::exists(COM_FABRIK_FRONTEND . DS . 'plugins/element/fabrikweather/assets/' . $custom_slug . '/render.php')) { require_once COM_FABRIK_FRONTEND . DS . 'plugins/element/fabrikweather/assets/' . $custom_slug . '/render.php'; } else { require_once COM_FABRIK_FRONTEND . DS . 'plugins/element/fabrikweather/assets/fabrikweather/render.php'; } $render = new fabrikWeatherRender(); $render->setIsNight($is_night); $render->setTempScale($temp_scale); if (!empty($custom_slug) && JFolder::exists(COM_FABRIK_FRONTEND . DS . 'plugins/element/fabrikweather/assets/' . $custom_slug . '/icons')) { $render->setIconPath('plugins/element/fabrikweather/assets/' . $custom_slug . '/icons'); } else { $render->setIconPath('plugins/element/fabrikweather/assets/fabrikweather/icons'); } if (!$render->getWeatherXml($weather, $watch_type, $language)) { return JText::_(PLG_ELEMENT_FABRIKWEATHER_NO_GOOGLE_DATA); } if ($format == 'table') { $html = $render->getTableHtml($id, $city); } else { $html = $render->getFormHtml($id, $city); } return $html; }
public function doEmail() { $listModel = $this->listModel; $app = JFactory::getApplication(); jimport('joomla.mail.helper'); if (!$this->_upload()) { return false; } $listModel->setId(JRequest::getInt('id', 0)); $w = new FabrikWorker(); $config = JFactory::getConfig(); $params = $this->getParams(); $to = JRequest::getVar('order_by'); $renderOrder = JRequest::getInt('renderOrder'); $toType = $params->get('emailtable_to_type', 'list'); $fromUser = $params->get('emailtable_from_user'); if ($toType == 'list') { $to = str_replace('.', '___', $to); } $subject = JRequest::getVar('subject'); $message = JRequest::getVar('message', '', 'post', 'string', 4); $data = $this->getRecords('recordids', true); if ($fromUser) { $my = JFactory::getUser(); $from = $my->get('email'); $fromname = $my->get('name'); } else { $from = $config->getValue('mailfrom'); $fromname = $config->getValue('fromname'); } $email_from = $config->getValue('mailfrom'); $cc = null; $bcc = null; $sent = 0; $notsent = 0; $updated = array(); foreach ($data as $group) { foreach ($group as $row) { if ($toType == 'list') { $process = isset($row->{$to}); $mailto = $row->{$to}; } else { $process = true; $mailto = $to; } if ($process) { $mailtos = explode(',', $mailto); foreach ($mailtos as $mailto) { $mailto = $w->parseMessageForPlaceholder($mailto, $row); if (JMailHelper::isEmailAddress($mailto)) { $thissubject = $w->parseMessageForPlaceholder($subject, $row); $thismessage = $w->parseMessageForPlaceholder($message, $row); $res = JUtility::sendMail($email_from, $email_from, $mailto, $thissubject, $thismessage, 1, $cc, $bcc, $this->filepath); if ($res) { $sent++; } else { $notsent++; } } else { $notsent++; } } if ($res) { $updated[] = $row->__pk_val; } } else { $notsent++; } } } if (!empty($updated)) { $updateField = $params->get('emailtable_update_field'); $updateVal = $params->get('emailtable_update_value'); $listModel->updateRows($updated, $updateField, $updateVal); } $app->enqueueMessage(JText::sprintf('PLG_LIST_EMAIL_N_SENT', $sent)); if ($notsent != 0) { JError::raiseWarning(E_NOTICE, JText::sprintf('PLG_LIST_EMAIL_N_NOT_SENT', $notsent)); } }
function downloadEmail(&$row, $filepath) { $params = $this->getParams(); $email_to = $params->get('fu_download_email', ''); if (!empty($email_to)) { JError::setErrorHandling(E_ALL, 'ignore'); jimport('joomla.mail.helper'); $w = new FabrikWorker(); $email_to = $w->parseMessageForPlaceholder($email_to, JArrayHelper::fromObject($row), false); $config = JFactory::getConfig(); $from = $config->getValue('mailfrom'); $fromname = $config->getValue('fromname'); $msg = JText::_('PLG_ELEMENT_FILEUPLOAD_DOWNLOAD_EMAIL_MSG') . "<br />\n"; $msg .= JText::_('PLG_ELEMENT_FILEUPLOAD_FILENAME') . ': ' . $filepath . "<br />\n"; $user = JFactory::getUser(); $msg .= JText::_('PLG_ELEMENT_FILEUPLOAD_BY') . ': ' . ($user->get('id') == 0 ? 'guest' : $user->get('username')) . "<br />\n"; $msg .= JText::_('PLG_ELEMENT_FILEUPLOAD_FROM') . ': ' . JRequest::getVar('REMOTE_ADDR', '', 'server') . "<br />\n"; $msg .= JText::_('PLG_ELEMENT_FILEUPLOAD_ON') . ': ' . date(DATE_RFC822) . "<br />\n"; $subject = JText::_('PLG_ELEMENT_FILEUPLOAD_DOWNLOAD_EMAIL_SUBJECT') . ' :: ' . $config->getValue('sitename'); foreach (explode(',', $email_to) as $to) { $res = JUtility::sendMail($from, $fromname, $to, $subject, $msg, true); } } }
function doemail() { jimport('joomla.mail.helper'); jimport('joomla.filesystem.file'); jimport('joomla.client.helper'); global $mainframe; JClientHelper::setCredentialsFromRequest('ftp'); $config =& JFactory::getConfig(); $folder = ''; $filepaths = array(); $attached = 0; $notattached = 0; foreach (JRequest::get('FILES') as $elname => $file) { if ($file['name'] != '') { if ($folder == '') { $folder = $config->getValue('config.tmp_path') . DS . uniqid('com_fabrik.plg.table.emailtableplus.'); if (!JFolder::create($folder)) { JError::raiseWarning(E_NOTICE, JText::_('Could not upload files')); break; } } $filepath = $folder . DS . JFile::makeSafe($file['name']); if (JFile::upload($file['tmp_name'], $filepath)) { $filepaths[count($filepaths)] = $filepath; $attached++; } else { JError::raiseWarning(E_NOTICE, JText::sprintf('Could not upload file %s', $file['name'])); } } } $renderOrder = JRequest::getInt('renderOrder', 0); $subject = JMailHelper::cleanSubject(JRequest::getVar('subject')); $message = JMailHelper::cleanBody(JRequest::getVar('message')); $recordids = explode(',', JRequest::getVar('recordids')); $tableModel =& $this->getModel('Table'); $tableModel->setId(JRequest::getVar('id', 0)); $formModel =& $tableModel->getForm(); $this->formModel =& $formModel; $params =& $tableModel->getParams(); $elementModel =& JModel::getInstance('element', 'FabrikModel'); $field_name = $params->get('emailtableplus_field_name'); if (is_array($field_name)) { $field_name = $field_name[$renderOrder]; } $elementModel->setId($field_name); $element =& $elementModel->getElement(true); $tonamefield = $elementModel->getFullName(false, true, false); $field_email = $params->get('emailtableplus_field_email'); if (is_array($field_email)) { $field_email = $field_email[$renderOrder]; } $elementModel->setId($field_email); $element =& $elementModel->getElement(true); $tofield = $elementModel->getFullName(false, true, false); $fromUser = $params->get('emailtableplus_from_user'); if (is_array($fromUser)) { $fromUser = $fromUser[$renderOrder]; } if ($fromUser[0]) { $my =& JFactory::getUser(); $from = $my->get('email'); $fromname = $my->get('name'); } else { $config =& JFactory::getConfig(); $from = $config->getValue('mailfrom'); $fromname = $config->getValue('fromname'); } $ubcc = $params->get('emailtableplus_use_BCC'); if (is_array($ubcc)) { $ubcc = $ubcc[$renderOrder]; } $useBCC = $ubcc && count($recordids) > 0 && !preg_match('/{[^}]*}/', $subject) && !preg_match('/{[^}]*}/', $message); /* $include_rowdata = $params->get('emailtableplus_include_rowdata'); if (is_array($include_rowdata)) { $include_rowdata = $include_rowdata[$renderOrder]; } */ $sent = 0; $notsent = 0; if ($useBCC) { $bcc = array(); foreach ($recordids as $id) { $row = $tableModel->getRow($id); //$message .= $this->_getTextEmail( JArrayHelper::fromObject($row)); $to = $row->{$tofield}; $toname = $row->{$tonamefield}; if (JMailHelper::cleanAddress($to) && JMailHelper::isEmailAddress($to)) { $tofull = '"' . JMailHelper::cleanLine($toname) . '" <' . $to . '>'; $bcc[$sent] = $tofull; $sent++; } else { $notsent++; } } // $$$ hugh - working round bug in the SMTP mailer method: // http://forum.joomla.org/viewtopic.php?f=199&t=530189&p=2190233#p2190233 // ... which basically means if using the SMTP method, we MUST specify a To addrees, // so if mailer is smtp, we'll set the To address to the same as From address if ($config->getValue('mailer') == 'smtp') { $res = JUtility::sendMail($from, $fromname, $from, $subject, $message, 0, null, $bcc, $filepaths); } else { $res = JUtility::sendMail($from, $fromname, null, $subject, $message, 0, null, $bcc, $filepaths); } if (!$res) { $notsent += $sent; $sent = 0; } } else { $w = new FabrikWorker(); foreach ($recordids as $id) { $row = $tableModel->getRow($id); $to = $row->{$tofield}; $toname = $row->{$tonamefield}; if (JMailHelper::cleanAddress($to) && JMailHelper::isEmailAddress($to)) { $tofull = '"' . JMailHelper::cleanLine($toname) . '" <' . $to . '>'; $thissubject = $w->parseMessageForPlaceholder($subject, $row); $thismessage = $w->parseMessageForPlaceholder($message, $row); $res = JUtility::sendMail($from, $fromname, $tofull, $thissubject, $thismessage, 0, null, null, $filepaths); if ($res) { $sent++; } else { $notsent++; } } else { $notsent++; } } } if ($folder != '') { JFolder::delete($folder); } if ($attached > 0) { $mainframe->enqueueMessage(JText::sprintf('%s files attached', $attached)); } $mainframe->enqueueMessage(JText::sprintf('%s emails sent', $sent)); if ($notsent != 0) { JError::raiseWarning(E_NOTICE, JText::sprintf('%s emails not sent', $notsent)); } }
/** * Process the plugin, called when form is submitted * * @return bool */ public function onAfterProcess() { $params = $this->getParams(); jimport('joomla.mail.helper'); $formModel = $this->getModel(); $input = $this->app->input; $ftpTemplate = JPath::clean(JPATH_SITE . '/plugins/fabrik_form/ftp/tmpl/' . $params->get('ftp_template', '')); $this->data = $this->getProcessData(); if (!$this->shouldProcess('ftp_conditon', null, $params)) { return; } $contentTemplate = $params->get('ftp_template_content'); $content = $contentTemplate != '' ? $this->_getContentTemplate($contentTemplate) : ''; if (JFile::exists($ftpTemplate)) { if (JFile::getExt($ftpTemplate) == 'php') { $message = $this->_getPHPTemplateFtp($ftpTemplate); if ($message === false) { return; } } else { $message = $this->_getTemplateFtp($ftpTemplate); } $message = str_replace('{content}', $content, $message); } else { $message = $contentTemplate != '' ? $content : $this->_getTextFtp(); } $cc = null; $bcc = null; $w = new FabrikWorker(); // $$$ hugh - test stripslashes(), should be safe enough. $message = stripslashes($message); $editURL = COM_FABRIK_LIVESITE . "index.php?option=com_fabrik&view=form&fabrik=" . $formModel->get('id') . "&rowid=" . $input->get('rowid', '', 'string'); $viewURL = COM_FABRIK_LIVESITE . "index.php?option=com_fabrik&view=details&fabrik=" . $formModel->get('id') . "&rowid=" . $input->get('rowid', '', 'string'); $editLink = "<a href=\"{$editURL}\">" . FText::_('EDIT') . "</a>"; $viewLink = "<a href=\"{$viewURL}\">" . FText::_('VIEW') . "</a>"; $message = str_replace('{fabrik_editlink}', $editLink, $message); $message = str_replace('{fabrik_viewlink}', $viewLink, $message); $message = str_replace('{fabrik_editurl}', $editURL, $message); $message = str_replace('{fabrik_viewurl}', $viewURL, $message); $ftpFileName = $params->get('ftp_filename', ''); $ftpFileName = $w->parseMessageForPlaceholder($ftpFileName, $this->data, false); $ftpEvalFileName = (int) $params->get('ftp_eval_filename', '0'); if ($ftpEvalFileName) { $ftpFileName = @eval($ftpFileName); FabrikWorker::logEval($ftpEvalFileName, 'Caught exception on eval in ftp filename eval : %s'); } if (empty($ftpFileName)) { $ftpFileName = 'fabrik_ftp_' . md5(uniqid()) . '.txt'; } $ftpHost = $w->parseMessageForPlaceholder($params->get('ftp_host', ''), $this->data, false); $ftpPort = $w->parseMessageForPlaceholder($params->get('ftp_port', '21'), $this->data, false); $ftpChDir = $w->parseMessageForPlaceholder($params->get('ftp_chdir', ''), $this->data, false); $ftpUser = $w->parseMessageForPlaceholder($params->get('ftp_user', ''), $this->data, false); $ftpPassword = $w->parseMessageForPlaceholder($params->get('ftp_password', ''), $this->data, false); $tmpDir = rtrim($this->config->getValue('config.tmp_path'), '/'); if (empty($tmpDir) || !JFolder::exists($tmpDir)) { throw new RuntimeException('PLG_FORM_FTP_NO_JOOMLA_TEMP_DIR', 500); } $tmpFile = $tmpDir . '/fabrik_ftp_' . md5(uniqid()); $message = $w->parseMessageForPlaceholder($message, $this->data, true, false); if (JFile::write($tmpFile, $message)) { $conn_id = ftp_connect($ftpHost, $ftpPort); if ($conn_id) { if (@ftp_login($conn_id, $ftpUser, $ftpPassword)) { if (!empty($ftpChDir)) { if (!ftp_chdir($conn_id, $ftpChDir)) { $this->app->enqueueMessage(FText::_('PLG_FORM_FTP_COULD_NOT_CHDIR'), 'notice'); JFile::delete($tmpFile); return false; } } if (!ftp_put($conn_id, $ftpFileName, $tmpFile, FTP_ASCII)) { $this->app->enqueueMessage(FText::_('PLG_FORM_FTP_COULD_NOT_SEND_FILE'), 'notice'); JFile::delete($tmpFile); return false; } } else { $this->app->enqueueMessage(FText::_('PLG_FORM_FTP_COULD_NOT_LOGIN'), 'notice'); JFile::delete($tmpFile); return false; } } else { throw new RuntimeException('PLG_FORM_FTP_COULD_NOT_CONNECT', 500); JFile::delete($tmpFile); return false; } } else { throw new RuntimeException('PLG_FORM_FTP_COULD_NOT_WRITE_TEMP_FILE', 500); JFile::delete($tmpFile); return false; } JFile::delete($tmpFile); return true; }
/** * add attachments to the email */ function addAttachments($params) { //get attachments $pluginManager = FabrikWorker::getPluginManager(); $data = $this->getEmailData(); $groups = $this->formModel->getGroupsHiarachy(); foreach ($groups as $groupModel) { $elementModels = $groupModel->getPublishedElements(); foreach ($elementModels as $elementModel) { $elName = $elementModel->getFullName(false, true, false); if (array_key_exists($elName, $this->data)) { if (method_exists($elementModel, 'addEmailAttachement')) { if (array_key_exists($elName . '_raw', $data)) { $val = $data[$elName . '_raw']; } else { $val = $data[$elName]; } if (is_array($val)) { $val = implode(',', $val); } $aVals = FabrikWorker::JSONtoData($val, true); foreach ($aVals as $v) { $file = $elementModel->addEmailAttachement($v); if ($file !== false) { $this->_aAttachments[] = $file; } } } } } } // $$$ hugh - added an optional eval for adding attachments. // Eval'ed code should just return an array of file paths which we merge with $this->_aAttachments[] $w = new FabrikWorker(); $email_attach_eval = $w->parseMessageForPlaceholder($params->get('email_attach_eval', ''), $this->data, false); if (!empty($email_attach_eval)) { $email_attach_array = @eval($email_attach_eval); FabrikWorker::logEval($email_attach_array, 'Caught exception on eval in email email_attach_eval : %s'); if (!empty($email_attach_array)) { $this->_aAttachments = array_merge($this->_aAttachments, $email_attach_array); } } }
/** * Create the article content * * @return string */ protected function buildContent() { $images = $this->images(); $formModel = $this->getModel(); $input = $this->app->input; $params = $this->getParams(); $template = JPath::clean(JPATH_SITE . '/plugins/fabrik_form/article/tmpl/' . $params->get('template', '')); $contentTemplate = $params->get('template_content'); $content = $contentTemplate != '' ? $this->_getContentTemplate($contentTemplate) : ''; $messageTemplate = ''; if (JFile::exists($template)) { $messageTemplate = JFile::getExt($template) == 'php' ? $this->_getPHPTemplateEmail($template) : $this->_getTemplateEmail($template); if ($content !== '') { $messageTemplate = str_replace('{content}', $messageTemplate, $content); } } $message = ''; if (!empty($messageTemplate)) { $message = $messageTemplate; } elseif (!empty($content)) { // Joomla article template: $message = $content; } $message = stripslashes($message); $editURL = COM_FABRIK_LIVESITE . 'index.php?option=com_' . $this->package . '&view=form&formid=' . $formModel->get('id') . '&rowid=' . $input->get('rowid', '', 'string'); $viewURL = COM_FABRIK_LIVESITE . 'index.php?option=com_' . $this->package . '&view=details&formid=' . $formModel->get('id') . '&rowid=' . $input->get('rowid', '', 'string'); $editLink = '<a href="' . $editURL . '">' . FText::_('EDIT') . '</a>'; $viewLink = '<a href="' . $viewURL . '">' . FText::_('VIEW') . '</a>'; $message = str_replace('{fabrik_editlink}', $editLink, $message); $message = str_replace('{fabrik_viewlink}', $viewLink, $message); $message = str_replace('{fabrik_editurl}', $editURL, $message); $message = str_replace('{fabrik_viewurl}', $viewURL, $message); foreach ($images as $key => $val) { $this->data[$key] = $val; } $w = new FabrikWorker(); $output = $w->parseMessageForPlaceholder($message, $this->data, true); return $output; }