]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/DirectionDetector/DirectionDetectorPlugin.php
b721ebb20e62f7195b1cff6ed22b65cc1fe8c2db
[quix0rs-gnu-social.git] / plugins / DirectionDetector / DirectionDetectorPlugin.php
1 <?php
2 /**
3  * DirectionDetector plugin, detects notices with RTL content & sets RTL
4  * style for them.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
18  *
19  * @category     Plugin
20  * @package      StatusNet
21  * @author               Behrooz shabani (everplays) - <behrooz@rock.com>
22  * @copyright    2009-2010 Behrooz shabani
23  * @license      http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
24  *
25  */
26
27 if (!defined('STATUSNET')) {
28     exit(1);
29 }
30
31 define('DIRECTIONDETECTORPLUGIN_VERSION', '0.2.0');
32
33 class DirectionDetectorPlugin extends Plugin {
34     /**
35      * SN plugin API, here we will make changes on rendered column
36      *
37      * @param object $notice notice is going to be saved
38      */
39     public function onStartNoticeSave($notice){
40         // don't use getRendered() here since it's not saved yet and thus can't ->update in case that would happen
41         if(!preg_match('/<span class="rtl">/', $notice->rendered) && self::isRTL($notice->content))
42             $notice->rendered = '<span class="rtl">'.$notice->rendered.'</span>';
43         return true;
44     }
45
46     /**
47      * is passed string a rtl content or not
48      *
49      * @param string $content
50      * @return boolean
51      */
52     public static function isRTL($content){
53         $content = self::getClearText($content);
54         $words = explode(' ', $content);
55         $rtl = 0;
56         foreach($words as $str)
57             if(self::startsWithRTLCharacter($str))
58                 $rtl++;
59             else
60                 $rtl--;
61         if($rtl>0)// if number of rtl words is more than ltr words so it's a rtl content
62             return true;
63         elseif($rtl==0)
64             // check first word again
65             return self::startsWithRTLCharacter($words[0]);
66         return false;
67     }
68
69     /**
70      * checks that passed string starts with a RTL language or not
71      *
72      * @param string $str
73      * @return boolean
74      */
75     public static function startsWithRTLCharacter($str){
76         if (strlen($str) < 1) {
77             return false;
78         }
79         if( is_array($cc = self::utf8ToUnicode(mb_substr($str, 0, 1, 'utf-8'))) )
80             $cc = $cc[0];
81         else
82             return false;
83         if($cc>=1536 && $cc<=1791) // arabic, persian, urdu, kurdish, ...
84             return true;
85         if($cc>=65136 && $cc<=65279) // arabic peresent 2
86             return true;
87         if($cc>=64336 && $cc<=65023) // arabic peresent 1
88             return true;
89         if($cc>=1424 && $cc<=1535) // hebrew
90             return true;
91         if($cc>=64256 && $cc<=64335) // hebrew peresent
92             return true;
93         if($cc>=1792 && $cc<=1871) // Syriac
94             return true;
95         if($cc>=1920 && $cc<=1983) // Thaana
96             return true;
97         if($cc>=1984 && $cc<=2047) // NKo
98             return true;
99         if($cc>=11568 && $cc<=11647) // Tifinagh
100             return true;
101         return false;
102     }
103
104     /**
105      * clears text from replys, tags, groups, reteets & whitespaces
106      *
107      * @param string $str
108      * @return string
109      */
110     private static function getClearText($str){
111         $str = preg_replace('/@[^ ]+|![^ ]+|#[^ ]+/u', '', $str); // reply, tag, group
112         $str = preg_replace('/^RT[: ]{1}| RT | RT: |^RD[: ]{1}| RD | RD: |[♺♻:]/u', '', $str); // redent, retweet
113         $str = preg_replace("/[ \r\t\n]+/", ' ', trim($str)); // remove spaces
114         return $str;
115     }
116
117     /**
118      * adds javascript to do same thing on input textarea
119      *
120      * @param Action $action
121      */
122     function onEndShowScripts($action){
123         if (common_logged_in()) {
124             $action->script($this->path('jquery.DirectionDetector.js'));
125         }
126     }
127
128     /**
129      * Takes an UTF-8 string and returns an array of ints representing the
130      * Unicode characters. Astral planes are supported ie. the ints in the
131      * output can be > 0xFFFF. O$ccurrances of the BOM are ignored. Surrogates
132      * are not allowed.
133      *
134      * @param string $str
135      * @return mixed array of ints, or false on invalid input
136      */
137     private static function utf8ToUnicode($str){
138         $mState = 0;       // cached expected number of octets after the current octet
139                    // until the beginning of the next UTF8 character sequence
140         $mUcs4  = 0;     // cached Unicode character
141         $mBytes = 1;       // cached expected number of octets in the current sequence
142         $out = array();
143         $len = strlen($str);
144
145         for($i = 0; $i < $len; $i++) {
146             $in = ord($str{$i});
147             if (0 == $mState) {
148                 // When mState is zero we expect either a US-ASCII character or a
149                 // multi-octet sequence.
150                 if (0 == (0x80 & ($in))) {
151                     // US-ASCII, pass straight through.
152                     $out[] = $in;
153                     $mBytes = 1;
154                 } elseif (0xC0 == (0xE0 & ($in))) {
155                     // First octet of 2 octet sequence
156                     $mUcs4 = ($in);
157                     $mUcs4 = ($mUcs4 & 0x1F) << 6;
158                     $mState = 1;
159                     $mBytes = 2;
160                 } elseif (0xE0 == (0xF0 & ($in))) {
161                     // First octet of 3 octet sequence
162                     $mUcs4 = ($in);
163                     $mUcs4 = ($mUcs4 & 0x0F) << 12;
164                     $mState = 2;
165                     $mBytes = 3;
166                 } elseif (0xF0 == (0xF8 & ($in))) {
167                     // First octet of 4 octet sequence
168                     $mUcs4 = ($in);
169                     $mUcs4 = ($mUcs4 & 0x07) << 18;
170                     $mState = 3;
171                     $mBytes = 4;
172                 } elseif (0xF8 == (0xFC & ($in))) {
173                     /* First octet of 5 octet sequence.
174                      *
175                      * This is illegal because the encoded codepoint must be either
176                      * (a) not the shortest form or
177                      * (b) outside the Unicode range of 0-0x10FFFF.
178                      * Rather than trying to resynchronize, we will carry on until the end
179                      * of the sequence and let the later error handling code catch it.
180                      */
181                     $mUcs4 = ($in);
182                     $mUcs4 = ($mUcs4 & 0x03) << 24;
183                     $mState = 4;
184                     $mBytes = 5;
185                 } elseif (0xFC == (0xFE & ($in))) {
186                     // First octet of 6 octet sequence, see comments for 5 octet sequence.
187                     $mUcs4 = ($in);
188                     $mUcs4 = ($mUcs4 & 1) << 30;
189                     $mState = 5;
190                     $mBytes = 6;
191                 } else {
192                     /* Current octet is neither in the US-ASCII range nor a legal first
193                      * octet of a multi-octet sequence.
194                      */
195                     return false;
196                 }
197             } else {
198                 // When mState is non-zero, we expect a continuation of the multi-octet
199                 // sequence
200                 if (0x80 == (0xC0 & ($in))) {
201                     // Legal continuation.
202                     $shift = ($mState - 1) * 6;
203                     $tmp = $in;
204                     $tmp = ($tmp & 0x0000003F) << $shift;
205                     $mUcs4 |= $tmp;
206                     if (0 == --$mState) {
207                         /* End of the multi-octet sequence. mUcs4 now contains the final
208                          * Unicode codepoint to be output
209                          *
210                          * Check for illegal sequences and codepoints.
211                          */
212                         // From Unicode 3.1, non-shortest form is illegal
213                         if      (
214                                 ((2 == $mBytes) && ($mUcs4 < 0x0080)) ||
215                                 ((3 == $mBytes) && ($mUcs4 < 0x0800)) ||
216                                 ((4 == $mBytes) && ($mUcs4 < 0x10000)) ||
217                                 (4 < $mBytes) ||
218                                 // From Unicode 3.2, surrogate characters are illegal
219                                 (($mUcs4 & 0xFFFFF800) == 0xD800) ||
220                                 // Codepoints outside the Unicode range are illegal
221                                 ($mUcs4 > 0x10FFFF)
222                             ){
223                             return false;
224                         }
225                         if (0xFEFF != $mUcs4) {
226                             $out[] = $mUcs4;
227                         }
228                         //initialize UTF8 cache
229                         $mState = 0;
230                         $mUcs4  = 0;
231                         $mBytes = 1;
232                     }
233                 } else {
234                     /* ((0xC0 & (*in) != 0x80) && (mState != 0))
235                      *
236                      * Incomplete multi-octet sequence.
237                      */
238                     return false;
239                 }
240             }
241         }
242         return $out;
243     }
244
245     /**
246      * plugin details
247      */
248     function onPluginVersion(array &$versions){
249         $url = 'http://status.net/wiki/Plugin:DirectionDetector';
250
251         $versions[] = array(
252             'name' => 'Direction detector',
253             'version' => DIRECTIONDETECTORPLUGIN_VERSION,
254             'author' => 'Behrooz Shabani',
255             'homepage' => $url,
256             // TRANS: Plugin description.
257             'rawdescription' => _m('Shows notices with right-to-left content in correct direction.')
258         );
259         return true;
260     }
261 }
262
263 /*
264 // Example:
265 var_dump(DirectionDetectorPlugin::isRTL('RT @everplays ♺: دادگاه به دليل عدم حضور وکلای متهمان بنا بر اصل ١٣٥ قانون اساسی غير قانونی است')); // true
266 */