K
K
K. A.2016-12-02 16:13:14
JavaScript
K. A., 2016-12-02 16:13:14

How to send a big message to wall.post?

Faced a problem, already ran out of ideas. The bottom line is this:
there is a page on which there is a WYSIWYG editor in which news is written. When submitting the form, the data is written to the database. It was necessary to add cross-posting to the VKontate group. Because this cannot be implemented without crutches in PHP, then I use OpenApi and jQuery. Wrote a function:

function postVK(text, news_id, id_tape)
{
    //функция редиректа
    function redirectToMain()
    {
        if (action == 'subscribe'){
            location.href='subscribes.php';
        } else {
            location.href='index.php?id_tape='+id_tape;
        }
    }


    //преобразование мнемоники
    var HTML=function(){
        var x,mnem=
            {34:"quot",38:"amp",39:"apos",60:"lt",62:"gt",402:"fnof",
                338:"OElig",339:"oelig",352:"Scaron",353:"scaron",
                376:"Yuml",710:"circ",732:"tilde",8226:"bull",8230:"hellip",
                8242:"prime",8243:"Prime",8254:"oline",8260:"frasl",8472:"weierp",
                8465:"image",8476:"real",8482:"trade",8501:"alefsym",8592:"larr",
                8593:"uarr",8594:"rarr",8595:"darr",8596:"harr",8629:"crarr",
                8656:"lArr",8657:"uArr",8658:"rArr",8659:"dArr",8660:"hArr",
                8704:"forall",8706:"part",8707:"exist",8709:"empty",8711:"nabla",
                8712:"isin",8713:"notin",8715:"ni",8719:"prod",8721:"sum",
                8722:"minus",8727:"lowast",8730:"radic",8733:"prop",8734:"infin",
                8736:"ang",8743:"and",8744:"or",8745:"cap",8746:"cup",8747:"int",
                8756:"there4",8764:"sim",8773:"cong",8776:"asymp",8800:"ne",
                8801:"equiv",8804:"le",8805:"ge",8834:"sub",8835:"sup",8836:"nsub",
                8838:"sube",8839:"supe",8853:"oplus",8855:"otimes",8869:"perp",
                8901:"sdot",8968:"lceil",8969:"rceil",8970:"lfloor",8971:"rfloor",
                9001:"lang",9002:"rang",9674:"loz",9824:"spades",9827:"clubs",
                9829:"hearts",9830:"diams",8194:"ensp",8195:"emsp",8201:"thinsp",
                8204:"zwnj",8205:"zwj",8206:"lrm",8207:"rlm",8211:"ndash",
                8212:"mdash",8216:"lsquo",8217:"rsquo",8218:"sbquo",8220:"ldquo",
                8221:"rdquo",8222:"bdquo",8224:"dagger",8225:"Dagger",8240:"permil",
                8249:"lsaquo",8250:"rsaquo",8364:"euro",977:"thetasym",978:"upsih",982:"piv"},
            tab=("nbsp|iexcl|cent|pound|curren|yen|brvbar|sect|uml|"+
            "copy|ordf|laquo|not|shy|reg|macr|deg|plusmn|sup2|sup3|"+
            "acute|micro|para|middot|cedil|sup1|ordm|raquo|frac14|"+
            "frac12|frac34|iquest|Agrave|Aacute|Acirc|Atilde|Auml|"+
            "Aring|AElig|Ccedil|Egrave|Eacute|Ecirc|Euml|Igrave|"+
            "Iacute|Icirc|Iuml|ETH|Ntilde|Ograve|Oacute|Ocirc|Otilde|"+
            "Ouml|times|Oslash|Ugrave|Uacute|Ucirc|Uuml|Yacute|THORN|"+
            "szlig|agrave|aacute|acirc|atilde|auml|aring|aelig|ccedil|"+
            "egrave|eacute|ecirc|euml|igrave|iacute|icirc|iuml|eth|ntilde|"+
            "ograve|oacute|ocirc|otilde|ouml|divide|oslash|ugrave|uacute|"+
            "ucirc|uuml|yacute|thorn|yuml").split("|");
        for(x=0;x<96;x++)mnem[160+x]=tab[x];
        tab=("Alpha|Beta|Gamma|Delta|Epsilon|Zeta|Eta|Theta|Iota|Kappa|"+
        "Lambda|Mu|Nu|Xi|Omicron|Pi|Rho").split("|");
        for(x=0;x<17;x++)mnem[913+x]=tab[x];
        tab=("Sigma|Tau|Upsilon|Phi|Chi|Psi|Omega").split("|");
        for(x=0;x<7;x++)mnem[931+x]=tab[x];
        tab=("alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|"+
        "lambda|mu|nu|xi|omicron|pi|rho|sigmaf|sigma|tau|upsilon|phi|chi|"+
        "psi|omega").split("|");
        for(x=0;x<25;x++)mnem[945+x]=tab[x];
        return {
            encode:function(text){
                return text.replace(/[\u00A0-\u2666<>\&]/g,function(a){
                    return "&"+(mnem[a=a.charCodeAt(0)]||"#"+a)+";"
                })
            },
            decode:function(text){
                return text.replace(/\&#?(\w+);/g,function(a,b){
                    if(Number(b))return String.fromCharCode(Number(b));
                    for(x in mnem){
                        if(mnem[x]===b)return String.fromCharCode(x);
                    }
                })
            }
        }
    }();

    //Спрашиваем, нужно ли добавлять запись в ВК
    if(confirm("Отправить запись в группу ВКонтакте?"))
    {
        //если да, то проверяем авторизацию, если нет, запрашиваем ее.
        VK.Auth.getLoginStatus(authInfo);

        //основная часть функции.
        function authInfo(auth) {
            //если авторизация есть
            if (auth.session) {
                //удаляем все HTML-тэги из него
                var strippedText = HTML.decode(text.replace(/(<([^>]+)>)/ig,""));
                //вызываем АПИ для добавления на стену
                VK.Api.call('wall.post', {owner_id: -123456789, from_group: 1, message: strippedText, attachments: 'http://www.site.ru/news/'+news_id}, function(r)
                {
                    //если пришел ответ - запись добавлена
                    if(r.response){
                        //сообщаем об успехе
                        alert("Запись успешно добавлена в группу ВКонтакте");
                        //и редиректим
                        redirectToMain();
                    }
                    //если ответ не пришел - репост отменен
                    else
                    {
                        //сообщаем об этом
                        alert("Запись в группу ВКонтакте отменена");
                        //редиректим
                        redirectToMain();
                    }
                });

                //если авторизации нет
            } else {
                //вызываем АПИ авторизации, и делаем рекурсию
                VK.Auth.login(authInfo);
            }
        }
        //ну а коль барин не желает репостить запись
    }else{
        //просто посылаем его редиректом
        redirectToMain();
    }
}


