moved code up one level to eliminate the docs subdirectory
[acontent.git] / include / classes / Utility.class.php
1 <?php\r
2 /************************************************************************/\r
3 /* AContent                                                             */\r
4 /************************************************************************/\r
5 /* Copyright (c) 2010                                                   */\r
6 /* Inclusive Design Institute                                           */\r
7 /*                                                                      */\r
8 /* This program is free software. You can redistribute it and/or        */\r
9 /* modify it under the terms of the GNU General Public License          */\r
10 /* as published by the Free Software Foundation.                        */\r
11 /************************************************************************/\r
12 \r
13 /**\r
14 * Utility functions \r
15 * @access       public\r
16 * @author       Cindy Qi Li\r
17 */\r
18 \r
19 if (!defined('TR_INCLUDE_PATH')) exit;\r
20 \r
21 class Utility {\r
22 \r
23         /**\r
24         * Return a unique random string based on the given length.\r
25         * The maxium length is 32 hexidecimal\r
26         * @access  public\r
27         * @param   none\r
28         * @return  a random string\r
29         * @author  Cindy Qi Li\r
30         */\r
31         public static function getRandomStr($length = "")\r
32         {\r
33                 $code = md5(uniqid(rand(), true));\r
34                 if ($length != "") return substr($code, 0, $length);\r
35                 else return $code;\r
36         }\r
37 \r
38         /* takes the array of valid prefs and assigns them to the current session */\r
39         public static function assign_session_prefs($prefs) {\r
40                 unset($_SESSION['prefs']);\r
41                 \r
42                 if (is_array($prefs)) {\r
43                         foreach($prefs as $pref_name => $value) {\r
44                                 $_SESSION['prefs'][$pref_name] = $value;\r
45                         }\r
46                 }\r
47         }\r
48 \r
49         /**\r
50         * Checks if the data exceeded the database predefined length, if so,\r
51         * truncate it.\r
52         * This is used on data that are being inserted into the database.\r
53         * If this function is used for display purposes, you may want to add the '...' \r
54         * at the end of the string by setting the $forDisplay=1\r
55         * @param        the mbstring that needed to be checked\r
56         * @param        the byte length of what the input should be in the database.\r
57         * @param        (OPTIONAL) 1 or 0, default value is 0 \r
58         *                       when 1, append '...' at the end of the string.\r
59         *           when 0, only truncate string, do not append '...'  \r
60         * @return       the mbstring safe sql entry\r
61         * @author       Harris Wong\r
62         */\r
63         public static function validateLength($input, $len, $forDisplay=0){\r
64                 global $strlen, $substr;\r
65                 $input_bytes_len = strlen($input);\r
66                 $input_len = $strlen($input);\r
67         \r
68                 //If the input has exceeded the db column limit\r
69                 if ($input_bytes_len > $len){\r
70                         //calculate where to chop off the string\r
71                         $percentage = $input_bytes_len / $input_len;\r
72                         //Get the suitable length that should be stored in the db\r
73                         $suitable_len = floor($len / $percentage);\r
74         \r
75                         if ($forDisplay===1){\r
76                                 return $substr($input, 0, $suitable_len).'...';\r
77                         }\r
78                         return $substr($input, 0, $suitable_len);\r
79                 }\r
80                 //if valid length\r
81                 return $input;\r
82         }\r
83 \r
84         /**\r
85         * check if value in the given attribute is a valid language code\r
86         * return true if valid, otherwise, return false\r
87         */\r
88         public static function isValidLangCode($code)\r
89         {\r
90                 require_once(TR_INCLUDE_PATH.'classes/DAO/LangCodesDAO.class.php');\r
91                 $langCodesDAO = new LangCodesDAO();\r
92 \r
93                 if (strlen($code) == 2) \r
94                 {\r
95                         $rows = $langCodesDAO->GetLangCodeBy2LetterCode($code);\r
96                 }\r
97                 else if (strlen($code) == 3)\r
98                 {\r
99                         $rows = $langCodesDAO->GetLangCodeBy3LetterCode($code);\r
100                 }\r
101                 else \r
102                 {\r
103                         return false;\r
104                 }\r
105 \r
106                 return (is_array($rows));\r
107         }\r
108 \r
109         /**\r
110          * Return a valid 3-character language code\r
111          * 1. if input is a valid 3-character language code, return itself;\r
112          * 2. if input is a valid 2-character language code, return according 3-character language code\r
113          * 3. if input is an invalid language code, return default language code\r
114          */\r
115         public static function get3LetterLangCode($code)\r
116         {\r
117                 require_once(TR_INCLUDE_PATH.'classes/DAO/LangCodesDAO.class.php');\r
118                 $langCodesDAO = new LangCodesDAO();\r
119                 \r
120                 if (!Utility::isValidLangCode($code))\r
121                         return $_config['default_language'];\r
122                 else\r
123                 {\r
124                         if (strlen($code) == 3) return $code;\r
125                         \r
126                         if (strlen($code) == 2) \r
127                         {\r
128                                 $rows = $langCodesDAO->GetLangCodeBy2LetterCode($code);\r
129                                 return $rows[0]['code_3letters'];\r
130                         }\r
131                         \r
132                 }\r
133         }\r
134         \r
135         /**\r
136          * Find out whether the current theme is a mobile theme\r
137          * @access public\r
138          * @param  none\r
139          * @return true if the current theme is a mobile theme; otherwise, false.\r
140          */\r
141         public static function isMobileTheme() {\r
142                 return ($_SESSION['prefs']['PREF_THEME'] == 'mobile');\r
143         }\r
144         \r
145         /**\r
146         * This function authenticate user privilege\r
147         * @access  public\r
148         * @param   privilege constants\r
149         *          $printMsg: true or false. \r
150         *                     When it's true, the function prints "NO_PRIV" error msg if the user does not have $privilegeToValidate\r
151         *                     When it's fales, the function returns true if the user has $privilegeToValidate, or false if the user has no $privilegeToValidate\r
152         * @return  If the caller is oauth, echo error msg.\r
153         *          Otherwise, the return is based on the value of $printMsg, @see @param $printMsg\r
154         * @author  Cindy Qi Li\r
155         */\r
156         public static function authenticate($privilegeToValidate, $printMsg=true) {\r
157                 global $_current_user, $_course_id, $msg, $oauth_import;\r
158                 \r
159                 if ($privilegeToValidate == '' || $privilegeToValidate == 0) return true;\r
160                 \r
161                 $authenticated = true; // default\r
162                 /* make sure the user is the author of the current course */\r
163                 if ($privilegeToValidate == TR_PRIV_ISAUTHOR_OF_CURRENT_COURSE && \r
164                     (!isset($_current_user) || !$_current_user->isAuthor($_course_id) || !isset($_course_id)))\r
165                 {\r
166                         $authenticated = false;\r
167                 }\r
168 \r
169                 if ($privilegeToValidate == TR_PRIV_ISAUTHOR &&\r
170                     (!isset($_current_user) || !$_current_user->isAuthor()))\r
171                 {\r
172                         $authenticated = false;\r
173                 }\r
174                 \r
175                 if ($privilegeToValidate == TR_PRIV_IN_A_COURSE &&\r
176                     (!isset($_course_id) || $_course_id == 0))\r
177                 {\r
178                         $authenticated = false;\r
179                 }\r
180                 \r
181                 if (!$authenticated)\r
182                 {\r
183                         if ($oauth_import)\r
184                         {\r
185                                 echo "error=".urlencode('User has no author privilege');\r
186                                 exit;\r
187                         }\r
188                         else if ($printMsg)\r
189                         {\r
190                                 $msg->addError('NO_PRIV');\r
191                                 include(TR_INCLUDE_PATH.'header.inc.php');\r
192                                 $msg->printAll(); \r
193                                 include(TR_INCLUDE_PATH.'footer.inc.php');\r
194                                 exit;\r
195                         }\r
196                         else {\r
197                                 return false;\r
198                         }\r
199                 }\r
200                 return true;\r
201         }\r
202         \r
203         /**\r
204          * This function highlights the given keywords in the text\r
205          * and perserves the case of the keywords in the text\r
206          * @access public\r
207          * @param  $text string, \r
208          *         $keywords    an array of keywords\r
209          * @author Cindy Qi Li\r
210          */\r
211         public static function highlightKeywords($text, $keywords)\r
212         {\r
213                 if (!is_array($keywords)) return $text;\r
214                 // remove empty and "OR" element from the keywords array\r
215                 $keywords = array_diff($keywords, array('OR', '', NULL));\r
216                 \r
217                 // strip html tags from input text\r
218                 $text = strip_tags($text);\r
219                 \r
220                 $i = 0;\r
221                 $highlight_start_tag = '<strong class="highlight">';\r
222                 $highlight_end_tag = '</strong>';\r
223                 \r
224                 $strlen_highlight_start_tag = strlen($highlight_start_tag);\r
225                 $strlen_highlight_end_tag = strlen($highlight_end_tag);\r
226                 \r
227                 // Read the text character one by one and highlight from the reading point\r
228                 // This is to avoid the highlight on highlight html tags.\r
229                 while ($i < strlen($text))\r
230                 {\r
231                         foreach ($keywords as $keyword)\r
232                         {\r
233                                 if (strtolower(substr($text, $i, strlen($keyword))) == strtolower($keyword))\r
234                                 {\r
235                                         $text = substr($text, 0, $i).$highlight_start_tag.substr($text, $i, strlen($keyword)).$highlight_end_tag.substr($text, $i+strlen($keyword));\r
236                                         $i += strlen($keyword) + $strlen_highlight_start_tag + $strlen_highlight_end_tag;\r
237                                         continue 2;\r
238                                 }\r
239                         }\r
240                         $i++;\r
241                 }\r
242                 \r
243                 return $text;\r
244         }\r
245         \r
246         /**\r
247          * This function removes all the items that are NULL or only spaces from the given array\r
248          * @access public\r
249          * @param  $in_array    array\r
250          * @return if successful, return the array without the NULL or all-space items\r
251          *         if the in_array is not an array or failed, return $in_array itself \r
252          * @author Cindy Qi Li\r
253          */\r
254         public static function removeEmptyItemsFromArray($in_array)\r
255         {\r
256                 if (!is_array($in_array)) return $in_array;\r
257                 \r
258                 foreach ($in_array as $key => $value)\r
259                         if (is_null($value) || trim($value) == '') unset($in_array[$key]);\r
260                 \r
261                 return array_values($in_array);\r
262         }\r
263         \r
264         /**\r
265          * This funciton replace the reserved constants with the real values\r
266          * @access public\r
267          * @param $str\r
268          * @return a replaced string\r
269          * @author Cindy Qi Li\r
270          */\r
271         public static function replaceConstants($str)\r
272         {\r
273                 global $_course_id, $_content_id;\r
274                 \r
275                 return str_replace(array('{COURSE_ID}', '{CONTENT_ID}'), array($_course_id, $_content_id), $str);\r
276         }\r
277 \r
278         /**\r
279          * This funciton returns a pair of (URL, URL parameters). \r
280          * For example, if input "tests/index.php?a=1&b=2", returns array ("tests/index.php", '?a=1&b=2"');\r
281          * @access public\r
282          * @param $str\r
283          * @return array of (URL, URL parameters)\r
284          * @author Cindy Qi Li\r
285          */\r
286         public static function separateURLAndParam($str)\r
287         {\r
288                 $pos = strpos($str, '?');\r
289                 \r
290                 if (!$pos) return array($str, '');\r
291                 else return array(substr($str, 0, $pos), substr($str, $pos));\r
292         }\r
293         \r
294         /**\r
295          * This funciton returns a pair of (URL, URL parameters) of the PHP_SELF url. \r
296          * For example, if http referer is "http://localhost/achecker/home/index.php?a=1&b=2", \r
297          * the function returns array ("http://localhost/achecker/home/index.php?a=1&b=2&", 'a=1&b=2"');\r
298          * @access public\r
299          * @param none\r
300          * @return array of (URL, URL parameters)\r
301          * @author Cindy Qi Li\r
302          */\r
303         public static function getRefererURLAndParams() {\r
304                 $caller_url_parts = explode('/', $_SERVER['PHP_SELF']); \r
305                 $caller_script = $caller_url_parts[count($caller_url_parts)-1];\r
306                 \r
307                 if (count($_GET) > 0)\r
308                 {\r
309                         foreach ($_GET as $param => $value)\r
310                         {\r
311                                 if ($param == 'action' || $param == 'cid') \r
312                                         continue;\r
313                                 else\r
314                                         $url_param .= $param.'='.urlencode($value).'&';\r
315                         }\r
316                 }\r
317                 \r
318                 $caller_url = $caller_script. '?'.(isset($url_param) ? $url_param : '');\r
319                 $url_param = substr($url_param, 0, -1);\r
320                 \r
321                 return array($caller_url, $url_param);\r
322         }\r
323 }\r
324 ?>