示例#1
0
 /**
  * Урл для отписки
  * @return string
  */
 public function unsubscribeUrl()
 {
     $ret = cot_url('subscribe', array('m' => 'user', 'a' => 'unsubscribe', 'code' => $this->_data['unsubscr_code']));
     if (!cot_url_check($ret)) {
         $ret = cot::$cfg['mainurl'] . '/' . $ret;
     }
     return $ret;
 }
示例#2
0
文件: Rss.php 项目: ASDAFF/advboard
 public function indexAction()
 {
     global $structure;
     if (!cot_module_active('rss')) {
         cot_die_message(404, TRUE);
     }
     $c = cot_import('c', 'G', 'TXT');
     if (!empty($c)) {
         if (!isset($structure['advboard'][$c])) {
             cot_die_message(404, TRUE);
         }
         list(cot::$usr['auth_read'], cot::$usr['auth_write'], cot::$usr['isadmin']) = cot_auth('advboard', $c);
         cot_block(cot::$usr['auth_read']);
     }
     $rss_title = cot::$L['advboard_rss_feed'] . cot::$cfg['maintitle'];
     $rss_link = cot::$cfg['mainurl'];
     $rss_description = cot::$cfg['subtitle'];
     $domain = cot::$sys['domain'];
     $condition = array(array('state', advboard_model_Advert::PUBLISHED), array('begin', cot::$sys['now'], '<='), array('SQL', "expire = 0 OR expire > " . cot::$sys['now']));
     if (!empty($c)) {
         $rss_title = cot::$L['advboard_rss_feed'] . $structure['advboard'][$c]['title'] . ' - ' . cot::$cfg['maintitle'];
         $condition[] = array('category', $c);
     }
     $advertisement = advboard_model_Advert::find($condition, cot::$cfg['rss']['rss_maxitems'], 0, array(array('sort', 'desc')));
     $t = new XTemplate(cot_tplfile('rss'));
     $now = cot::$sys['now'];
     $now += cot::$usr['timezone'] * 3600;
     $t->assign(array('RSS_ENCODING' => cot::$cfg['rss']['rss_charset'], 'RSS_TITLE' => htmlspecialchars($rss_title), 'RSS_LINK' => $rss_link, 'RSS_LANG' => cot::$cfg['defaultlang'], 'RSS_DESCRIPTION' => htmlspecialchars($rss_description), 'RSS_DATE' => $this->fixPubDate(date("r", $now))));
     if (!empty($advertisement)) {
         foreach ($advertisement as $advert) {
             $url = $advert->url;
             if (!cot_url_check($url)) {
                 $url = COT_ABSOLUTE_URL . $url;
             }
             $date = '';
             if (!empty($advert->created)) {
                 $date = strtotime($advert->created);
                 $date += cot::$usr['timezone'] * 3600;
                 $date = date('r', $date);
                 $date = $this->fixPubDate($date);
             }
             $text = $advert->text;
             $textlength = intval(cot::$cfg['rss']['rss_pagemaxsymbols']);
             if ($textlength > 0 && mb_strlen($text) > $textlength) {
                 $text = cot_string_truncate($text, $textlength, true, false, cot::$R['advboard_cuttext']);
             }
             $t->assign(array('RSS_ROW_TITLE' => htmlspecialchars($advert->title), 'RSS_ROW_DESCRIPTION' => $this->convertRelativeUrls($text), 'RSS_ROW_DATE' => $date, 'RSS_ROW_LINK' => $url));
             $t->parse('MAIN.ITEM_ROW');
         }
     }
     $t->parse('MAIN');
     //        ob_clean();
     header('Content-type: text/xml; charset=UTF-8');
     echo $t->text('MAIN');
     exit;
 }
         include cot_langfile('main', 'core', cot::$cfg['defaultlang'], $owner['user_lang']);
         include cot_langfile('advboard', 'module', cot::$cfg['defaultlang'], $owner['user_lang']);
     }
 }
 // Выдержка с поста
 //        $len_cut = 500;  // Длина выдержки с поста (символов)
 $advComText = cot_parse($comarray['com_text'], cot::$cfg['plugin']['comments']['markup']);
 //        $advComText = cot_string_truncate($advComText, $len_cut, true, false, '...');
 // /Выдержка с поста
 // Автор комментария
 $advCommenterName = cot::$L['Anonymous'];
 $advCommenterUrl = '';
 if (cot::$usr['id'] > 0) {
     $advCommenterName = cot_user_full_name(cot::$usr['profile']);
     $advCommenterUrl = cot_url('users', array('m' => 'details', 'id' => cot::$usr['id'], 'u' => htmlspecialchars(cot::$usr['name'])));
     if (!cot_url_check($advCommenterUrl)) {
         $advCommenterUrl = COT_ABSOLUTE_URL . $advCommenterUrl;
     }
 } elseif ($comarray['com_author'] != '') {
     $advCommenterName = $comarray['com_author'];
 }
 // /Автор комментария
 $mailView = new View();
 $mailView->advert = $advert;
 $mailView->owner = $owner;
 $mailView->commentText = $advComText;
 $mailView->commentUrl = $advertUrl . "#c" . $id;
 $mailView->commenter = cot::$usr['id'] > 0 ? cot::$usr['profile'] : array();
 $mailView->commenterName = $advCommenterName;
 $mailView->commenterUrl = $advCommenterUrl;
 $mailView->advertUrl = $advertUrl;