It takes the text of the post when sent from the editor, cleans it from HTML tags and entities, and sends a request to the wall.post api. The send function is like this (don't kick who did it - xs):
function save_message(){
    $("#bg_form_div").css('display','block');
    params = {
        id_tape:id_tape,
        action:action,
        id_message:id_message
    };
    var fields = $('#mess_form').serializeArray();
    for (i in fields ) {
        params[fields [i].name] = fields [i].value;
    }
    if ($('#t_content')[0]){
        var txt = CKEDITOR.instances.t_content;
        params['t_content']=txt.getData();
    }
    if ($('#foto')[0]) params['file']=$('#foto')[0];
    params['is_cats']=a_cats;
    var message='';
    JsHttpRequest.query('message.ajax.php', params,function(result, errors) {
        $("#bg_form_div").css('display','none');
        if (result&&!result.success){

            $.each( result.messages, function(i,n){
                message+=n+"\n";
            });
            alert(message);
        }
        if (result&&result.success){
            $.each(result.messages, function(i,n){
                message+=n+"\n";
/////////////////////////////////////////////////////////////////////////////////////////////////
                var news_id=message.substring(0,message.indexOf(':'));
                $.when(alert(message)).done(postVK($("#t_content").text(), news_id, id_tape));
/////////////////////////////////////////////////////////////////////////////////////////////////
            });
        }
    },true);

}


slashes indicated the place in which he pushed the function of sending to VK. In fact, the function here simply sends data to a php file by Ajax, which loads everything into the database.

The problem itself:
when sending one text (for example, 2000 characters long) - VK accepts it without problems, and when sending another (for example, 3000 characters, or 1500 characters) - VK rejects and breaks the connection, but at the same time accepts the same text after trimming up to, for example, 500 characters. There are suspicions that this is due to the limitations of the GET method (8192 bytes), but I'm not entirely sure that 1k characters can take that much (CP-1251 file encoding)

What is this arcane magic and what spell to avoid it? Thank you!

PS: jQuery version 1.5 (no higher)

UPD:
passed the token received by the method to PHPImplicit Flow like this:
require './apivk/apivk.php';

$vk = new apivk;
if(!isset($_GET['auth']))
{
  $vk->oAuth();
}
elseif(isset($_GET['auth']) && !isset($_GET['access_token']))
{
?>
  <script 
    src="https://code.jquery.com/jquery-1.5.js" 
    integrity="sha256-NhPIl0e+Si1dwX9ELQpILaZleE4uWjkx+5ofw4+g+o0=" 
    crossorigin="anonymous">
  </script>
  <script type="text/javascript" >
      $(document).ready(function(){
      //получаем данные из адресной строки в виде объекта
      var pageHref=location;
      //преобразуем в строку
      var stroka =pageHref.toString();
      //находим выстригаем все данные от слова 'access_token='
      var get_data = stroka.substring(stroka.indexOf('access_token='), stroka.length);
      //редиректим с подстановкой полученной строки
      location.replace('?auth=true&'+get_data);
      });
  </script>

<?php
}
elseif(isset($_GET['access_token']) && isset($_GET['auth']))
{
  var_dump($_GET);
}


crutch, I understand. But it doesn't work either... When handling the received token, I get the same as with the token received according to the second scheme ( Authorization Code Flow ) :
{"error":{"error_code":15,"error_msg":"Access denied: no access to call this method","request_params":[{"key":"oauth","value":"1"},{"key":"method","value":"wall.post"}]}}


As long as there are no more ideas...

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question