From 7b8ff9fe7ca04799679ed935e0c8fbc8cdddeee6 Mon Sep 17 00:00:00 2001 From: Pierre-Lin Bonnemaison Date: Tue, 22 Sep 2015 16:04:41 +0200 Subject: [PATCH 1/8] =?UTF-8?q?Ajout=20du=20m=C3=A9canisme=20SMS=20STOP=20?= =?UTF-8?q?pour=20bloquer=20les=20SMS.=20Mise=20en=20place=20de=20la=20con?= =?UTF-8?q?figuration=20et=20repercussion=20sur=20les=20scripts=20d'envoi?= =?UTF-8?q?=20et=20de=20reception?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/internalConsole.php | 27 ++++++++++ controllers/settings.php | 42 ++++++++++++++- controllers/smsstop.php | 49 ++++++++++++++++++ createDatabase.sql | 11 +++- templates/internalIncs/nav.php | 3 ++ templates/settings/default.php | 19 +++++++ templates/smsstop/default.php | 91 +++++++++++++++++++++++++++++++++ 7 files changed, 240 insertions(+), 2 deletions(-) create mode 100755 controllers/smsstop.php create mode 100755 templates/smsstop/default.php diff --git a/controllers/internalConsole.php b/controllers/internalConsole.php index a81f383..cd14c54 100755 --- a/controllers/internalConsole.php +++ b/controllers/internalConsole.php @@ -131,9 +131,26 @@ $numbers[] = $contact['number']; } } + + $smsStops = $db->getFromTableWhere('sms_stop'); foreach ($numbers as $number) { + //Si les SMS STOP sont activés, on passe au numéro suivant si le numéro actuelle fait parti des SMS STOP + if (RASPISMS_SETTINGS_SMS_STOP) + { + foreach ($smsStops as $smsStop) + { + if (!($number == $smsStop['number'])) + { + continue; + } + + echo "Un SMS destiné au " . $number . " a été bloqué par SMS STOP\n"; + continue(2); //On passe au numéro suivant ! + } + } + echo " Envoi d'un SMS au " . $number . "\n"; //On ajoute le SMS aux SMS envoyés //Pour plus de précision, on remet la date à jour en réinstanciant l'objet DateTime (et on reformatte la date, bien entendu) @@ -183,6 +200,8 @@ continue; } + echo "Analyse du SMS " . $dir . "\n"; + //On récupère la date du SMS à la seconde près grâce au nom du fichier (Cf. parseSMS.sh) //Il faut mettre la date au format Y-m-d H:i:s $date = substr($dir, 0, 4) . '-' . substr($dir, 4, 2) . '-' . substr($dir, 6, 2) . ' ' . substr($dir, 8, 2) . ':' . substr($dir, 10, 2) . ':' . substr($dir, 12, 2); @@ -217,6 +236,14 @@ $number = internalTools::parsePhone($number); $text = $content_file[1]; + //On gère les SMS STOP + if (trim($text) == 'STOP') + { + echo 'STOP SMS detected ' . $number; + $this->wlog('STOP SMS detected ' . $number); + $db->insertIntoTable('sms_stop', ['number' => $number]); + continue; + } if (!$number) { diff --git a/controllers/settings.php b/controllers/settings.php index b95643c..f79cec8 100755 --- a/controllers/settings.php +++ b/controllers/settings.php @@ -30,7 +30,7 @@ /** * Cette fonction permet de mettre à jour l'activation ou la désactivation du transfer des SMS * @param $csrf : Le jeton CSRF - * @param string $_POST['transfer'] : Le nouveau transfer de l'utilisateur + * @param string $_POST['transfer'] : Le nouveau transfer * @return void; */ public function changeTransfer($csrf) @@ -66,4 +66,44 @@ header('Location: ' . $this->generateUrl('settings')); return true; } + + /** + * Cette fonction permet de mettre à jour l'activation ou la désactivation de SMS-STOP + * @param $csrf : Le jeton CSRF + * @param string $_POST['stop'] : Le nouveau stop + * @return void; + */ + public function changeSmsStop($csrf) + { + //On vérifie que le jeton csrf est bon + if (!internalTools::verifyCSRF($csrf)) + { + $_SESSION['errormessage'] = 'Jeton CSRF invalide !'; + header('Location: ' . $this->generateUrl('settings')); + return false; + } + + //Creation de l'object de base de données + global $db; + + if (!isset($_POST['sms_stop'])) + { + $_SESSION['errormessage'] = 'Vous devez renseigner un valeur'; + header('Location: ' . $this->generateUrl('settings')); + return false; + } + + $stop = (int)$_POST['sms_stop']; + + if (!$db->updateTableWhere('settings', ['value' => $stop], ['name' => 'sms_stop'])) + { + $_SESSION['errormessage'] = 'Impossible de mettre les données à jour.'; + header('Location: ' . $this->generateUrl('settings')); + return false; + } + + $_SESSION['successmessage'] = 'Les données ont été mises à jour.'; + header('Location: ' . $this->generateUrl('settings')); + return true; + } } diff --git a/controllers/smsstop.php b/controllers/smsstop.php new file mode 100755 index 0000000..e690075 --- /dev/null +++ b/controllers/smsstop.php @@ -0,0 +1,49 @@ +showAll(); + } + + /** + * Cette fonction retourne tous les numéros sous sms stop, sous forme d'un tableau permettant l'administration de ces numéros + * @param int $page : La page à consulter. Par défaut 0 + * @return void; + */ + public function showAll($page = 0) + { + //Creation de l'object de base de données + global $db; + + $page = (int)($page < 0 ? $page = 0 : $page); + $limit = 25; + $offset = $limit * $page; + + //Récupération des sms-stop, par paquets de $limit, en ignorant les $offset premiers + $smsStops = $db->getFromTableWhere('sms_stop', [], false, true, $limit, $offset); + + $this->render('smsstop/default', array( + 'smsStops' => $smsStops, + 'page' => $page, + 'limit' => $limit, + 'nbResults' => count($smsStops), + )); + } + } diff --git a/createDatabase.sql b/createDatabase.sql index 9d0d114..31f72a3 100755 --- a/createDatabase.sql +++ b/createDatabase.sql @@ -135,6 +135,15 @@ CREATE TABLE IF NOT EXISTS transfers FOREIGN KEY (id_received) REFERENCES receiveds (id) ON DELETE CASCADE ON UPDATE CASCADE ); +CREATE TABLE IF NOT EXISTS sms_stop +( + id INT NOT NULL AUTO_INCREMENT, + number VARCHAR(12) NOT NULL, + PRIMARY KEY (id), + UNIQUE (number) +); + #On insert les données par défaut dans les settings INSERT INTO settings (name, value) -VALUES ('transfer', '1'); +VALUES ('transfer', '1'), +VALUES ('sms_stop', '1'); diff --git a/templates/internalIncs/nav.php b/templates/internalIncs/nav.php index bd57133..024226d 100755 --- a/templates/internalIncs/nav.php +++ b/templates/internalIncs/nav.php @@ -60,6 +60,9 @@
  • > SMS reçus
  • +
  • > + SMS STOP +
  • > Évènements
  • diff --git a/templates/settings/default.php b/templates/settings/default.php index c0643b0..66b9350 100755 --- a/templates/settings/default.php +++ b/templates/settings/default.php @@ -56,6 +56,25 @@
    +
    +
    +

    Activation de SMS-STOP

    +
    +
    +
    +
    + + +
    +
    + +
    +
    +
    +
    diff --git a/templates/smsstop/default.php b/templates/smsstop/default.php new file mode 100755 index 0000000..bb5c36c --- /dev/null +++ b/templates/smsstop/default.php @@ -0,0 +1,91 @@ +head('SMS STOP - Show All'); +?> +
    +nav('smsstop'); +?> +
    +
    + +
    +
    +

    + Dashboard SMS STOP +

    + +
    +
    + + +
    +
    +
    +
    +

    Liste SMS STOP

    +
    +
    +
    + + + + + + + + + + + + + + + +
    #Numéro
    +
    + +
    +
    +
    +
    +
    +
    +
    + +footer(); From b74856d50e75f4776417a423e0419fb707f21b3f Mon Sep 17 00:00:00 2001 From: Pierre-Lin Bonnemaison Date: Tue, 22 Sep 2015 16:13:54 +0200 Subject: [PATCH 2/8] =?UTF-8?q?Ajout=20d'un=20avertissement=20pour=20conse?= =?UTF-8?q?iller=20l'utilisation=20des=20num=C3=A9ros=20internationaux?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- css/style.css | 10 ++++++++++ templates/contacts/add.php | 2 +- templates/contacts/edit.php | 2 +- templates/scheduleds/add.php | 2 +- templates/scheduleds/edit.php | 2 +- 5 files changed, 14 insertions(+), 4 deletions(-) diff --git a/css/style.css b/css/style.css index a7df0e9..9e320a7 100755 --- a/css/style.css +++ b/css/style.css @@ -8,6 +8,16 @@ padding: 0 !important; } +.small-text +{ + font-size: 0.7em; +} + +.italic +{ + font-style: italic; +} + /** POPUPS ALERT **/ .popup-alerts-container { diff --git a/templates/contacts/add.php b/templates/contacts/add.php index 517c3a0..bb81c8e 100755 --- a/templates/contacts/add.php +++ b/templates/contacts/add.php @@ -46,7 +46,7 @@
    - +
    diff --git a/templates/contacts/edit.php b/templates/contacts/edit.php index 90b151d..b52b171 100755 --- a/templates/contacts/edit.php +++ b/templates/contacts/edit.php @@ -50,7 +50,7 @@
    - +
    diff --git a/templates/scheduleds/add.php b/templates/scheduleds/add.php index 8eb838a..ffe1906 100755 --- a/templates/scheduleds/add.php +++ b/templates/scheduleds/add.php @@ -47,7 +47,7 @@
    - +
    diff --git a/templates/scheduleds/edit.php b/templates/scheduleds/edit.php index 5a0cc8a..0534e30 100755 --- a/templates/scheduleds/edit.php +++ b/templates/scheduleds/edit.php @@ -72,7 +72,7 @@
    - +
    From 44312ca7f03250f2d765612f6cceef8aae3d0199 Mon Sep 17 00:00:00 2001 From: Pierre-Lin Bonnemaison Date: Tue, 22 Sep 2015 16:35:33 +0200 Subject: [PATCH 3/8] Ajout de la detection des liens dans les sms --- js/Autolinker.min.js | 10 ++++++++++ templates/discussions/show.php | 3 +++ templates/internalIncs/head.php | 1 + 3 files changed, 14 insertions(+) create mode 100644 js/Autolinker.min.js diff --git a/js/Autolinker.min.js b/js/Autolinker.min.js new file mode 100644 index 0000000..1ae6d41 --- /dev/null +++ b/js/Autolinker.min.js @@ -0,0 +1,10 @@ +/*! + * Autolinker.js + * 0.18.1 + * + * Copyright(c) 2015 Gregory Jacobs + * MIT Licensed. http://www.opensource.org/licenses/mit-license.php + * + * https://github.com/gregjacobs/Autolinker.js + */ +!function(a,b){"function"==typeof define&&define.amd?define([],function(){return a.Autolinker=b()}):"object"==typeof exports?module.exports=b():a.Autolinker=b()}(this,function(){var a=function(b){a.Util.assign(this,b);var c=this.hashtag;if(c!==!1&&"twitter"!==c&&"facebook"!==c)throw new Error("invalid `hashtag` cfg - see docs")};return a.prototype={constructor:a,urls:!0,email:!0,twitter:!0,phone:!0,hashtag:!1,newWindow:!0,stripPrefix:!0,truncate:void 0,className:"",htmlParser:void 0,matchParser:void 0,tagBuilder:void 0,link:function(a){if(!a)return"";for(var b=this.getHtmlParser(),c=b.parse(a),d=0,e=[],f=0,g=c.length;g>f;f++){var h=c[f],i=h.getType(),j=h.getText();if("element"===i)"a"===h.getTagName()&&(h.isClosing()?d=Math.max(d-1,0):d++),e.push(j);else if("entity"===i||"comment"===i)e.push(j);else if(0===d){var k=this.linkifyStr(j);e.push(k)}else e.push(j)}return e.join("")},linkifyStr:function(a){return this.getMatchParser().replace(a,this.createMatchReturnVal,this)},createMatchReturnVal:function(b){var c;if(this.replaceFn&&(c=this.replaceFn.call(this,this,b)),"string"==typeof c)return c;if(c===!1)return b.getMatchedText();if(c instanceof a.HtmlTag)return c.toAnchorString();var d=this.getTagBuilder(),e=d.build(b);return e.toAnchorString()},getHtmlParser:function(){var b=this.htmlParser;return b||(b=this.htmlParser=new a.htmlParser.HtmlParser),b},getMatchParser:function(){var b=this.matchParser;return b||(b=this.matchParser=new a.matchParser.MatchParser({urls:this.urls,email:this.email,twitter:this.twitter,phone:this.phone,hashtag:this.hashtag,stripPrefix:this.stripPrefix})),b},getTagBuilder:function(){var b=this.tagBuilder;return b||(b=this.tagBuilder=new a.AnchorTagBuilder({newWindow:this.newWindow,truncate:this.truncate,className:this.className})),b}},a.link=function(b,c){var d=new a(c);return d.link(b)},a.match={},a.htmlParser={},a.matchParser={},a.Util={abstractMethod:function(){throw"abstract"},trimRegex:/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,assign:function(a,b){for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a},extend:function(b,c){var d=b.prototype,e=function(){};e.prototype=d;var f;f=c.hasOwnProperty("constructor")?c.constructor:function(){d.constructor.apply(this,arguments)};var g=f.prototype=new e;return g.constructor=f,g.superclass=d,delete c.constructor,a.Util.assign(g,c),f},ellipsis:function(a,b,c){return a.length>b&&(c=null==c?"..":c,a=a.substring(0,b-c.length)+c),a},indexOf:function(a,b){if(Array.prototype.indexOf)return a.indexOf(b);for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},splitAndCapture:function(a,b){if(!b.global)throw new Error("`splitRegex` must have the 'g' flag set");for(var c,d=[],e=0;c=b.exec(a);)d.push(a.substring(e,c.index)),d.push(c[0]),e=c.index+c[0].length;return d.push(a.substring(e)),d},trim:function(a){return a.replace(this.trimRegex,"")}},a.HtmlTag=a.Util.extend(Object,{whitespaceRegex:/\s+/,constructor:function(b){a.Util.assign(this,b),this.innerHtml=this.innerHtml||this.innerHTML},setTagName:function(a){return this.tagName=a,this},getTagName:function(){return this.tagName||""},setAttr:function(a,b){var c=this.getAttrs();return c[a]=b,this},getAttr:function(a){return this.getAttrs()[a]},setAttrs:function(b){var c=this.getAttrs();return a.Util.assign(c,b),this},getAttrs:function(){return this.attrs||(this.attrs={})},setClass:function(a){return this.setAttr("class",a)},addClass:function(b){for(var c,d=this.getClass(),e=this.whitespaceRegex,f=a.Util.indexOf,g=d?d.split(e):[],h=b.split(e);c=h.shift();)-1===f(g,c)&&g.push(c);return this.getAttrs()["class"]=g.join(" "),this},removeClass:function(b){for(var c,d=this.getClass(),e=this.whitespaceRegex,f=a.Util.indexOf,g=d?d.split(e):[],h=b.split(e);g.length&&(c=h.shift());){var i=f(g,c);-1!==i&&g.splice(i,1)}return this.getAttrs()["class"]=g.join(" "),this},getClass:function(){return this.getAttrs()["class"]||""},hasClass:function(a){return-1!==(" "+this.getClass()+" ").indexOf(" "+a+" ")},setInnerHtml:function(a){return this.innerHtml=a,this},getInnerHtml:function(){return this.innerHtml||""},toAnchorString:function(){var a=this.getTagName(),b=this.buildAttrsStr();return b=b?" "+b:"",["<",a,b,">",this.getInnerHtml(),""].join("")},buildAttrsStr:function(){if(!this.attrs)return"";var a=this.getAttrs(),b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c+'="'+a[c]+'"');return b.join(" ")}}),a.AnchorTagBuilder=a.Util.extend(Object,{constructor:function(b){a.Util.assign(this,b)},build:function(b){var c=new a.HtmlTag({tagName:"a",attrs:this.createAttrs(b.getType(),b.getAnchorHref()),innerHtml:this.processAnchorText(b.getAnchorText())});return c},createAttrs:function(a,b){var c={href:b},d=this.createCssClass(a);return d&&(c["class"]=d),this.newWindow&&(c.target="_blank"),c},createCssClass:function(a){var b=this.className;return b?b+" "+b+"-"+a:""},processAnchorText:function(a){return a=this.doTruncate(a)},doTruncate:function(b){return a.Util.ellipsis(b,this.truncate||Number.POSITIVE_INFINITY)}}),a.htmlParser.HtmlParser=a.Util.extend(Object,{htmlRegex:function(){var a=/!--([\s\S]+?)--/,b=/[0-9a-zA-Z][0-9a-zA-Z:]*/,c=/[^\s\0"'>\/=\x01-\x1F\x7F]+/,d=/(?:"[^"]*?"|'[^']*?'|[^'"=<>`\s]+)/,e=c.source+"(?:\\s*=\\s*"+d.source+")?";return new RegExp(["(?:","<(!DOCTYPE)","(?:","\\s+","(?:",e,"|",d.source+")",")*",">",")","|","(?:","<(/)?","(?:",a.source,"|","(?:","("+b.source+")","(?:","\\s+",e,")*","\\s*/?",")",")",">",")"].join(""),"gi")}(),htmlCharacterEntitiesRegex:/( | |<|<|>|>|"|"|')/gi,parse:function(a){for(var b,c,d=this.htmlRegex,e=0,f=[];null!==(b=d.exec(a));){var g=b[0],h=b[3],i=b[1]||b[4],j=!!b[2],k=a.substring(e,b.index);k&&(c=this.parseTextAndEntityNodes(k),f.push.apply(f,c)),f.push(h?this.createCommentNode(g,h):this.createElementNode(g,i,j)),e=b.index+g.length}if(ee;e+=2){var g=d[e],h=d[e+1];g&&c.push(this.createTextNode(g)),h&&c.push(this.createEntityNode(h))}return c},createCommentNode:function(b,c){return new a.htmlParser.CommentNode({text:b,comment:a.Util.trim(c)})},createElementNode:function(b,c,d){return new a.htmlParser.ElementNode({text:b,tagName:c.toLowerCase(),closing:d})},createEntityNode:function(b){return new a.htmlParser.EntityNode({text:b})},createTextNode:function(b){return new a.htmlParser.TextNode({text:b})}}),a.htmlParser.HtmlNode=a.Util.extend(Object,{text:"",constructor:function(b){a.Util.assign(this,b)},getType:a.Util.abstractMethod,getText:function(){return this.text}}),a.htmlParser.CommentNode=a.Util.extend(a.htmlParser.HtmlNode,{comment:"",getType:function(){return"comment"},getComment:function(){return this.comment}}),a.htmlParser.ElementNode=a.Util.extend(a.htmlParser.HtmlNode,{tagName:"",closing:!1,getType:function(){return"element"},getTagName:function(){return this.tagName},isClosing:function(){return this.closing}}),a.htmlParser.EntityNode=a.Util.extend(a.htmlParser.HtmlNode,{getType:function(){return"entity"}}),a.htmlParser.TextNode=a.Util.extend(a.htmlParser.HtmlNode,{getType:function(){return"text"}}),a.matchParser.MatchParser=a.Util.extend(Object,{urls:!0,email:!0,twitter:!0,phone:!0,hashtag:!1,stripPrefix:!0,matcherRegex:function(){var a=/(^|[^\w])@(\w{1,15})/,b=/(^|[^\w])#(\w{1,139})/,c=/(?:[\-;:&=\+\$,\w\.]+@)/,d=/(?:\+?\d{1,3}[-\s.])?\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/,e=/(?:[A-Za-z][-.+A-Za-z0-9]+:(?![A-Za-z][-.+A-Za-z0-9]+:\/\/)(?!\d+\/?)(?:\/\/)?)/,f=/(?:www\.)/,g=/[A-Za-z0-9\.\-]*[A-Za-z0-9\-]/,h=/\.(?:international|construction|contractors|enterprises|photography|productions|foundation|immobilien|industries|management|properties|technology|christmas|community|directory|education|equipment|institute|marketing|solutions|vacations|bargains|boutique|builders|catering|cleaning|clothing|computer|democrat|diamonds|graphics|holdings|lighting|partners|plumbing|supplies|training|ventures|academy|careers|company|cruises|domains|exposed|flights|florist|gallery|guitars|holiday|kitchen|neustar|okinawa|recipes|rentals|reviews|shiksha|singles|support|systems|agency|berlin|camera|center|coffee|condos|dating|estate|events|expert|futbol|kaufen|luxury|maison|monash|museum|nagoya|photos|repair|report|social|supply|tattoo|tienda|travel|viajes|villas|vision|voting|voyage|actor|build|cards|cheap|codes|dance|email|glass|house|mango|ninja|parts|photo|shoes|solar|today|tokyo|tools|watch|works|aero|arpa|asia|best|bike|blue|buzz|camp|club|cool|coop|farm|fish|gift|guru|info|jobs|kiwi|kred|land|limo|link|menu|mobi|moda|name|pics|pink|post|qpon|rich|ruhr|sexy|tips|vote|voto|wang|wien|wiki|zone|bar|bid|biz|cab|cat|ceo|com|edu|gov|int|kim|mil|net|onl|org|pro|pub|red|tel|uno|wed|xxx|xyz|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw)\b/,i=/[\-A-Za-z0-9+&@#\/%=~_()|'$*\[\]?!:,.;]*[\-A-Za-z0-9+&@#\/%=~_()|'$*\[\]]/;return new RegExp(["(",a.source,")","|","(",c.source,g.source,h.source,")","|","(","(?:","(",e.source,g.source,")","|","(?:","(.?//)?",f.source,g.source,")","|","(?:","(.?//)?",g.source,h.source,")",")","(?:"+i.source+")?",")","|","(",d.source,")","|","(",b.source,")"].join(""),"gi")}(),charBeforeProtocolRelMatchRegex:/^(.)?\/\//,constructor:function(b){a.Util.assign(this,b),this.matchValidator=new a.MatchValidator},replace:function(a,b,c){var d=this;return a.replace(this.matcherRegex,function(a,e,f,g,h,i,j,k,l,m,n,o,p){var q=d.processCandidateMatch(a,e,f,g,h,i,j,k,l,m,n,o,p);if(q){var r=b.call(c,q.match);return q.prefixStr+r+q.suffixStr}return a})},processCandidateMatch:function(b,c,d,e,f,g,h,i,j,k,l,m,n){var o,p=i||j,q="",r="";if(g&&!this.urls||f&&!this.email||k&&!this.phone||c&&!this.twitter||l&&!this.hashtag||!this.matchValidator.isValidMatch(g,h,p))return null;if(this.matchHasUnbalancedClosingParen(b))b=b.substr(0,b.length-1),r=")";else{var s=this.matchHasInvalidCharAfterTld(g,h);s>-1&&(r=b.substr(s),b=b.substr(0,s))}if(f)o=new a.match.Email({matchedText:b,email:f});else if(c)d&&(q=d,b=b.slice(1)),o=new a.match.Twitter({matchedText:b,twitterHandle:e});else if(k){var t=b.replace(/\D/g,"");o=new a.match.Phone({matchedText:b,number:t})}else if(l)m&&(q=m,b=b.slice(1)),o=new a.match.Hashtag({matchedText:b,serviceName:this.hashtag,hashtag:n});else{if(p){var u=p.match(this.charBeforeProtocolRelMatchRegex)[1]||"";u&&(q=u,b=b.slice(1))}o=new a.match.Url({matchedText:b,url:b,protocolUrlMatch:!!h,protocolRelativeMatch:!!p,stripPrefix:this.stripPrefix})}return{prefixStr:q,suffixStr:r,match:o}},matchHasUnbalancedClosingParen:function(a){var b=a.charAt(a.length-1);if(")"===b){var c=a.match(/\(/g),d=a.match(/\)/g),e=c&&c.length||0,f=d&&d.length||0;if(f>e)return!0}return!1},matchHasInvalidCharAfterTld:function(a,b){if(!a)return-1;var c=0;b&&(c=a.indexOf(":"),a=a.slice(c));var d=/^((.?\/\/)?[A-Za-z0-9\.\-]*[A-Za-z0-9\-]\.[A-Za-z]+)/,e=d.exec(a);return null===e?-1:(c+=e[1].length,a=a.slice(e[1].length),/^[^.A-Za-z:\/?#]/.test(a)?c:-1)}}),a.MatchValidator=a.Util.extend(Object,{invalidProtocolRelMatchRegex:/^[\w]\/\//,hasFullProtocolRegex:/^[A-Za-z][-.+A-Za-z0-9]+:\/\//,uriSchemeRegex:/^[A-Za-z][-.+A-Za-z0-9]+:/,hasWordCharAfterProtocolRegex:/:[^\s]*?[A-Za-z]/,isValidMatch:function(a,b,c){return b&&!this.isValidUriScheme(b)||this.urlMatchDoesNotHaveProtocolOrDot(a,b)||this.urlMatchDoesNotHaveAtLeastOneWordChar(a,b)||this.isInvalidProtocolRelativeMatch(c)?!1:!0},isValidUriScheme:function(a){var b=a.match(this.uriSchemeRegex)[0].toLowerCase();return"javascript:"!==b&&"vbscript:"!==b},urlMatchDoesNotHaveProtocolOrDot:function(a,b){return!(!a||b&&this.hasFullProtocolRegex.test(b)||-1!==a.indexOf("."))},urlMatchDoesNotHaveAtLeastOneWordChar:function(a,b){return a&&b?!this.hasWordCharAfterProtocolRegex.test(a):!1},isInvalidProtocolRelativeMatch:function(a){return!!a&&this.invalidProtocolRelMatchRegex.test(a)}}),a.match.Match=a.Util.extend(Object,{constructor:function(b){a.Util.assign(this,b)},getType:a.Util.abstractMethod,getMatchedText:function(){return this.matchedText},getAnchorHref:a.Util.abstractMethod,getAnchorText:a.Util.abstractMethod}),a.match.Email=a.Util.extend(a.match.Match,{getType:function(){return"email"},getEmail:function(){return this.email},getAnchorHref:function(){return"mailto:"+this.email},getAnchorText:function(){return this.email}}),a.match.Hashtag=a.Util.extend(a.match.Match,{getType:function(){return"hashtag"},getHashtag:function(){return this.hashtag},getAnchorHref:function(){var a=this.serviceName,b=this.hashtag;switch(a){case"twitter":return"https://twitter.com/hashtag/"+b;case"facebook":return"https://www.facebook.com/hashtag/"+b;default:throw new Error("Unknown service name to point hashtag to: ",a)}},getAnchorText:function(){return"#"+this.hashtag}}),a.match.Phone=a.Util.extend(a.match.Match,{getType:function(){return"phone"},getNumber:function(){return this.number},getAnchorHref:function(){return"tel:"+this.number},getAnchorText:function(){return this.matchedText}}),a.match.Twitter=a.Util.extend(a.match.Match,{getType:function(){return"twitter"},getTwitterHandle:function(){return this.twitterHandle},getAnchorHref:function(){return"https://twitter.com/"+this.twitterHandle},getAnchorText:function(){return"@"+this.twitterHandle}}),a.match.Url=a.Util.extend(a.match.Match,{urlPrefixRegex:/^(https?:\/\/)?(www\.)?/i,protocolRelativeRegex:/^\/\//,protocolPrepended:!1,getType:function(){return"url"},getUrl:function(){var a=this.url;return this.protocolRelativeMatch||this.protocolUrlMatch||this.protocolPrepended||(a=this.url="http://"+a,this.protocolPrepended=!0),a},getAnchorHref:function(){var a=this.getUrl();return a.replace(/&/g,"&")},getAnchorText:function(){var a=this.getUrl();return this.protocolRelativeMatch&&(a=this.stripProtocolRelativePrefix(a)),this.stripPrefix&&(a=this.stripUrlPrefix(a)),a=this.removeTrailingSlash(a)},stripUrlPrefix:function(a){return a.replace(this.urlPrefixRegex,"")},stripProtocolRelativePrefix:function(a){return a.replace(this.protocolRelativeRegex,"")},removeTrailingSlash:function(a){return"/"===a.charAt(a.length-1)&&(a=a.slice(0,-1)),a}}),a}); \ No newline at end of file diff --git a/templates/discussions/show.php b/templates/discussions/show.php index 519bf12..1fa2a8c 100755 --- a/templates/discussions/show.php +++ b/templates/discussions/show.php @@ -65,6 +65,9 @@ $.each(data.messages, function(key, message) { + //On ajoute la detection de lien dans le texte du message + message.text = Autolinker.link(message.text, {newWindow:true}); + switch (message.type) { case 'received' : diff --git a/templates/internalIncs/head.php b/templates/internalIncs/head.php index b4d3a7a..eea63b3 100755 --- a/templates/internalIncs/head.php +++ b/templates/internalIncs/head.php @@ -23,6 +23,7 @@ + From 0625d93f8ecbd4c4a3268153d2a54d36778b209b Mon Sep 17 00:00:00 2001 From: Pierre-Lin Bonnemaison Date: Tue, 22 Sep 2015 16:50:52 +0200 Subject: [PATCH 4/8] Ajout des reglages pour la detection d'url dans les discussions --- controllers/settings.php | 40 ++++++++++++++++++++++++++++++++++ createDatabase.sql | 3 ++- templates/discussions/show.php | 6 +++-- templates/settings/default.php | 19 ++++++++++++++++ 4 files changed, 65 insertions(+), 3 deletions(-) diff --git a/controllers/settings.php b/controllers/settings.php index f79cec8..df1757d 100755 --- a/controllers/settings.php +++ b/controllers/settings.php @@ -106,4 +106,44 @@ header('Location: ' . $this->generateUrl('settings')); return true; } + + /** + * Cette fonction permet de mettre à jour l'activation ou la désactivation de la detection d'URL dans les discussions + * @param $csrf : Le jeton CSRF + * @param string $_POST['detect_url'] : Le nouveau stop + * @return void; + */ + public function changeDetectionUrl($csrf) + { + //On vérifie que le jeton csrf est bon + if (!internalTools::verifyCSRF($csrf)) + { + $_SESSION['errormessage'] = 'Jeton CSRF invalide !'; + header('Location: ' . $this->generateUrl('settings')); + return false; + } + + //Creation de l'object de base de données + global $db; + + if (!isset($_POST['detect_url'])) + { + $_SESSION['errormessage'] = 'Vous devez renseigner un valeur'; + header('Location: ' . $this->generateUrl('settings')); + return false; + } + + $detectUrl = (int)$_POST['detect_url']; + + if (!$db->updateTableWhere('settings', ['value' => $detectUrl], ['name' => 'detect_url'])) + { + $_SESSION['errormessage'] = 'Impossible de mettre les données à jour.'; + header('Location: ' . $this->generateUrl('settings')); + return false; + } + + $_SESSION['successmessage'] = 'Les données ont été mises à jour.'; + header('Location: ' . $this->generateUrl('settings')); + return true; + } } diff --git a/createDatabase.sql b/createDatabase.sql index 31f72a3..aeecfe6 100755 --- a/createDatabase.sql +++ b/createDatabase.sql @@ -146,4 +146,5 @@ CREATE TABLE IF NOT EXISTS sms_stop #On insert les données par défaut dans les settings INSERT INTO settings (name, value) VALUES ('transfer', '1'), -VALUES ('sms_stop', '1'); +('sms_stop', '1'), +('detect_url', '1'); diff --git a/templates/discussions/show.php b/templates/discussions/show.php index 1fa2a8c..5222b1d 100755 --- a/templates/discussions/show.php +++ b/templates/discussions/show.php @@ -65,8 +65,10 @@ $.each(data.messages, function(key, message) { - //On ajoute la detection de lien dans le texte du message - message.text = Autolinker.link(message.text, {newWindow:true}); + + //On ajoute la detection de lien dans le texte du message + message.text = Autolinker.link(message.text, {newWindow:true}); + switch (message.type) { diff --git a/templates/settings/default.php b/templates/settings/default.php index 66b9350..f7ae82f 100755 --- a/templates/settings/default.php +++ b/templates/settings/default.php @@ -54,6 +54,25 @@
    +
    +
    +

    Détection des URL dans les discussions

    +
    +
    +
    +
    + + +
    +
    + +
    +
    +
    +
    From 469e2fce59b76507f36569a5df47a6fa1550d224 Mon Sep 17 00:00:00 2001 From: Pierre-Lin Bonnemaison Date: Tue, 22 Sep 2015 20:12:42 +0200 Subject: [PATCH 5/8] =?UTF-8?q?Mise=20=C3=A0=20jour=20du=20mod=C3=A8le=20v?= =?UTF-8?q?ers=20la=20derni=C3=A8re=20version=20de=20Descartes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mvc/Model.php | 211 ++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 189 insertions(+), 22 deletions(-) diff --git a/mvc/Model.php b/mvc/Model.php index 428f203..15404be 100755 --- a/mvc/Model.php +++ b/mvc/Model.php @@ -131,9 +131,11 @@ foreach ($fields as $field) { $fieldInfo = array(); + $fieldInfo['NAME'] = $field['Field']; $fieldInfo['NULL'] = $field['Null'] == 'NO' ? false : true; $fieldInfo['AUTO_INCREMENT'] = $field['Extra'] == 'auto_increment' ? true : false; $fieldInfo['PRIMARY'] = $field['Key'] == 'PRI' ? true : false; + $fieldInfo['FOREIGN'] = $field['Key'] == 'MUL' ? true : false; $fieldInfo['UNIQUE'] = $field['Key'] == 'UNI' ? true : false; $fieldInfo['TYPE'] = mb_convert_case(preg_replace('#[^a-z]#ui', '', $field['Type']), MB_CASE_UPPER); $fieldInfo['SIZE'] = filter_var($field['Type'], FILTER_SANITIZE_NUMBER_INT); @@ -145,6 +147,53 @@ return $return; } + /** + * Cette finction retourne la table et le champs référent pour un champ avec une foreign key + * @param string $table : Le nom de la table qui contient le champ + * @param string $field : Le nom du champ + * @return mixed : False en cas d'erreur, un tableau avec 'table' en index pour la table et 'field' pour le champ + */ + public function getReferenceForForeign ($table, $field) + { + if (!$this->fieldExist($field, $table)) + { + return false; + } + + $query = 'SELECT referenced_table_name as table_name, referenced_column_name as field_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE table_name = :table AND column_name = :field AND referenced_table_name IS NOT NULL'; + + $params = array( + 'table' => $table, + 'field' => $field, + ); + + return $this->runQuery($query, $params, self::FETCH); + } + + /** + * Cette fonction retourne les valeurs possibles pour un champ muni d'une clef étrangère + * @param string $table : Le nom de la table qui contient le champ + * @param string $field : Le nom du champ + * @return mixed : Retourne les valeurs possible sous forme d'un tableau + */ + public function getPossibleValuesForForeign ($table, $field) + { + if (!$this->fieldExist($field, $table)) + { + return false; + } + + //On recupère le champs référence pour la foreign key + if (!$reference = $this->getReferenceForForeign($table, $field)) + { + return false; + } + + //On recupère les valeurs possible de la table + $query = 'SELECT DISTINCT ' . $reference['field_name'] . ' as possible_value FROM ' . $reference['table_name']; + return $this->runQuery($query); + } + /** * Cette fonction permet de compter le nombre de ligne d'une table * @param string $table : Le nom de la table à compter @@ -246,8 +295,8 @@ /** * Cette fonction permet de récupérer des lignes en fonction de restrictions * @param string $table : Le nom de la table dans laquelle on veux recuperer la ligne - * @param array $restrictions : Les restrictions que l'on veux appliquer - * @param string $order_by : Le nom de la colonne par laquelle on veux trier les résultats. Si non fourni, tri automatique + * @param array $restrictions : Les restrictions sous la forme "label" => "valeur". Un operateur '<, >, <=, >=, !' peux précder le label pour modifier l'opérateur par défaut (=) + * @param mixed $order_by : Le nom de la colonne par laquelle on veux trier les résultats ou son numero. Si non fourni, tri automatique * @param string $desc : L'ordre de tri (asc ou desc). Si non défini, ordre par défaut (ASC) * @param string $limit : Le nombre maximum de résultats à récupérer (par défaut pas le limite) * @param string $offset : Le nombre de résultats à ignorer (par défaut pas de résultats ignorés) @@ -266,27 +315,66 @@ //On gère les restrictions $wheres = array(); $params = array(); - + $i = 0; foreach ($restrictions as $label => $value) { + //Pour chaque restriction, on essaye de detecter un "! ou < ou > ou <= ou >=" + $first_char = mb_substr($label, 0, 1); + $second_char = mb_substr($label, 1, 1); + + switch(true) + { + //Important de traiter <= & >= avant < & > + case ('<=' == $first_char . $second_char) : + $trueLabel = mb_substr($label, 2); + $operator = '<='; + break; + + case ('>=' == $first_char . $second_char) : + $trueLabel = mb_substr($label, 2); + $operator = '>='; + break; + + case ('!' == $first_char) : + $trueLabel = mb_substr($label, 1); + $operator = '!='; + break; + + case ('<' == $first_char) : + $trueLabel = mb_substr($label, 1); + $operator = '<'; + break; + + case ('>' == $first_char) : + $trueLabel = mb_substr($label, 1); + $operator = '>'; + break; + + default : + $trueLabel = $label; + $operator = '='; + } + //Si le champs pour la restriction n'existe pas on retourne false - if (!array_key_exists($label, $fields)) + if (!array_key_exists($trueLabel, $fields)) { return false; } - + //On ajoute la restriction au WHERE - $params['where_' . $label] = $value; - $wheres[] = $label . ' = :where_' . $label . ' '; + $params['where_' . $trueLabel . $i] = $value; + $wheres[] = $trueLabel . ' ' . $operator . ' :where_' . $trueLabel . $i . ' '; + $i++; } - $query = "SELECT " . $this->getColumnsForTable($table) . " FROM " . $table . " WHERE 1 " . (count($wheres) ? 'AND ' : '') . implode('AND ', $wheres); + $query = "SELECT * FROM " . $table . " WHERE 1 " . (count($wheres) ? 'AND ' : '') . implode('AND ', $wheres); if ($order_by) { - if ($this->fieldExist($order_by, $table)) + //Si le champs existe ou si c'est un numeric inférieur ou egale au nombre de champs dispo + if (array_key_exists($order_by, $fields) || (is_numeric($order_by) && $order_by <= count($fields))) { - $query .= ' ORDER BY '. $order_by; + $query .= ' ORDER BY ' . $order_by; if ($desc) { $query .= ' DESC'; @@ -307,9 +395,11 @@ if ($limit !== false) { + $limit = (int)$limit; $req->bindParam(':limit', $limit, PDO::PARAM_INT); if ($offset !== false) { + $offset = (int)$offset; $req->bindParam(':offset', $offset, PDO::PARAM_INT); } } @@ -322,6 +412,7 @@ $req->setFetchMode(PDO::FETCH_ASSOC); $req->execute(); + return $req->fetchAll(); } @@ -330,7 +421,7 @@ * @param string $table : Le nom de la table dans laquelle on veux insérer des données * @param string $primary : La clef primaire qui sert à identifier la ligne a modifier * @param array $datas : Les données à insérer au format "champ" => "valeur" - * @param array $restrictions : Un tableau des restrictions à appliquer sous forme "champ" => "valeur". Par défaut un tableau vide + * @param array $restrictions : Les restrictions pour la mise à jour sous la forme "label" => "valeur". Un operateur '<, >, <=, >=, !' peux précder le label pour modifier l'opérateur par défaut (=) * @return mixed : False en cas d'erreur, sinon le nombre de lignes modifiées */ public function updateTableWhere ($table, $datas, $restrictions = array()) @@ -365,17 +456,56 @@ //On gère les restrictions $wheres = array(); + $i = 0; foreach ($restrictions as $label => $value) { + //Pour chaque restriction, on essaye de detecter un "! ou < ou > ou <= ou >=" + $first_char = mb_substr($label, 0, 1); + $second_char = mb_substr($label, 1, 1); + + switch(true) + { + //Important de traiter <= & >= avant < & > + case ('<=' == $first_char . $second_char) : + $trueLabel = mb_substr($label, 2); + $operator = '<='; + break; + + case ('>=' == $first_char . $second_char) : + $trueLabel = mb_substr($label, 2); + $operator = '>='; + break; + + case ('!' == $first_char) : + $trueLabel = mb_substr($label, 1); + $operator = '!='; + break; + + case ('<' == $first_char) : + $trueLabel = mb_substr($label, 1); + $operator = '<'; + break; + + case ('>' == $first_char) : + $trueLabel = mb_substr($label, 1); + $operator = '>'; + break; + + default : + $trueLabel = $label; + $operator = '='; + } + //Si le champs pour la restriction n'existe pas on retourne false - if (!array_key_exists($label, $fields)) + if (!array_key_exists($trueLabel, $fields)) { return false; } - + //On ajoute la restriction au WHERE - $params['where_' . $label] = $value; - $wheres[] = $label . ' = :where_' . $label . ' '; + $params['where_' . $trueLabel . $i] = $value; + $wheres[] = $trueLabel . ' ' . $operator . ' :where_' . $trueLabel . $i . ' '; + $i++; } //On fabrique la requete @@ -388,7 +518,7 @@ /** * Cette fonction permet de supprimer des lignes d'une table en fonctions de restrictions * @param string $table : Le nom de la table dans laquelle on veux supprimer la ligne - * @param array $restrictions : Les restrictions pour la suppression sous la forme "label" => "valeur" + * @param array $restrictions : Les restrictions pour la suppression sous la forme "label" => "valeur". Un operateur '<, >, <=, >=, !' peux précder le label pour modifier l'opérateur par défaut (=) * @return mixed : False en cas d'erreur, sinon le nombre de lignes supprimées */ public function deleteFromTableWhere($table, $restrictions = array()) @@ -403,22 +533,59 @@ //On gère les restrictions $wheres = array(); $params = array(); - + $i = 0; foreach ($restrictions as $label => $value) { + //Pour chaque restriction, on essaye de detecter un "! ou < ou > ou <= ou >=" + $first_char = mb_substr($label, 0, 1); + $second_char = mb_substr($label, 1, 1); + + switch(true) + { + //Important de traiter <= & >= avant < & > + case ('<=' == $first_char . $second_char) : + $trueLabel = mb_substr($label, 2); + $operator = '<='; + break; + + case ('>=' == $first_char . $second_char) : + $trueLabel = mb_substr($label, 2); + $operator = '>='; + break; + + case ('!' == $first_char) : + $trueLabel = mb_substr($label, 1); + $operator = '!='; + break; + + case ('<' == $first_char) : + $trueLabel = mb_substr($label, 1); + $operator = '<'; + break; + + case ('>' == $first_char) : + $trueLabel = mb_substr($label, 1); + $operator = '>'; + break; + + default : + $trueLabel = $label; + $operator = '='; + } + //Si le champs pour la restriction n'existe pas on retourne false - if (!array_key_exists($label, $fields)) + if (!array_key_exists($trueLabel, $fields)) { return false; } - + //On ajoute la restriction au WHERE - $params['where_' . $label] = $value; - $wheres[] = $label . ' = :where_' . $label . ' '; + $params['where_' . $trueLabel . $i] = $value; + $wheres[] = $trueLabel . ' ' . $operator . ' :where_' . $trueLabel . $i . ' '; + $i++; } $query = "DELETE FROM " . $table . " WHERE 1 AND " . implode('AND ', $wheres); - return $this->runQuery($query, $params, self::ROWCOUNT); } From 479b2c24427479f51ac494992b9e5a0012d86a95 Mon Sep 17 00:00:00 2001 From: Pierre-Lin Bonnemaison Date: Tue, 22 Sep 2015 20:12:59 +0200 Subject: [PATCH 6/8] =?UTF-8?q?Ajout=20des=20accus=C3=A9s=20de=20reception?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/discussions.php | 1 + controllers/internalConsole.php | 23 ++++++++++++++++++++++- createDatabase.sql | 1 + templates/discussions/show.php | 2 +- templates/sendeds/showAll.php | 2 ++ 5 files changed, 27 insertions(+), 2 deletions(-) diff --git a/controllers/discussions.php b/controllers/discussions.php index d1be75c..127b0da 100755 --- a/controllers/discussions.php +++ b/controllers/discussions.php @@ -85,6 +85,7 @@ 'date' => htmlspecialchars($sended['at']), 'text' => htmlspecialchars($sended['content']), 'type' => 'sended', + 'delivered' => ($sended['delivered'] ? true : false), ); } diff --git a/controllers/internalConsole.php b/controllers/internalConsole.php index cd14c54..a0afaf1 100755 --- a/controllers/internalConsole.php +++ b/controllers/internalConsole.php @@ -239,12 +239,33 @@ //On gère les SMS STOP if (trim($text) == 'STOP') { - echo 'STOP SMS detected ' . $number; + echo 'STOP SMS detected ' . $number . "\n"; $this->wlog('STOP SMS detected ' . $number); $db->insertIntoTable('sms_stop', ['number' => $number]); continue; } + //On gère les accusés de reception + if (trim($text) == 'Delivered') + { + echo 'Delivered SMS for ' . $number . "\n"; + $this->wlog('Delivered SMS for ' . $number); + + //On récupère les SMS par encore validé, uniquement sur les dernières 24h + $now = new DateTime(); + $interval = new DateInterval('P1D'); + $sinceDate = $now->sub($interval)->format('Y-m-d H:i:s'); + + if (!$sendeds = $db->getFromTableWhere('sendeds', ['target' => $number, 'delivered' => false, '>at' => $sinceDate], 'at', false, 1)) + { + continue; + } + + $db->updateTableWhere('sendeds', ['delivered' => true], ['id' => $sendeds[0]['id']]); + echo "Sended SMS id " . $sendeds[0]['id'] . " to delivered status\n"; + continue; + } + if (!$number) { $this->wlog('Invalid phone number in file "' . $dir); diff --git a/createDatabase.sql b/createDatabase.sql index aeecfe6..2586787 100755 --- a/createDatabase.sql +++ b/createDatabase.sql @@ -27,6 +27,7 @@ CREATE TABLE IF NOT EXISTS sendeds at DATETIME NOT NULL, target VARCHAR(12) NOT NULL, content VARCHAR(1000) NOT NULL, + delivered BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (id) ); diff --git a/templates/discussions/show.php b/templates/discussions/show.php index 5222b1d..4ec68ba 100755 --- a/templates/discussions/show.php +++ b/templates/discussions/show.php @@ -86,7 +86,7 @@ '
    ' + '
    ' + '
    ' + message.text + '
    ' + - '
    ' + message.date + '
    ' + + '
    ' + message.date + (message.delivered ? ' ' : '' ) + '
    ' + '
    ' + '
    '; break; diff --git a/templates/sendeds/showAll.php b/templates/sendeds/showAll.php index 63fa145..dffd754 100755 --- a/templates/sendeds/showAll.php +++ b/templates/sendeds/showAll.php @@ -42,6 +42,7 @@ Numéro Message Date + Delivré @@ -54,6 +55,7 @@ + Date: Tue, 22 Sep 2015 20:22:14 +0200 Subject: [PATCH 7/8] =?UTF-8?q?Ajout=20de=20l'activation=20des=20accus?= =?UTF-8?q?=C3=A9s=20de=20reception?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/internalConsole.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/internalConsole.php b/controllers/internalConsole.php index a0afaf1..2ae77bc 100755 --- a/controllers/internalConsole.php +++ b/controllers/internalConsole.php @@ -164,7 +164,7 @@ $id_sended = $db->lastId(); //Commande qui envoie le SMS - $commande_send_sms = 'gammu-smsd-inject TEXT ' . escapeshellarg($number) . ' -len ' . mb_strlen($text_sms) . ' -text ' . $text_sms; + $commande_send_sms = 'gammu-smsd-inject TEXT ' . escapeshellarg($number) . ' -report -len ' . mb_strlen($text_sms) . ' -text ' . $text_sms; //Commande qui s'assure de passer le SMS dans ceux envoyés, et de lui donner le bon statut //On va liée les deux commandes pour envoyer le SMS puis le passer en echec From d58f51d08ae96a4a3db775e2fcda7b25379f6512 Mon Sep 17 00:00:00 2001 From: Pierre-Lin Bonnemaison Date: Tue, 22 Sep 2015 22:04:59 +0200 Subject: [PATCH 8/8] =?UTF-8?q?Ajout=20de=20la=20gestion=20des=20failed=20?= =?UTF-8?q?et=20des=20accus=C3=A9s=20de=20reception=20sur=20les=20messages?= =?UTF-8?q?=20de=20plus=20de=20160=20caract=C3=A8res?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/discussions.php | 2 +- controllers/internalConsole.php | 39 +++++++++++++++++++++++++-------- createDatabase.sql | 2 ++ templates/discussions/show.php | 2 +- 4 files changed, 34 insertions(+), 11 deletions(-) diff --git a/controllers/discussions.php b/controllers/discussions.php index 127b0da..461bd19 100755 --- a/controllers/discussions.php +++ b/controllers/discussions.php @@ -85,7 +85,7 @@ 'date' => htmlspecialchars($sended['at']), 'text' => htmlspecialchars($sended['content']), 'type' => 'sended', - 'delivered' => ($sended['delivered'] ? true : false), + 'status' => ($sended['delivered'] ? 'delivered' : ($sended['failed'] ? 'failed' : '')), ); } diff --git a/controllers/internalConsole.php b/controllers/internalConsole.php index 2ae77bc..200e993 100755 --- a/controllers/internalConsole.php +++ b/controllers/internalConsole.php @@ -156,11 +156,13 @@ //Pour plus de précision, on remet la date à jour en réinstanciant l'objet DateTime (et on reformatte la date, bien entendu) $now = new DateTime(); $now = $now->format('Y-m-d H:i:s'); + //On peut maintenant ajouter le SMS - if (!$db->insertIntoTable('sendeds', ['at' => $now, 'target' => $number, 'content' => $scheduled['content']])) + if (!$db->insertIntoTable('sendeds', ['at' => $now, 'target' => $number, 'content' => $scheduled['content'], 'before_delivered' => ceil(mb_strlen($scheduled['content'])/160)])) { echo 'Impossible d\'inserer le sms pour le numero ' . $number . "\n"; } + $id_sended = $db->lastId(); //Commande qui envoie le SMS @@ -246,23 +248,42 @@ } //On gère les accusés de reception - if (trim($text) == 'Delivered') + if (trim($text) == 'Delivered' || trim($text) == 'Failed') { - echo 'Delivered SMS for ' . $number . "\n"; - $this->wlog('Delivered SMS for ' . $number); + echo 'Delivered or Failed SMS for ' . $number . "\n"; + $this->wlog('Delivered or Failed SMS for ' . $number); - //On récupère les SMS par encore validé, uniquement sur les dernières 24h + //On récupère les SMS pas encore validé, uniquement sur les dernières 12h $now = new DateTime(); - $interval = new DateInterval('P1D'); + $interval = new DateInterval('P12H'); $sinceDate = $now->sub($interval)->format('Y-m-d H:i:s'); - if (!$sendeds = $db->getFromTableWhere('sendeds', ['target' => $number, 'delivered' => false, '>at' => $sinceDate], 'at', false, 1)) + if (!$sendeds = $db->getFromTableWhere('sendeds', ['target' => $number, 'delivered' => false, 'failed' => false, '>at' => $sinceDate], 'at', false, 1)) { continue; } - $db->updateTableWhere('sendeds', ['delivered' => true], ['id' => $sendeds[0]['id']]); - echo "Sended SMS id " . $sendeds[0]['id'] . " to delivered status\n"; + $sended = $sendeds[0]; + + //On gère les echecs + if (trim($text) == 'Failed') + { + $db->updateTableWhere('sendeds', ['before_delivered' => 0, 'failed' => true], ['id' => $sended['id']]); + echo "Sended SMS id " . $sended['id'] . " pass to failed status\n"; + continue; + } + + //On gère le cas des messages de plus de 160 caractères, lesquels impliquent plusieurs accusés + if ($sended['before_delivered'] > 1) + { + $db->updateTableWhere('sendeds', ['before_delivered' => $sended['before_delivered'] - 1], ['id' => $sended['id']]); + echo "Sended SMS id " . $sended['id'] . " before_delivered decrement\n"; + continue; + } + + //Si tout est bon, que nous avons assez d'accusés, nous validons ! + $db->updateTableWhere('sendeds', ['before_delivered' => 0, 'delivered' => true], ['id' => $sended['id']]); + echo "Sended SMS id " . $sended['id'] . " to delivered status\n"; continue; } diff --git a/createDatabase.sql b/createDatabase.sql index 2586787..964d872 100755 --- a/createDatabase.sql +++ b/createDatabase.sql @@ -27,7 +27,9 @@ CREATE TABLE IF NOT EXISTS sendeds at DATETIME NOT NULL, target VARCHAR(12) NOT NULL, content VARCHAR(1000) NOT NULL, + before_delivered INT NOT NULL, delivered BOOLEAN NOT NULL DEFAULT FALSE, + failed BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (id) ); diff --git a/templates/discussions/show.php b/templates/discussions/show.php index 4ec68ba..f4f0b3f 100755 --- a/templates/discussions/show.php +++ b/templates/discussions/show.php @@ -86,7 +86,7 @@ '
    ' + '
    ' + '
    ' + message.text + '
    ' + - '
    ' + message.date + (message.delivered ? ' ' : '' ) + '
    ' + + '
    ' + message.date + (message.status ? (message.status == 'delivered' ? ' ' : '' ) : '' ) + '
    ' + '
    ' + '
    '; break;