示例#4
0
/* ====================
[BEGIN_COT_EXT]
Hooks=header.main
[END_COT_EXT]
==================== */
/**
 * Ads board module for Cotonti Siena
 *
 * @package Advboard
 * @author Kalnov Alexey    <*****@*****.**>
 * @copyright (c) 2015 Portal30 Studio http://portal30.ru
 */
defined('COT_CODE') or die('Wrong URL');
if (!defined('COT_ADMIN') && cot::$cfg['advboard']['rssToHeader'] == 1 && cot_module_active('rss')) {
    require_once cot_incfile('advboard', 'module');
    // Получить все категории
    if (!empty($structure['advboard'])) {
        foreach ($structure['advboard'] as $adv_rssCode => $adv_rssCat) {
            if ($adv_rssCat['count'] == 0 || !cot_auth('advboard', $adv_rssCode, 'R')) {
                continue;
            }
            $advCatTitle = htmlspecialchars($adv_rssCat['title']);
            $adv_rssUrl = cot_url('advboard', array('m' => 'rss', 'c' => $adv_rssCode));
            if (!cot_url_check($adv_rssUrl)) {
                $adv_rssUrl = COT_ABSOLUTE_URL . $adv_rssUrl;
            }
            cot::$out['head_head'] .= "\n" . '<link rel="alternate" type="application/rss+xml" title="' . cot::$L['advboard_rss_feed'] . $advCatTitle . '" href="' . $adv_rssUrl . '" />';
        }
    }
}
示例#5
0
 * Installation handler
 *
 * @package SiteMap
 * @copyright (c) Cotonti Team
 * @license https://github.com/Cotonti/Cotonti/blob/master/License.txt
 *
 * @todo notifications about robots.txt (if need to add o delete some strings)
 */
