/** * Updates a XML representation of a Product * * @access public * @param mixed $product * @return mixed */ public function update($product) { $root = 'Article'; $productNode = array(); $productNode['Description'] = $product->get_title(); $productNode['ArticleNumber'] = $product->get_sku(); $productNode['StockGoods'] = true; $productNode['QuantityInStock'] = $product->managing_stock() ? $product->get_stock_quantity() : 0; $productNode['Unit'] = 'st'; $options = get_option('woocommerce_fortnox_advanced_accounting_settings'); $tax_class = $this->get_tax_class_by_tax_name($product->get_tax_class()); logthis($tax_class); if (!empty($options['product_eu_sales_account'])) { $productNode['EUAccount'] = $options['product_eu_sales_account']; } if (!empty($options['product_eu_sales_vat_account'])) { $productNode['EUVATAccount'] = $options['product_eu_sales_vat_account']; } if (!empty($options['product_export_sales_account'])) { $productNode['ExportAccount'] = $options['product_export_sales_account']; } logthis('R: ' . $options['product_sales_account_' . $tax_class]); if (!empty($options['product_sales_account_' . $tax_class])) { $productNode['SalesAccount'] = $options['product_sales_account_' . $tax_class]; } if (!empty($options['product_purchase_account'])) { $productNode['PurchaseAccount'] = $options['product_purchase_account']; } return $this->generate($root, $productNode); }
/** * Content generator - creates table-formed report * */ function contentGenerator($template) { // append userapi scripts and CSS if (is_dir('userapi/js/')) { $user_js_files = scandir('userapi/js/'); foreach ($user_js_files as $user_js_file) { if (pathinfo($user_js_file, PATHINFO_EXTENSION) == 'js') { add_JS('userapi/js/' . $user_js_file); logthis('userAPI script added: ' . $user_js_file); } } } if (is_dir('userapi/css/')) { $user_css_files = scandir('userapi/css/'); foreach ($user_css_files as $user_css_file) { if (pathinfo($user_css_file, PATHINFO_EXTENSION) == 'css') { add_CSS('userapi/css/' . $user_css_file); logthis('userAPI CSS added: ' . $user_css_file); } } } // replace all templates to generated content while (preg_match(macro_regexp('db'), $template, $match) > 0) { // parse template parameters into array $params = parse_plugin_template($match[0]); // generate HTML if (!isset($params['id'])) { $table_html = '<b>[JuliaCMS][db] error:</b> no ID specified for the table'; } else { // all API/UI require "report_id" parameter $params['report_id'] = $params['id']; $table_html = J_DB_UI::generateTable($params, $this->DB); } // replace $template = str_replace($match[0], $table_html, $template); } // yeah we are ready return $template; }
/** * Creates meta if order in Woo differences from Fortnox * * @access public * @return int */ public function get_synced_products() { global $wpdb; $rows = $wpdb->get_results("SELECT meta2.post_id, meta2.meta_value from wp_postmeta meta1\n JOIN wp_postmeta meta2 ON meta1.post_id = meta2.post_id WHERE meta1.meta_key = '_is_synced_to_fortnox' AND meta1.meta_value = '1' AND meta2.meta_key = '_sku'"); foreach ($rows as $key => $row) { logthis($row->meta_value); } }
/** * Creates a HttpRequest for an update of a product and appends the given XML to the request and sends it to Fortnox * * @access private * @param mixed $message * @return bool */ private function post_error($message) { if (!isset($this->api_key)) { return false; } $fields = array('api_key' => $this->api_key, 'message' => $message); $ch = curl_init(); $url = "http://plugapi.consuasor.se/api_post.php"; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_VERBOSE, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $data = curl_exec($ch); curl_close($ch); logthis($data); }
/** * To run query using the mysqli library * @subpackage Database Helper * @param string $sql SQL to execute * @param integer $ln Line number of the caller * @param boolean $die_on_error if the call should die on failure to execute the query * @return boolean */ function doqueryi($sql, $ln = 0, $die_on_error = 1) { global $mysqli; global $debugprinting; global $debug_dump; global $last_mysql_error; global $last_mysql_errno; if ($debugprinting) { echo "<!-- doqueryi ({$sql}) -->\n"; } $debug_dump .= "<font class=query>doquery({$sql}) /* line {$ln} */</font>\n"; $result = mysqli_query($mysqli, $sql); if ($last_mysql_errno = mysqli_errno($mysqli)) { $errstr = $last_mysql_error = mysqli_error($mysqli); $e_out = "<font color=red>{$errstr}</font> at line {$ln} (" . session_id() . ")<br/>"; $debug_dump .= $e_out; mysqli_rollback($mysqli); if ($debugprinting) { echo "<div class='sql_error'>" . $errstr . "</div>"; echo "<div class='sql'>{$sql}</div>"; echo "<pre class='backtrace'>"; debug_print_backtrace(); echo "</pre>"; } $errstr = quotemeta($errstr); logthis("v2-doquery-FAILED", $errstr); if ($die_on_error) { exit; } else { return false; } } return $result; }
function clean_customer_table_callback() { global $wpdb; // this is how you get access to the database include_once "class-fortnox3-database-interface.php"; logthis('clean_customer_table_callback'); check_ajax_referer('fortnox_woocommerce', 'security'); $databaseInterface = new WCF_Database_Interface(); $customer_emails = $databaseInterface->clean_customer_table(); if ($customer_emails) { logthis($customer_emails); $message = 'Tabell rensad.'; if (is_array($customer_emails)) { $message .= 'För att undvika dubbletter, ta bort dessa kunder i er Fortnox: '; foreach ($customer_emails as $email) { logthis($email); $message .= $email->email . ', '; } $message = substr($message, 0, strlen($message) - 2); } echo json_encode(array('success' => true, 'message' => $message)); } else { echo json_encode(array('success' => false, 'message' => 'Tabell rensad.')); } die; // this is required to return a proper result }
/** * WooCommerce Fortnox General Settings * * @access public * @param void * @return void */ function register_woocommerce_advanced_accounting_settings() { $this->plugin_settings_tabs[$this->advanced_accounting_key] = 'Avancerade Bokföringsinställningar'; $pg = new WC_Payment_Gateways(); $payment_gateways = $pg->get_available_payment_gateways(); register_setting($this->advanced_accounting_key, $this->advanced_accounting_key); add_settings_section('section_general', 'Avancerade Bokföringsinställningar', array(&$this, 'section_freight_desc'), $this->advanced_accounting_key); foreach ($payment_gateways as $payment_gateway) { logthis($payment_gateway->enabled); //add_settings_field( 'woocommerce-fortnox-api-key', 'API Nyckel', array( &$this, 'field_hidden_option_text' ), $this->general_settings_key, 'section_general', array ( 'tab_key' => $this->general_settings_key, 'key' => 'api-key', 'desc' => '') ); if ($payment_gateway->enabled == 'yes') { add_settings_field('woocommerce-fortnox-advanced-accounting-' . $payment_gateway->id, $payment_gateway->title, array(&$this, 'field_option_text'), $this->advanced_accounting_key, 'section_general', array('tab_key' => $this->advanced_accounting_key, 'key' => $payment_gateway->id, 'desc' => '')); } } add_settings_field('woocommerce-fortnox-product-sales-account-25', 'Bokföringskonto försäljning 25% Moms', array(&$this, 'field_option_text'), $this->advanced_accounting_key, 'section_general', array('tab_key' => $this->advanced_accounting_key, 'key' => 'product_sales_account_25', 'desc' => '')); add_settings_field('woocommerce-fortnox-product-sales-account-12', 'Bokföringskonto försäljning 12% Moms', array(&$this, 'field_option_text'), $this->advanced_accounting_key, 'section_general', array('tab_key' => $this->advanced_accounting_key, 'key' => 'product_sales_account_12', 'desc' => '')); add_settings_field('woocommerce-fortnox-product-sales-account-6', 'Bokföringskonto försäljning 6% Moms', array(&$this, 'field_option_text'), $this->advanced_accounting_key, 'section_general', array('tab_key' => $this->advanced_accounting_key, 'key' => 'product_sales_account_6', 'desc' => '')); add_settings_field('woocommerce-fortnox-product-eu-sales-account', 'Bokföringskonto försäljning EU', array(&$this, 'field_option_text'), $this->advanced_accounting_key, 'section_general', array('tab_key' => $this->advanced_accounting_key, 'key' => 'product_eu_sales_account', 'desc' => '')); add_settings_field('woocommerce-fortnox-product-eu-sales-vat-account', 'Bokföringskonto Moms EU', array(&$this, 'field_option_text'), $this->advanced_accounting_key, 'section_general', array('tab_key' => $this->advanced_accounting_key, 'key' => 'product_eu_sales_vat_account', 'desc' => '')); add_settings_field('woocommerce-fortnox-product-export-sales-account', 'Bokföringskonto försäljning export', array(&$this, 'field_option_text'), $this->advanced_accounting_key, 'section_general', array('tab_key' => $this->advanced_accounting_key, 'key' => 'product_export_sales_account', 'desc' => '')); add_settings_field('woocommerce-fortnox-product-purchase-account', 'Bokföringskonto inköp', array(&$this, 'field_option_text'), $this->advanced_accounting_key, 'section_general', array('tab_key' => $this->advanced_accounting_key, 'key' => 'product_purchase_account', 'desc' => '')); }
function buildPostsInTagsTable($exclude = '', $hide_ping_and_track) { global $utw_is_present; if ($utw_is_present) { global $wpdb, $tabletags, $tablepost2tag; if (1 == $hide_ping_and_track) { $ping = "AND comment_type NOT LIKE '%pingback%' AND comment_type NOT LIKE '%trackback%'"; } else { $ping = ''; } if (!empty($exclude)) { $excats = preg_split('/[\\s,]+/', $exclude); if (count($excats)) { foreach ($excats as $excat) { $exclusions .= ' AND p2c.category_id <> ' . intval($excat) . ' '; } } } $now = current_time('mysql', 1); foreach ($this->tagsTable as $tag) { $posts_in_tags[$tags[0]] = array(); $query = "SELECT p2t.post_id\r\n\t\t\t\t\tFROM {$tablepost2tag} p2t \r\n\t\t\t\t\tINNER JOIN {$wpdb->post2cat} p2c ON p2t.post_id = p2c.post_ID\r\n\t\t\t\t\tWHERE p2t.tag_id = {$tag['0']} \r\n\t\t\t\t\t{$exclusions}"; logthis("SQL Query :" . $query, __FUNCTION__, __LINE__); $posts_in_tag_results = $wpdb->get_results($query); if ($posts_in_tag_results) { $posts_in_tag_results = array_reverse($posts_in_tag_results); foreach ($posts_in_tag_results as $posts_in_tag_result) { $query = "SELECT ID, post_title, post_date as `day`, comment_status \r\n\t\t\t\t\t\t\tFROM {$wpdb->posts} \r\n\t\t\t\t\t\t\tWHERE ID = {$posts_in_tag_result->post_id} \r\n\t\t\t\t\t\t\tAND post_status = 'publish' \r\n\t\t\t\t\t\t\tAND post_date_gmt <= '{$now}'\r\n\t\t\t\t\t\t\tORDER By post_date"; logthis("SQL Query :" . $query, __FUNCTION__, __LINE__); $post_results = $wpdb->get_results($query); if ($post_results) { foreach ($post_results as $post_result) { $query = "SELECT COUNT(comment_ID) \r\n\t\t\t\t\t\t\t\t\tFROM {$wpdb->comments} \r\n\t\t\t\t\t\t\t\t\tWHERE comment_post_ID = {$post_result->ID} \r\n\t\t\t\t\t\t\t\t\tAND comment_approved = '1' \r\n\t\t\t\t\t\t\t\t\t{$ping}"; logthis("SQL Query :" . $query, __FUNCTION__, __LINE__); $num_comments = $wpdb->get_var($query); $this->postsInTagsTable[$tag[0]][$post_result->ID] = array($post_result->day, $post_result->post_title, get_permalink($post_result->ID), $num_comments, $post_result->comment_status); } } } if ($this->postsInTagsTable[$tag[0]]) { $this->cache->contentIs($this->postsInTagsTable[$tag[0]]); $this->cache->writeFile('tag-' . $tag[0] . '.dat'); } } } } }
function af_ela_set_config($config, $reset = false) { global $wpdb, $af_ela_cache_root, $utw_is_present; $settings = get_option('af_ela_options'); foreach ($config as $optionKey => $optionValue) { switch ($optionKey) { case 'newest_first': case 'num_entries': case 'num_entries_tagged': case 'num_comments': case 'fade': case 'hide_pingbacks_and_trackbacks': case 'use_default_style': case 'paged_posts': case 'truncate_title_at_space': case 'abbreviated_month': if ($optionValue != 0 && $optionValue != 1) { return -1; } break; case 'tag_soup_cut': case 'tag_soup_X': case 'truncate_title_length': case 'truncate_cat_length': case 'excluded_categories': case 'paged_post_num': //if(!is_numeric($optionValue)) return -2; break; case 'menu_order': $table = split(',', $optionValue); foreach ($table as $content) { if ($content != 'chrono' && $content != 'cats' && $content != 'tags' && !empty($content)) { return -3; } } break; default: break; } } $config['last_modified'] = gmdate("D, d M Y H:i:s", time()); if (!$reset) { $config = array_merge($settings, $config); } logthis($config); update_option('af_ela_options', $config, 'Set of Options for Extended Live Archive'); return true; }
/** * */ function requestParser($template) { // some speed improvement if (@$_POST['module'] != 'feedback' && @$_GET['module'] != 'feedback') { return $template; } $input_filter = array('action' => array('filter' => FILTER_VALIDATE_REGEXP, 'options' => array('regexp' => '~^[a-z_]+$~ui')), 'filename' => array('filter' => FILTER_VALIDATE_REGEXP, 'options' => array('regexp' => '~^[a-zA-Zа-яА-Я0-9][a-zA-Zа-яА-Я0-9_\\-\\s]*(\\.html|)$~ui')), 'filecontent' => array('filter' => FILTER_VALIDATE_REGEXP, 'options' => array('regexp' => '~^.*$~smui')), 'template' => array('filter' => FILTER_VALIDATE_REGEXP, 'options' => array('regexp' => REGEXP_IDENTIFIER)), 'module' => array('filter' => FILTER_VALIDATE_REGEXP, 'options' => array('regexp' => '~^feedback$~ui'))); $_INPUT = get_filtered_input($input_filter); // another check as both POST and GET may contain "module" parameter but with different values if ($_INPUT['module'] != 'feedback') { return $template; } switch ($_INPUT['action']) { case 'add_template': if (!user_allowed_to('manage feedback templates')) { return $template; } if ($this->templateAddEmpty($_INPUT['filename'])) { terminate('', 'Location: ./?module=feedback&action=manage', 302); } break; case 'delete_template': if (!user_allowed_to('manage feedback templates')) { return $template; } if ($this->templateDelete($_INPUT['filename'])) { terminate('', 'Location: ./?module=feedback&action=manage', 302); } break; case 'update_template': if (!user_allowed_to('manage feedback templates')) { return $template; } if ($this->templateUpdate($_INPUT['filename'], $_INPUT['filecontent'])) { terminate('', 'Location: ./?module=feedback&action=manage', 302); } break; case 'send': // TAG_TODO вынести это в отдельный метод (или вообще использовать lib/common/... // get the first of: message template, failure template, hardcoded failure message if (($text = @file_get_contents(__DIR__ . '/templates/' . $_INPUT['template'] . '.html')) == '') { logthis('[feedback] template "' . $_INPUT['template'] . '" specified, file not exists', ZLogger::LOG_LEVEL_ERROR); if (file_exists($filename_fail_message = __DIR__ . '/templates/_error_detected.html')) { $text = file_get_contents($filename_fail_message); } else { $text = 'error reading message template ("' . $_INPUT['template'] . '"), code FEEDBACK/001)' . PHP_EOL . PHP_EOL . 'POST details:' . PHP_EOL . '%POST%'; popup_message_add($_INPUT['template']); } terminate('', 'Location: ./service_feedback_failed', 302); } // replace templates foreach ($_POST as $index => $value) { $text = str_replace('%' . $index . '%', $this->prepareToInsert($value), $text); } // also add POST and referer (may be useful on error handling) $text = str_replace('%POST%', '<pre>' . $this->prepareToInsert(print_r($_POST, 1)) . '</pre>', $text); $text = str_replace('%REFERER%', '<pre>' . $this->prepareToInsert($_SERVER['HTTP_REFERER']) . '</pre>', $text); // remove unused templates (note on lazy regexp) $text = preg_replace('~%.*?%~', '', $text); // try to use template <title> as message subject if (preg_match('~<title>(.*?)</title>~smui', $text, $match)) { $subject = $match[1]; } else { $subject = $this->CONFIG['default_subject']; } // determine addressee - from config by index or first if not found $feedback_addresses = $this->CONFIG['addresses']; $recipient = isset($_POST['recipient']) && isset($feedback_addresses[$_POST['recipient']]) ? $feedback_addresses[$_POST['recipient']] : array_shift($feedback_addresses); // send message $this->mail_send(array('to' => $recipient, 'subject' => $subject, 'text' => $text), $this->CONFIG['transport'], $send_log); // add debug dialog if requested if ($this->CONFIG['transport']['debug']) { $template = str_insert_before('</body>', '<div class="debug-dialog">' . $send_log . '</div>', $template); CMS::$lock_redirect = true; } terminate('', 'Location: ./service_feedback_ok', 302); break; } return $template; }
/** * Creates a n XML representation of an Order * * @access public * @param mixed $arr * @param $customerNumber * @return mixed */ public function create($arr, $customerNumber) { $orderOptions = get_option('woocommerce_fortnox_order_settings'); $freight_options = get_option('woocommerce_fortnox_freight_settings'); $root = 'Order'; $seq_order_number = get_post_meta($arr->id, '_order_number', true); if (!empty($seq_order_number)) { logthis($seq_order_number); $order['DocumentNumber'] = $seq_order_number; } else { $order['DocumentNumber'] = $arr->id; } $order['AdministrationFee'] = $orderOptions['admin-fee']; $order['OrderDate'] = substr($arr->order_date, 0, 10); $order['DeliveryDate'] = substr($arr->order_date, 0, 10); $order['Currency'] = $arr->get_order_currency(); $order['CurrencyRate'] = '1'; $order['CurrencyUnit'] = '1'; $order['YourOrderNumber'] = $arr->id; $order['CustomerNumber'] = $customerNumber; $order['Address1'] = $arr->billing_address_1; $order['City'] = $arr->billing_city; $order['Country'] = $this->countries[$arr->billing_country]; $order['Phone1'] = $arr->billing_phone; $order['DeliveryAddress1'] = $arr->shipping_address_1; $order['DeliveryCity'] = $arr->shipping_city; $order['DeliveryCountry'] = $this->countries[$arr->shipping_country]; $order['DeliveryZipCode'] = $arr->shipping_postcode; $shipping_methods = $arr->get_shipping_methods(); $shipping_method = reset($shipping_methods); if (!empty($shipping_method)) { if (!empty($shipping_method['method_id'])) { if (isset($freight_options[$shipping_method['method_id']])) { $order['WayOfDelivery'] = $freight_options[$shipping_method['method_id']]; } } } if ($arr->payment_method == 'klarna_checkout') { $order['ExternalInvoiceReference1'] = $arr->id; } if (isset($arr->billing_company) && $arr->billing_company != '') { $order['CustomerName'] = $arr->billing_company; $order['YourReference'] = $arr->billing_first_name . " " . $arr->billing_last_name; } else { $order['CustomerName'] = $arr->billing_first_name . " " . $arr->billing_last_name; $order['DeliveryName'] = $arr->billing_first_name . " " . $arr->billing_last_name; } if ($orderOptions['payment-options'] != '') { $order['TermsOfPayment'] = $orderOptions['payment-options']; } if ($orderOptions['cost-center'] != '') { $order['CostCenter'] = $orderOptions['cost-center']; } $include_freight_tax = get_option('woocommerce_prices_include_tax'); if ($include_freight_tax == 'yes') { $order['Freight'] = $arr->get_total_shipping() * 0.8; } else { $order['Freight'] = $arr->get_total_shipping(); } $order['VATIncluded'] = 'false'; if ($orderOptions['add-payment-type'] == 'on') { $payment_method = get_post_meta($arr->id, '_payment_method_title'); $order['Remarks'] = $payment_method[0]; } $email = array(); $email['EmailAddressTo'] = $arr->billing_email; $order['EmailInformation'] = $email; $invoicerows = array(); //loop all items $index = 0; $pf = new WC_Product_Factory(); foreach ($arr->get_items() as $item) { $key = "OrderRow" . $index; //if variable product there might be a different SKU $is_variation = false; if (empty($item['variation_id'])) { $productId = $item['product_id']; } else { $productId = $item['variation_id']; $is_variation = true; } $product = $pf->get_product($productId); //handles missing product $invoicerow = array(); if (!($product == NULL)) { //!is_null($product) $invoicerow['ArticleNumber'] = $product->get_sku(); } $invoicerow['Description'] = $this->get_item_name($item, $product, $is_variation); $invoicerow['Unit'] = 'st'; $invoicerow['DeliveredQuantity'] = $item['qty']; $invoicerow['OrderedQuantity'] = $item['qty']; $invoicerow['Price'] = $this->get_product_price($item) / $item['qty']; $invoicerow['VAT'] = $this->get_tax_class_by_tax_name($product->get_tax_class(), $arr->shipping_country); $index += 1; $invoicerows[$key] = $invoicerow; } /****HANDLE FEES*****/ foreach ($arr->get_fees() as $item) { $key = "OrderRow" . $index; $invoicerow['Description'] = $item['name']; $invoicerow['Unit'] = 'st'; $invoicerow['DeliveredQuantity'] = 1; $invoicerow['OrderedQuantity'] = 1; $invoicerow['Price'] = $item['line_total']; $invoicerow['VAT'] = 25; $index += 1; $invoicerows[$key] = $invoicerow; } if ($arr->get_total_discount() > 0) { $coupon = $arr->get_used_coupons(); $coupon = new WC_Coupon($coupon[0]); if (!$coupon->apply_before_tax()) { $key = "OrderRow" . $index; $invoicerow = array(); $invoicerow['Description'] = "Rabatt"; $invoicerow['Unit'] = 'st'; $invoicerow['DeliveredQuantity'] = 1; $invoicerow['OrderedQuantity'] = 1; $invoicerow['Price'] = -1 * $arr->get_total_discount(); $invoicerow['VAT'] = 0; $invoicerows[$key] = $invoicerow; $index += 1; } } /****HANDLE PRODUCT AS FREIGHT*****/ if (!empty($orderOptions['freight-product-sku'])) { //RESET FREIGHT $order['Freight'] = 0; $product = $this->get_product_by_sku($orderOptions['freight-product-sku']); $key = "OrderRow" . $index; $invoicerow['ArticleNumber'] = $orderOptions['freight-product-sku']; $invoicerow['Description'] = $product->get_title(); $invoicerow['Unit'] = 'st'; $invoicerow['DeliveredQuantity'] = 1; $invoicerow['OrderedQuantity'] = 1; $invoicerow['Price'] = $arr->get_total_shipping(); $invoicerow['VAT'] = $this->get_tax_class_by_tax_name($product->get_tax_class(), $arr->shipping_country); $invoicerows[$key] = $invoicerow; } $order['OrderRows'] = $invoicerows; logthis(print_r($order, true)); return $this->generate($root, $order); }
function task_complete() { $ssh = new Net_SSH2('192.168.88.1'); if (!$ssh->login('admin', '')) { if ($ssh->login('admin', $GLOBALS['admin_password'])) { logthis('initial configuration completed'); $ssh->exec(':beep frequency=784 length=200ms;'); $ssh->exec(':delay 200ms;'); $ssh->exec(':beep frequency=740 length=200ms;'); $ssh->exec(':delay 200ms;'); $ssh->exec(':beep frequency=659 length=200ms;'); $ssh->exec(':delay 200ms;'); $ssh->exec(':beep frequency=659 length=200ms;'); $ssh->exec(':delay 200ms;'); $ssh->exec(':beep frequency=740 length=200ms;'); $ssh->exec(':delay 1000ms;'); } else { logthis('password ' . $GLOBALS['admin_password'] . ' is incorrect. '); } } }
} if (get_array_value(CMS::$cache[$module_name]['config'], 'disabled' === true)) { continue; } logthis('applying template processor at module: ' . $module_name); $template = CMS::$cache[$module_name]['object']->ContentGenerator($template); logthis('template processor finished at module: ' . $module_name); if (get_array_value(CMS::$cache[$module_name]['config'], 'break_after', false)) { break; } } // remove unused templates $template = preg_replace('~</?macro.*?>~', '', $template); $template = preg_replace('~\\[/?macro.*?\\]~', '', $template); // back-replace protected templates $template = str_replace('<protected-macro', '<macro', $template); $template = str_replace('[protected-macro', '[macro', $template); $template = str_replace('</protected-macro', '</macro', $template); $template = str_replace('[/protected-macro', '[/macro', $template); logthis('unused templates removed'); $template = popup_messages_to_template($template); logthis('popups added'); // flush CSS and JS storages $template = flush_CSS($template); $template = flush_JS($template); // sign it! $template = add_meta($template, 'name', 'generator', 'JuliaCMS Valenok Edition'); // yeah we did it! logthis('completed, adding log results and flushing!'); echo $template; terminate();
/** * TAG_TODO: написать очень, очень подробный комментарий сюда * */ function send_email($mailer, $from, $to, $subject, $body, $headers = array(), $attachments = array(), $server_params = null) { logthis('[send_email] : sending email "' . $subject . '" from "' . $from . '" to "' . $to . '"'); // extract emails if (!preg_match('~[a-zA-Z0-9.\\-]+@[a-zA-Z0-9.\\-]+~', $to, $mail_addresses)) { logthis('[send_email] : no addresses found!', ZLogger::LOG_LEVEL_ERROR); return false; } // $to may contain such structure: Julia (julia@example.com). Round brackets should be replaced with angle brackets $to = preg_replace('~[\\<\\[\\(]*([a-zA-Z0-9.\\-]+@[a-zA-Z0-9.\\-]+)[\\>\\]\\)]*~', '<$1>', $to); // encoding data for mail_mime $encoding_parameters = array('head_encoding' => 'base64', 'text_encoding' => 'base64', 'html_encoding' => 'base64', 'head_charset' => 'utf-8', 'text_charset' => 'utf-8', 'html_charset' => 'utf-8'); // add some important headers $headers_primary = array('From' => $from, 'To' => $to, 'Subject' => $subject); $headers = array_merge($headers_primary, $headers); // create mail body generator $mime = new Mail_mime($encoding_parameters); // by default, no text part $mime->setTXTBody(''); $alarm = 0; // replace image links with attached images if ($image_count = preg_match_all('~<img[^>]+src="(?!cid:)([^"]+)"[^>]*>~', $body, $img_data)) { for ($img_index = 0; $img_index < $image_count; $img_index++) { // generate new CID $cid = strtolower(str_replace('-', '', create_guid())); // image full CID, must contain sender domain to be displayed inline instead as attachment $cid_full = $cid . '@' . preg_replace('~[^@]*@~', '', $from); // add image $mime->addHTMLImage($img_data[1][$img_index], get_file_mime_type($img_data[1][$img_index]), '', true, $cid); // replace local image link to inline $new_image_link = str_replace($img_data[1][$img_index], 'cid:' . $cid_full, $img_data[0][$img_index]); // new image link $body = str_replace($img_data[0][$img_index], $new_image_link, $body); } } // ok, HTML part is ready now $mime->setHTMLBody($body); // add attachments foreach ($attachments as $attachment) { $attachment_filename = $attachment['filename']; $attachment_realname = $attachment['realname']; $mime->addAttachment($attachment_filename, get_file_mime_type($attachment_filename), $attachment_realname, true, 'base64', 'attachment', '', '', '', 'base64', 'utf-8', '', 'utf-8'); } // generate final headers $headers_ready = $mime->headers($headers); // get full message body $body_ready = $mime->get(); // now send $mail_result = $mailer->send($mail_addresses, $headers_ready, $body_ready); // free mem as messages are big unset($mime); // log result if ($mail_result === true) { logthis('[send_email] : ok'); } else { logthis('[send_email] : failed mailing to ' . $to . ' : ' . $mail_result->getMessage(), ZLogger::LOG_LEVEL_ERROR); } return $mail_result; }