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