defined('COT_CODE') or die('Wrong URL');
$robotsTxtFilePath = './robots.txt';
$robotsTxtFile = '';
$robotsTxtChanged = false;
if (file_exists($robotsTxtFilePath) && is_writable($robotsTxtFilePath)) {
    $siteMapLinks = array('index' => cot_url('plug', array('r' => 'sitemap', 'a' => 'index'), '', true), 'handy' => 'sitemap.xml');
    foreach ($siteMapLinks as $key => $val) {
        if (!cot_url_check($val)) {
            $siteMapLinks[$key] = cot::$cfg['mainurl'] . '/' . $siteMapLinks[$key];
        }
    }
    $robotsTxtFile = file($robotsTxtFilePath);
    $to_delete = array();
    $to_add = $siteMapLinks;
    foreach ($robotsTxtFile as $line) {
        // Sitemap line. Find it all
        if (mb_strpos(mb_strtolower($line), 'sitemap:') !== false) {
            // find all Sitemap links in robots.txt and remove duplicates
            $found = false;
            foreach ($siteMapLinks as $key => $siteMapLink) {
                if (mb_stripos($line, $siteMapLink) !== false) {
                    $found = true;
                    unset($to_add[$key]);
示例#6
0
/**
 * Displays redirect page
 *
 * @param string $url Target URI
 */
function cot_redirect($url)
{
    global $cfg, $env, $error_string, $sys;
    if (cot_error_found() && $_SERVER['REQUEST_METHOD'] == 'POST') {
        // Save the POST data
        if (!empty($error_string)) {
            // Message should not be lost
            cot_error($error_string);
        }
        cot_import_buffer_save();
    }
    if (!cot_url_check($url)) {
        // No redirects to foreign domains
        if ($url == '/' || $url == $sys['site_uri']) {
            $url = COT_ABSOLUTE_URL;
        } else {
            if ($url[0] === '/') {
                $url = mb_substr($url, 1);
            }
            $url = COT_ABSOLUTE_URL . $url;
        }
    }
    if (defined('COT_AJAX') && COT_AJAX) {
        // Save AJAX state, some browsers loose it after redirect (e.g. FireFox 3.6)
        $sep = strpos($url, '?') === false ? '?' : '&';
        $url .= $sep . '_ajax=1';
    }
    if (isset($env['status'])) {
        $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
        header($protocol . ' ' . $env['status']);
    }
    if ($cfg['redirmode']) {
        $output = $cfg['doctype'] . <<<HTM
\t\t<html>
\t\t<head>
\t\t<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
\t\t<meta http-equiv="refresh" content="0; url={$url}" />
\t\t<title>Redirecting...</title></head>
\t\t<body>Redirecting to <a href="{$url}">{$url}</a>
\t\t</body>
\t\t</html>
HTM;
        header('Refresh: 0; URL=' . $url);
        echo $output;
        exit;
    } else {
        header('Location: ' . $url);
        exit;
    }
}
示例#7
0
    if ($already_rated) {
        $db->delete($db_rated, 'rated_userid = ? AND rated_area = ? AND rated_code = ?', array($usr['id'], $area, $code));
    }
    // Insert new rating for the item if none is present
    if (!$item_has_rating) {
        $db->insert($db_ratings, array('rating_code' => $code, 'rating_area' => $area, 'rating_state' => 0, 'rating_average' => (int) $newrate, 'rating_creationdate' => (int) $sys['now'], 'rating_text' => ''));
    }
    if ($newrate > 0) {
        // Insert new vote and recalculate average value
        $db->insert($db_rated, array('rated_code' => $code, 'rated_area' => $area, 'rated_userid' => $usr['id'], 'rated_value' => (int) $newrate, 'rated_date' => $sys['now']));
    }
    $rating_voters = $db->query("SELECT COUNT(*) FROM {$db_rated}\n\t\tWHERE rated_area = ? AND rated_code = ?", array($area, $code))->fetchColumn();
    if ($rating_voters > 0) {
        $ratingnewaverage = $db->query("SELECT AVG(rated_value) FROM {$db_rated}\n\t\t\tWHERE rated_area = ? AND rated_code = ?", array($area, $code))->fetchColumn();
    } else {
        $ratingnewaverage = 0;
    }
    $db->update($db_ratings, array('rating_average' => round($ratingnewaverage, 2)), 'rating_area = ? AND rating_code = ?', array($area, $code));
    /* == Hook for the plugins == */
    foreach (cot_getextplugins('ratings.send.done') as $pl) {
        include $pl;
    }
    /* ===== */
    // Done, output results
    if (!COT_AJAX && cot_url_check($_SERVER['HTTP_REFERER'])) {
        cot_redirect($_SERVER['HTTP_REFERER']);
    } else {
        echo round($ratingnewaverage);
    }
    exit;
}
示例#8
0
文件: User.php 项目: ASDAFF/advboard
 /**
  * Рассылка уведомлений об истечении сроков публикации объявления
  */
 public static function sendExpireNotify()
 {
     global $L;
     $cacheFileName = cot::$cfg["modules_dir"] . '/advboard/inc/send.txt';
     if (file_exists($cacheFileName)) {
         $adv_send = file_get_contents($cacheFileName);
     } else {
         $adv_send = 0;
     }
     $tmp = getdate(cot::$sys['now']);
     $today = mktime(0, 0, 0, $tmp["mon"], $tmp["mday"], $tmp["year"]);
     // Рассылаем раз в сутки
     if ($today - $adv_send >= 86400) {
         // Период за который рассылаем
         if ($adv_send == 0) {
             // не разу не рассылали еще
             $adv_sendPer = cot::$cfg['advboard']['expNotifyPeriod'];
         } else {
             $adv_sendPer = floor(($today - $adv_send) / 86400);
         }
         // Уведомляем об истечении
         // Пока тупо шлем напоминание всем объявлениям у которых дата истечения
         // Больше той, когда заходили последний раз, но меньше текущей минус <уведомить за>
         $stDay = $tmp["mday"] + cot::$cfg['advboard']['expNotifyPeriod'] - $adv_sendPer;
         $periodStart = mktime(0, 0, 0, $tmp["mon"], $stDay, $tmp["year"]);
         if ($periodStart < cot::$sys['now']) {
             $periodStart = cot::$sys['now'];
         }
         $periodEnd = mktime(0, 0, 0, $tmp["mon"], $tmp["mday"] + cot::$cfg['advboard']['expNotifyPeriod'], $tmp["year"]);
         $condition = array(array('expire', $periodStart, '>='), array('expire', $periodEnd, '<'), array('state', advboard_model_Advert::PUBLISHED), array('user', 0, '>'));
         $advertisement = advboard_model_Advert::find($condition, 0, 0, array(array('id', 'ASC')));
         $cnt = 0;
         if ($advertisement) {
             foreach ($advertisement as $advRow) {
                 if (!$advRow->issetEmail(true)) {
                     return false;
                 }
                 $advertUrl = $advRow->getUrl();
                 if (!cot_url_check($advertUrl)) {
                     $advertUrl = COT_ABSOLUTE_URL . $advertUrl;
                 }
                 $advertEditUrl = $advRow->getEditUrl();
                 if (!cot_url_check($advertEditUrl)) {
                     $advertEditUrl = COT_ABSOLUTE_URL . $advertEditUrl;
                 }
                 $myAdvsUrl = cot_url('advboard', 'm=user');
                 if (!cot_url_check($myAdvsUrl)) {
                     $myAdvsUrl = COT_ABSOLUTE_URL . $myAdvsUrl;
                 }
                 $tmpL = $L;
                 $text = $advRow->description;
                 if (empty($text)) {
                     $text = $advRow->text;
                 }
                 $user = null;
                 $userLang = cot::$cfg['defaultlang'];
                 $owner = $advRow->getOwner();
                 if ($owner['user_id'] > 0) {
                     if (cot::$cfg['defaultlang'] != $owner['user_lang']) {
                         $userLang = $owner['user_lang'];
                         include cot_langfile('main', 'core', cot::$cfg['defaultlang'], $owner['user_lang']);
                         include cot_langfile('advboard', 'module', cot::$cfg['defaultlang'], $owner['user_lang']);
                     }
                 }
                 $mailView = new View();
                 $mailView->advert = $advRow;
                 $mailView->user = $owner;
                 $mailView->advertUrl = $advertUrl;
                 $mailView->advertEditUrl = $advertEditUrl;
                 $mailView->myAdvsUrl = $myAdvsUrl;
                 $mailView->advertText = $text;
                 $mailSubject = cot::$L['advboard_expire_title'];
                 $mailBody = $mailView->render('advboard.notify_expire.' . $userLang . '.' . $advRow->category);
                 if (cot_mail($advRow->getEmail(false, true), $mailSubject, $mailBody, '', false, null, true)) {
                     $cnt++;
                 }
                 // Вернем язык на место
                 $L = $tmpL;
             }
         }
         file_put_contents($cacheFileName, $today);
         return $cnt;
     }
     return 0;
 }
示例#9
0
 public function viewAction()
 {
     global $admintitle, $adminpath, $Ls;
     $id = cot_import('id', 'G', 'INT');
     // id Рассылки
     if (empty($id)) {
         cot_error(cot::$L['subscribe_err_not_found']);
         cot_redirect(cot_url('admin', array('m' => 'subscribe'), '', true));
     }
     $subscribe = subscribe_model_Subscribe::getById($id);
     if (empty($subscribe)) {
         cot_error(cot::$L['subscribe_err_not_found']);
         cot_redirect(cot_url('admin', array('m' => 'subscribe'), '', true));
     }
     $admintitle = $subscribe->title;
     $adminpath[] = array(cot_url('admin', array('m' => 'subscribe')), cot::$L['subscribe_subscribes']);
     $adminpath[] = array(cot_url('admin', array('m' => 'subscribe', 'a' => 'edit', 'id' => $id)), $subscribe->title);
     $adminpath[] = array(cot_url('admin', array('m' => 'subscribe', 'a' => 'view', 'id' => $id)), cot::$L['Preview']);
     $rpc = trim($subscribe->content_url);
     if ($rpc != '') {
         $text = file_get_contents($rpc);
         if (!$text || $text == '') {
             echo "[Error] I can not get email content from address: '{$rpc}' \n";
             echo "Stopped\n\n";
             ob_flush();
             return false;
         }
     } else {
         $text = $subscribe->text;
         preg_match_all("/\\[URL#([a-zA-Z0-9-\\?_\\=\\:\\/\\.\\&;,]+)#]/ies", $text, $m);
         $_vars = array();
         foreach ($m[1] as $varName) {
             $varurl = html_entity_decode($varName);
             $_vars["[URL#" . $varName . "#]"] = file_get_contents($varurl);
         }
         $text = str_replace(array_keys($_vars), $_vars, $text);
         $text = str_replace('[YEAR]', cot_date('Y'), $text);
     }
     $msgView = new View();
     $msgView->subscribe = $subscribe;
     $msgView->text = $text;
     $tpl = array('subscribe', 'mail');
     if (!empty($subscribe->alias)) {
         $tpl[] = $subscribe->alias;
     }
     $fromTitle = cot::$cfg['maintitle'];
     if (!empty($subscribe->from_title)) {
         $fromTitle = $subscribe->from_title;
     }
     $fromEmail = cot::$cfg["adminemail"];
     if (!empty($subscribe->from_mail)) {
         $fromEmail = $subscribe->from_mail;
     }
     $subject = !empty($subscribe->subject) ? $subscribe->subject : $subscribe->title;
     $data = array('subscribe' => $subscribe->id, 'subject' => $subject, 'fromName' => $fromTitle, 'fromEmail' => $fromEmail);
     // Тестовый подписчик
     $item = array('id' => 123, 'email' => '*****@*****.**', 'name' => 'Test User', 'unsubscr_code' => '123456789qwertyu');
     $msgView->subscribe = $subscribe;
     $msgView->subscriber = $item;
     $msgBody = $msgView->render($tpl);
     $data['subscriber'] = $item['id'];
     $data['toEmail'] = $item['email'];
     $data['toName'] = $item['name'];
     // Поддержка тегов 'отписаться'
     $tmp = cot_url('subscribe', array('m' => 'user', 'a' => 'unsubscribe', 'code' => $item['unsubscr_code']));
     if (!cot_url_check($tmp)) {
         $tmp = cot::$cfg['mainurl'] . '/' . $tmp;
     }
     $toSend = str_replace('[UNSUBSCRIBE_URL]', "<a href=\"{$tmp}\">{$tmp}</a>", $msgBody);
     $data['text'] = $toSend;
     $subscribers = subscribe_model_Subscriber::count(array(array('subscribe', $id)));
     $activeSubscribers = subscribe_model_Subscriber::count(array(array('subscribe', $id), array('active', 1)));
     $template = array('subscribe', 'admin', 'view');
     $view = new View();
     $view->page_title = $subscribe->title . ' [' . cot::$L['Preview'] . ']';
     $view->subscribe = $subscribe;
     $view->subscriber = $item;
     $view->subscribers = $subscribers;
     $view->activeSubscribers = $activeSubscribers;
     $view->data = $data;
     return $view->render($template);
 }
示例#10
0
                    $page_args['id'] = $row['page_id'];
                }
                $sql = $db->query("SELECT c.*, u.user_name\n\t\t\t\t\tFROM {$db_com} AS c\n\t\t\t\t\tLEFT JOIN {$db_users} AS u ON c.com_authorid = u.user_id\n\t\t\t\t\tWHERE com_area = 'page' AND com_code='{$page_id}'\n\t\t\t\t\tORDER BY com_date DESC LIMIT " . $cfg['rss']['rss_maxitems']);
                $i = 0;
                while ($row1 = $sql->fetch()) {
                    $items[$i]['title'] = $L['rss_comment_of_user'] . " " . $row1['user_name'];
                    $text = cot_parse($row1['com_text'], $cfg['plugin']['comments']['parsebbcodecom']);
                    if ((int) $cfg['plugin']['comments']['rss_commentmaxsymbols'] > 0) {
                        $text .= cot_string_truncate($text, $cfg['plugin']['comments']['rss_commentmaxsymbols']) ? '...' : '';
                    }
                    $items[$i]['description'] = $text;
                    $items[$i]['link'] = cot_url('page', $page_args, '#c' . $row1['com_id'], true);
                    if (!cot_url_check($items[$i]['link'])) {
                        $items[$i]['link'] = COT_ABSOLUTE_URL . $items[$i]['link'];
                    }
                    $items[$i]['pubDate'] = cot_date('r', $row1['com_date']);
                    $i++;
                }
                // Attach original page text as last item
                $row['page_pageurl'] = cot_url('page', $page_args, '', true);
                $items[$i]['title'] = $L['rss_original'];
                $items[$i]['description'] = cot_parse_page_text($row['page_text'], $row['page_pageurl'], $row['page_parser']);
                $items[$i]['link'] = $row['page_pageurl'];
                if (!cot_url_check($items[$i]['link'])) {
                    $items[$i]['link'] = COT_ABSOLUTE_URL . $items[$i]['link'];
                }
                $items[$i]['pubDate'] = cot_date('r', $row['page_date']);
            }
        }
    }
}
示例#11
0
 /**
  * @param subscribe_model_Subscribe $subscribe
  * @return int количество отосланных писем
  */
 public static function subscribeRun($subscribe)
 {
     if (empty($subscribe)) {
         return false;
     }
     $nowdate = date('Y-m-d H:i:s', cot::$sys['now']);
     // Сэкономим память. Ощутимо на большом количестве подписчиков
     $stmtSubscribers = cot::$db->query("SELECT * FROM " . subscribe_model_Subscriber::tableName() . "\n            WHERE subscribe={$subscribe->id} AND last_executed<'{$nowdate}' AND active=1");
     $count = $stmtSubscribers->rowCount();
     if ($count == 0) {
         return 0;
     }
     $i = 0;
     $rpc = trim($subscribe->content_url);
     if ($rpc != '') {
         $text = file_get_contents($rpc);
         if (!$text || $text == '') {
             echo "[Error] I can not get email content from address: '{$rpc}' \n";
             echo "Stopped\n\n";
             ob_flush();
             return false;
         }
     } else {
         $text = $subscribe->text;
         preg_match_all("/\\[URL#([a-zA-Z0-9-\\?_\\=\\:\\/\\.\\&;,]+)#]/ies", $text, $m);
         $_vars = array();
         foreach ($m[1] as $varName) {
             $varurl = html_entity_decode($varName);
             $_vars["[URL#" . $varName . "#]"] = file_get_contents($varurl);
         }
         $text = str_replace(array_keys($_vars), $_vars, $text);
         $text = str_replace('[YEAR]', cot_date('Y'), $text);
     }
     echo "Subscribers count: " . $stmtSubscribers->rowCount() . "\n";
     $msgView = new View();
     $msgView->subscribe = $subscribe;
     $msgView->text = $text;
     $tpl = array('subscribe', 'mail');
     if (!empty($subscribe->alias)) {
         $tpl[] = $subscribe->alias;
     }
     $fromTitle = cot::$cfg['maintitle'];
     if (!empty($subscribe->from_title)) {
         $fromTitle = $subscribe->from_title;
     }
     $fromEmail = cot::$cfg["adminemail"];
     if (!empty($subscribe->from_mail)) {
         $fromEmail = $subscribe->from_mail;
     }
     $subject = !empty($subscribe->subject) ? $subscribe->subject : $subscribe->title;
     if (cot::$cfg['subscribe']['useQueue']) {
         $sender = new subscribe_sender_Queue();
     } else {
         $sender = new subscribe_sender_Cotmail();
     }
     $errors = 0;
     $data = array('subscribe' => $subscribe->id, 'subject' => $subject, 'fromName' => $fromTitle, 'fromEmail' => $fromEmail);
     while ($item = $stmtSubscribers->fetch()) {
         echo " - Processing: " . trim($item['name'] . ' ' . $item['email']) . " ...";
         ob_flush();
         // Кешируем время выполнения
         // Memcache было бы лучше
         $subscribe->ping = date('Y-m-d H:i:s');
         // Текущее системное время, а не то что было на момент старта скрипта
         $subscribe->save();
         $msgView->subscribe = $subscribe;
         $msgView->subscriber = $item;
         $msgBody = $msgView->render($tpl);
         $data['subscriber'] = $item['id'];
         $data['toEmail'] = $item['email'];
         $data['toName'] = $item['name'];
         // Поддержка тегов 'отписаться'
         $tmp = cot_url('subscribe', array('m' => 'user', 'a' => 'unsubscribe', 'code' => $item['unsubscr_code']));
         if (!cot_url_check($tmp)) {
             $tmp = cot::$cfg['mainurl'] . '/' . $tmp;
         }
         $toSend = str_replace('[UNSUBSCRIBE_URL]', "<a href=\"{$tmp}\">{$tmp}</a>", $msgBody);
         $data['body'] = $toSend;
         $isError = false;
         try {
             $sender->send($data);
         } catch (Exception $e) {
             $isError = true;
             $errors++;
             $errCode = $e->getCode();
             $errMsg = $e->getMessage();
             echo "\n[ERROR] {$errCode}:  {$errMsg}! While sending to: {$item['email']}\n";
             ob_flush();
             // Зафиксировать в базе ошибку отправки сообщения
             $tmpData = array('last_error' => mb_substr("{$errCode}:  {$errMsg}", 0, 253));
             cot::$db->update(subscribe_model_Subscriber::tableName(), $tmpData, "id={$item['id']}");
             // TODO проанализировать ошибку, если User not found - отписать его, чтобы больше не слать ему письма
             // 500 - User not found
             // 553 - Invalid domain name
             //                if ($errCode == 550 || $errCode == 553){
             //                    // Зафиксировать в базе ошибку отправки сообщения
             //                    echo "Отписываю его...\n";
             //                    ob_flush();
             //                    $data = array(
             //                        'subr_on' => 'false',
             //                        'subr_last_error' => "{$errCode}:  {$errMsg}",
             //                    );
             //                    $db->update('subscriber', $data, "subr_id={$item['subr_id']}");
             //
             //                }else{
             var_dump($e);
             echo "\n------------\n";
             ob_flush();
             //                }
         }
         if (!$isError) {
             echo " done\n";
             $tmpData = array('last_executed' => $nowdate, 'last_error' => '');
             cot::$db->update(subscribe_model_Subscriber::tableName(), $tmpData, "id={$item['id']}");
             $i++;
         }
         unset($item);
         if ($i % 100 == 0) {
             gc_collect_cycles();
         }
     }
     if ($errors > 0) {
         echo "\nErrors count: {$errors} \n";
         ob_flush();
     }
     return $i;
 }
示例#12
0
 /**
  * Обработка Ajax запроса на подписку на рассылку
  * Используется виджетом
  * Принимает email пользователя
  * Допускается подписка неавторизованными пользователями (они должны подтвердить email)
  */
 public function ajxSubscribeAction()
 {
     global $db_users;
     $ret = array('error' => '', 'message' => '');
     $id = cot_import('id', 'P', 'INT');
     $email = cot_import('email', 'P', 'TXT');
     if (!$id) {
         $ret['error'] = cot::$L['subscribe_err_not_found'];
         echo json_encode($ret);
         exit;
     }
     $subscribe = subscribe_model_Subscribe::getById($id);
     if (!$subscribe) {
         $ret['error'] = cot::$L['subscribe_err_not_found'];
         echo json_encode($ret);
         exit;
     }
     if (!$subscribe->active) {
         $ret['error'] = cot::$L['subscribe_err_disabled'];
         echo json_encode($ret);
         exit;
     }
     if (empty($email)) {
         $ret['error'] = cot::$L['field_required'] . ': ' . cot::$L['Email'];
         echo json_encode($ret);
         exit;
     }
     $tmp = subscribe_checkEmail($email);
     if ($tmp !== true) {
         $ret['error'] = $tmp;
         echo json_encode($ret);
         exit;
     }
     $email = mb_strtolower($email);
     $subscriber = subscribe_model_Subscriber::fetchOne(array(array('subscribe', $id), array('email', $email)));
     if ($subscriber) {
         if ($subscriber->active) {
             $ret['error'] = sprintf(cot::$L['subscribe_err_user_subscribed'], $email, $subscribe->title);
             echo json_encode($ret);
             exit;
         }
     } else {
         $subscriber = new subscribe_model_Subscriber();
     }
     $sql = cot::$db->query("SELECT * FROM {$db_users} WHERE user_email = ? LIMIT 1", $email);
     $user = $sql->fetch();
     $subscriber->subscribe = $id;
     $subscriber->email = $email;
     if (!empty($user)) {
         $subscriber->user = $user['user_id'];
         $subscriber->name = cot_user_full_name($user);
     }
     $needConfirm = cot::$cfg['subscribe']['guestConfirmMail'];
     if (cot::$usr['id'] > 0) {
         if (cot::$usr['id'] == $user['user_id'] || cot::$usr['isadmin']) {
             $needConfirm = false;
         }
     }
     if ($needConfirm) {
         // Возможно пользователь уже подтверждал свой email
         $tmp = subscribe_model_Subscriber::count(array(array('email', $email), array('email_valid', 1)));
         if ($tmp > 0) {
             $needConfirm = false;
         }
     }
     if (!$needConfirm) {
         $subscriber->email_valid = 1;
         $subscriber->email_valid_date = date('Y-m-d H:i:s', cot::$sys['now']);
         $subscriber->active = 1;
     }
     // Сохранение
     $subscriber->save();
     $ret['message'] = sprintf(cot::$L['subscribe_msg_you_subscribed'], $subscribe->title);
     // Письмо для поджтверждения e-mail адреса
     if ($needConfirm) {
         $confirmUrl = cot_url('subscribe', array('m' => 'user', 'a' => 'confirm', 'code' => $subscriber->unsubscr_code));
         if (!cot_url_check($confirmUrl)) {
             $confirmUrl = cot::$cfg['mainurl'] . '/' . $confirmUrl;
         }
         $mailView = new View();
         $mailView->subscriber = $subscriber;
         $mailView->subscribe = $subscribe;
         $mailView->confirmUrl = $confirmUrl;
         $mailTpl = array('subscribe', 'mail_confirm', cot::$usr['lang']);
         $mailBody = $mailView->render($mailTpl);
         cot_mail($email, cot::$L['subscribe_confirm'], $mailBody, '', false, null, true);
         $ret['message'] .= cot::$L['subscribe_wait_confirm'];
     }
     echo json_encode($ret);
     exit;
 }
示例#13
0
 public function notifyUserModerated()
 {
     global $db_users, $L;
     $advertUrl = $this->getUrl();
     if (!cot_url_check($advertUrl)) {
         $advertUrl = COT_ABSOLUTE_URL . $advertUrl;
     }
     $tmpL = $L;
     $text = $this->_data['description'];
     if (empty($text)) {
         $text = $this->_data['text'];
     }
     $user = null;
     $userLang = cot::$cfg['defaultlang'];
     if (!$this->issetEmail(true)) {
         return false;
     }
     $this->getOwner();
     if ($this->_data['user'] > 0) {
         if (cot::$cfg['defaultlang'] != $this->_owner['user_lang']) {
             $userLang = $this->_owner['user_lang'];
             include cot_langfile('main', 'core', cot::$cfg['defaultlang'], $this->_owner['user_lang']);
             include cot_langfile('advboard', 'module', cot::$cfg['defaultlang'], $this->_owner['user_lang']);
         }
     }
     $mailView = new View();
     $mailView->advert = $this;
     $mailView->user = $this->_owner;
     $mailView->advertUrl = $advertUrl;
     $mailView->advertText = $text;
     $mailSubject = $L['advboard_moderated'];
     $mailBody = $mailView->render('advboard.notify_user_moderated.' . $userLang . '.' . $this->_data['category']);
     cot_mail($this->getEmail(false, true), $mailSubject, $mailBody, '', false, null, true);
     // Вернем язык на место
     $L = $tmpL;
     // Сбросить флаг уведомления
     static::$_db->update(static::$_tbname, array('admin_notified' => '1970-01-01 00:00:01'), 'id=' . $this->_data['id']);
 }