ossn.lib.system.php
Go to the documentation of this file.
1 <?php
2 /**
3  * Open Source Social Network
4  *
5  * @package (Informatikon.com).ossn
6  * @author OSSN Core Team <[email protected]>
7  * @copyright 2014 iNFORMATIKON TECHNOLOGIES
8  * @license General Public Licence http://www.opensource-socialnetwork.org/licence
9  * @link http://www.opensource-socialnetwork.org/licence
10  */
11 
12 /*
13  * OSSN ACCESS VALUES
14  */
15 define('OSSN_FRIENDS', 3);
16 define('OSSN_PUBLIC', 2);
17 define('OSSN_PRIVATE', 1);
18 /**
19  * Constants
20  */
21 define('REF', true);
22 /*
23  * Load site settings , so the setting should not load agian and again
24  */
25 global $Ossn;
27 $Ossn->siteSettings = $settings->getAllSettings();
28 
29 /*
30  * Set exceptions handler
31  */
32 set_exception_handler('_ossn_exception_handler');
33 /**
34  * ossn_recursive_array_search
35  * Searches the array for a given value and returns the corresponding key if successful
36  * @source: http://php.net/manual/en/function.array-search.php
37  *
38  * @param mixed $needle The searched value. If needle is a string, the comparison is done in a case-sensitive manner.
39  * @param array $haystack The array
40  * @return false|integer
41  */
42 function ossn_recursive_array_search($needle, $haystack) {
43  foreach($haystack as $key => $value) {
44  $current_key = $key;
45  if(($needle === $value) || (is_array($value) && ossn_recursive_array_search($needle, $value))) {
46  return $current_key;
47  }
48  }
49  return false;
50 }
51 /**
52  * Get site url
53  *
54  * @params $extend => Extned site url like http://site.com/my/extended/path
55  *
56  * @return string
57  */
58 function ossn_site_url($extend = '', $action = false) {
59  global $Ossn;
60  $siteurl = "{$Ossn->url}{$extend}";
61  if($action === true){
62  $siteurl = ossn_add_tokens_to_url($siteurl);
63  }
64  return $siteurl;
65 }
66 
67 /**
68  * Get data directory contaning user and system files
69  *
70  * @params $extend => Extned data directory path like /home/htdocs/userdata/my/extend/path
71  *
72  * @return string
73  */
74 function ossn_get_userdata($extend = '') {
75  global $Ossn;
76  return "{$Ossn->userdata}{$extend}";
77 }
78 
79 /**
80  * Get database settings
81  *
82  * @return object
83  */
85  global $Ossn;
86  $defaults = array(
87  'host' => $Ossn->host,
88  'user' => $Ossn->user,
89  'password' => $Ossn->password,
90  'database' => $Ossn->database
91  );
92  return arrayObject($defaults);
93 }
94 
95 /**
96  * Get version package file
97  *
98  * @return SimpleXMLElement
99  */
101  return simplexml_load_file(ossn_route()->www . 'opensource-socialnetwork.xml');
102 }
103 
104 /**
105  * Add a hook to system, hooks are usefull for callback returns
106  *
107  * @param string $hook The name of the hook
108  * @param string $type The type of the hook
109  * @param callable $callback The name of a valid function or an array with object and method
110  * @param int $priority The priority - 500 is default, lower numbers called first
111  *
112  * @return bool
113  */
114 function ossn_add_hook($hook, $type, $callback, $priority = 200) {
115  global $Ossn;
116 
117  if (empty($hook) || empty($type)) {
118  return false;
119  }
120 
121  if (!isset($Ossn->hooks)) {
122  $Ossn->hooks = array();
123  }
124  if (!isset($Ossn->hooks[$hook])) {
125  $Ossn->hooks[$hook] = array();
126  }
127  if (!isset($Ossn->hooks[$hook][$type])) {
128  $Ossn->hooks[$hook][$type] = array();
129  }
130 
131  if (!is_callable($callback, true)) {
132  return false;
133  }
134 
135  $priority = max((int)$priority, 0);
136 
137  while (isset($Ossn->hooks[$hook][$type][$priority])) {
138  $priority++;
139  }
140  $Ossn->hooks[$hook][$type][$priority] = $callback;
141  ksort($Ossn->hooks[$hook][$type]);
142  return true;
143 
144 }
145 
146 /**
147  * Check if the hook exists or not
148  *
149  * @param string $hook The name of the hook
150  * @param string $type The type of the hook
151  *
152  * @return bool
153  */
154 function ossn_is_hook($hook, $type) {
155  global $Ossn;
156  $hooks = array();
157  if (isset($Ossn->hooks[$hook][$type])) {
158  return true;
159  }
160  return false;
161 }
162 
163 /**
164  * Call a hook
165  *
166  * @param string $hook The name of the hook
167  * @param string $type The type of the hook
168  * @param mixed $params Additional parameters to pass to the handlers
169  * @param mixed $returnvalue An initial return value
170  *
171  * @return mix data
172  */
173 function ossn_call_hook($hook, $type, $params = null, $returnvalue = null) {
174  global $Ossn;
175  $hooks = array();
176  if (isset($Ossn->hooks[$hook][$type])) {
177  $hooks[] = $Ossn->hooks[$hook][$type];
178  }
179  foreach ($hooks as $callback_list) {
180  if (is_array($callback_list)) {
181  foreach ($callback_list as $hookcallback) {
182  if (is_callable($hookcallback)) {
183  $args = array(
184  $hook,
185  $type,
186  $returnvalue,
187  $params
188  );
189  $temp_return_value = call_user_func_array($hookcallback, $args);
190  if (!is_null($temp_return_value)) {
191  $returnvalue = $temp_return_value;
192  }
193  }
194  }
195  }
196  }
197 
198  return $returnvalue;
199 }
200 
201 /**
202  * Trigger a callback
203  *
204  * @param string $event Callback event name
205  * @param string $type The type of the callback
206  * @param mixed $params Additional parameters to pass to the handlers
207  *
208  * @return bool
209  */
210 function ossn_trigger_callback($event, $type, $params = null) {
211  global $Ossn;
212  $events = array();
213  if (isset($Ossn->events[$event][$type])) {
214  $events[] = $Ossn->events[$event][$type];
215  }
216  foreach ($events as $callback_list) {
217  if (is_array($callback_list)) {
218  foreach ($callback_list as $eventcallback) {
219  $args = array(
220  $event,
221  $type,
222  $params
223  );
224  if (is_callable($eventcallback) && (call_user_func_array($eventcallback, $args) === false)) {
225  return false;
226  }
227  }
228  }
229  }
230 
231  return true;
232 }
233 
234 /**
235  * Register a callback
236  *
237  * @param string $event Callback event name
238  * @param string $type The type of the callback
239  * @params $priority callback priority
240  * @param string $callback
241  *
242  * @return bool
243  */
244 function ossn_register_callback($event, $type, $callback, $priority = 200) {
245  global $Ossn;
246 
247  if (empty($event) || empty($type)) {
248  return false;
249  }
250 
251  if (!isset($Ossn->events)) {
252  $Ossn->events = array();
253  }
254  if (!isset($Ossn->events[$event])) {
255  $Ossn->events[$event] = array();
256  }
257  if (!isset($Ossn->events[$event][$type])) {
258  $Ossn->events[$event][$type] = array();
259  }
260 
261  if (!is_callable($callback, true)) {
262  return false;
263  }
264 
265  $priority = max((int)$priority, 0);
266 
267  while (isset($Ossn->events[$event][$type][$priority])) {
268  $priority++;
269  }
270  $Ossn->events[$event][$type][$priority] = $callback;
271  ksort($Ossn->events[$event][$type]);
272  return true;
273 
274 }
275 
276 /**
277  * Get a site settings
278  *
279  * @param string $setting Settings Name like (site_name, language)
280  *
281  * @return string or null
282  */
283 function ossn_site_settings($setting) {
284  global $Ossn;
285  if (isset($Ossn->siteSettings->$setting)) {
286  //allow to override a settings
287  return ossn_call_hook('load:settings', $setting, false, $Ossn->siteSettings->$setting);
288  }
289  return false;
290 }
291 
292 /**
293  * Redirect a user to specific url
294  *
295  * @param string $new uri of page. If it is REF then user redirected to the url that user just came from.
296  *
297  * @return return
298  */
299 function redirect($new = '') {
300  global $Ossn;
301  $url = ossn_site_url($new);
302  if ($new === REF) {
303  if (isset($_SERVER['HTTP_REFERER'])) {
304  $url = $_SERVER['HTTP_REFERER'];
305  } else {
306  $url = ossn_site_url();
307  }
308  }
309  if(ossn_is_xhr()){
310  $Ossn->redirect = $url;
311  } else {
312  header("Location: {$url}");
313  exit;
314  }
315 }
316 
317 /**
318  * Get default access types
319  *
320  * @return integer[]
321  */
322 function ossn_access_types() {
323  return array(
324  OSSN_FRIENDS,
325  OSSN_PUBLIC,
327  );
328 }
329 
330 /**
331  * Validate Access
332  *
333  * @return bool
334  */
335 function ossn_access_validate($access, $owner) {
336  if ($access == OSSN_FRIENDS) {
337  if (ossn_user_is_friend(ossn_loggedin_user()->guid, $owner) || ossn_loggedin_user()->guid == $owner) {
338  return true;
339  }
340  }
341  if ($access == OSSN_PUBLIC) {
342  return true;
343  }
344  return false;
345 }
346 
347 /**
348  * Check if the request is ajax or not
349  *
350  * @return bool
351  */
352 function ossn_is_xhr() {
353  if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'
354  ) {
355  return true;
356  }
357  return false;
358 }
359 
360 /**
361  * Serialize Array
362  * This starts array from key 1
363  * Don't use this for multidemension arrays
364  *
365  * @return array
366  */
367 function arraySerialize($array = NULL) {
368  if (isset($array) && !empty($array)) {
369  array_unshift($array, "");
370  unset($array[0]);
371  return $array;
372  }
373 }
374 
375 /**
376  * Limit a words in a string
377  * @params $str = string;
378  * @params $limit = words limit;
379  * @param integer $limit
380  *
381  * @last edit: $arsalanshah
382  * @return bool
383  */
384 function strl($str, $limit = NULL, $dots = true) {
385  if (isset($str) && isset($limit)
386  ) {
387  if (strlen($str) > $limit) {
388  if ($dots == true) {
389  return substr($str, 0, $limit) . '...';
390  } elseif ($dots == false) {
391  return substr($str, 0, $limit);
392  }
393  } elseif (strlen($str) <= $limit) {
394  return $str;
395  }
396 
397  }
398  return false;
399 }
400 
401 /**
402  * Update site settings
403  *
404  * @params $name => settings name
405  * $value => new value
406  * $id => $settings name
407  *
408  * @todo remove $id and update without having $id as settings names must be unique
409  * @return bool
410  */
411 function ossn_site_setting_update($name, $value, $id) {
412  $settings = new OssnSite;
413  if ($settings->UpdateSettings(array('value'), array($value), array("setting_id='{$id}'"))
414  ) {
415  return true;
416  }
417  return false;
418 }
419 
420 /**
421  * Add a system messages for users
422  *
423  * @params $messages => Message for user
424  * $type = message type
425  * $for => for site/frontend or admin/backend
426  * $count => count the message
427  *
428  * @return bool
429  */
430 function ossn_system_message_add($message = null, $register = "success", $count = false) {
431  if (!isset($_SESSION['ossn_messages'])) {
432  $_SESSION['ossn_messages'] = array();
433  }
434  if (!isset($_SESSION['ossn_messages'][$register]) && !empty($register)) {
435  $_SESSION['ossn_messages'][$register] = array();
436  }
437  if (!$count) {
438  if (!empty($message) && is_array($message)) {
439  $_SESSION['ossn_messages'][$register] = array_merge($_SESSION['ossn_messages'][$register], $message);
440  return true;
441  } else if (!empty($message) && is_string($message)) {
442  $_SESSION['ossn_messages'][$register][] = $message;
443  return true;
444  } else if (is_null($message)) {
445  if ($register != "") {
446  $returnarray = array();
447  $returnarray[$register] = $_SESSION['ossn_messages'][$register];
448  $_SESSION['ossn_messages'][$register] = array();
449  } else {
450  $returnarray = $_SESSION['ossn_messages'];
451  $_SESSION['ossn_messages'] = array();
452  }
453  return $returnarray;
454  }
455  } else {
456  if (!empty($register)) {
457  return sizeof($_SESSION['ossn_messages'][$register]);
458  } else {
459  $count = 0;
460  foreach ($_SESSION['ossn_messages'] as $submessages) {
461  $count += sizeof($submessages);
462  }
463  return $count;
464  }
465  }
466  return false;
467 }
468 
469 /**
470  * Add a system messages for users
471  *
472  * @params $messages => Message for user
473  * $type = message type
474  *
475  * @return void
476  */
477 function ossn_trigger_message($message, $type = 'success') {
478  if ($type == 'error') {
479  ossn_system_message_add($message, 'danger');
480  }
481  if ($type == 'success') {
482  ossn_system_message_add($message, 'success');
483  }
484 }
485 /**
486  * Display a error if post size exceed
487  *
488  * @param string $error Langauge string
489  * @param string $redirect Custom redirect url
490  */
491 function ossn_post_size_exceed_error($error = 'ossn:post:size:exceed', $redirect = null){
492  if(!empty($_SERVER['CONTENT_LENGTH']) && empty($_POST)){
493  if(empty($redirect)){
494  $redirect = null;
495  }
496  ossn_trigger_message(ossn_print($error), 'error');
497  redirect($redirect);
498  }
499 }
500 /**
501  * Display a system messages
502  *
503  * @params $for => for site/frontend or admin/backend
504  *
505  * @return string|null data
506  */
508  if (isset($_SESSION['ossn_messages'])) {
509  $dermessage = $_SESSION['ossn_messages'];
510  if (!empty($dermessage)) {
511 
512  if (isset($dermessage) && is_array($dermessage) && sizeof($dermessage) > 0) {
513  foreach ($dermessage as $type => $list) {
514  foreach($list as $message){
515  $m = "<div class='alert alert-$type'>";
516  $m .= '<a href="#" class="close" data-dismiss="alert">&times;</a>';
517  $m .= $message;
518  $m .= '</div>';
519  $ms[] = $m;
520  unset($_SESSION['ossn_messages'][$type]);
521  }
522  }
523  }
524 
525  }
526 
527  }
528  if (isset($ms) && is_array($ms)) {
529  return implode('', $ms);
530  }
531 }
532 
533 /**
534  * Count total themes
535  *
536  * @return (int)
537  */
539  $themes = new OssnThemes;
540  return $themes->total();
541 }
542 
543 /**
544  * Validate filepath , add backslash to end of path
545  *
546  * @param string $path
547  * @return string;
548  */
549 function ossn_validate_filepath($path, $append_slash = TRUE) {
550  $path = str_replace('\\', '/', $path);
551  $path = str_replace('../', '/', $path);
552 
553  $path = preg_replace("/([^:])\/\//", "$1/", $path);
554  $path = trim($path);
555  $path = rtrim($path, " \n\t\0\x0B/");
556 
557  if ($append_slash) {
558  $path = $path . '/';
559  }
560 
561  return $path;
562 }
563 
564 /**
565  * Output Ossn Error page
566  *
567  * @return mix data
568  */
569 function ossn_error_page() {
570  if(ossn_is_xhr()){
571  header("HTTP/1.0 404 Not Found");
572  } else {
573  $title = ossn_print('page:error');
574  $contents['content'] = ossn_plugin_view('pages/contents/error');
575  $contents['background'] = false;
576  $content = ossn_set_page_layout('contents', $contents);
577  $data = ossn_view_page($title, $content);
578  echo $data;
579  }
580  exit;
581 }
582 
583 /**
584  * Acces id to string
585  *
586  * @return string
587  */
588 function ossn_access_id_str($id) {
589  $access = array(
590  '3' => 'friends',
591  '2' => 'public',
592  '1' => 'private',
593  );
594  if (isset($access[$id])) {
595  return $access[$id];
596  }
597  return false;
598 }
599 
600 /**
601  * Check if loggedin is friend with item owner or if owner is loggedin user;
602  *
603  * @return bool;
604  */
606  if (ossn_user_is_friend(ossn_loggedin_user()->guid, $owner) || ossn_loggedin_user()->guid == $owner || ossn_isAdminLoggedin()
607  ) {
608  return true;
609  }
610  return false;
611 }
612 
613 /**
614  * Ossn encrypt string
615  *
616  * @params $string a string you want to encrypt
617  * @param string $string
618  *
619  * @return string string
620  */
621 function ossn_string_encrypt($string) {
622  $key = ossn_site_settings('site_key');
623  return mcrypt_encrypt(MCRYPT_BLOWFISH, $key, utf8_encode($string), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB), MCRYPT_RAND));
624 }
625 
626 /**
627  * Ossn decrypt string
628  *
629  * @params $string a string you want to decrypt
630  * @param string $string
631  *
632  * @return string string
633  */
634 function ossn_string_decrypt($string) {
635  $key = ossn_site_settings('site_key');
636  return mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $string, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB), MCRYPT_RAND));
637 }
638 
639 /**
640  * Ossn php display erros settings
641  *
642  * @return (void);
643  * @access pritvate;
644  */
645 function ossn_errros() {
646  $settings = ossn_site_settings('display_errors');
647  if ($settings == 'on' || is_file(ossn_route()->www . 'DISPLAY_ERRORS')) {
648  error_reporting(E_NOTICE ^ ~E_WARNING);
649 
650  ini_set('log_errors', 1);
651  ini_set('error_log', ossn_route()->www . 'error_log');
652 
653  set_error_handler('_ossn_php_error_handler');
654  } elseif ($settings !== 'on') {
655  ini_set("log_errors", 0);
656  ini_set('display_errors', 'off');
657  }
658 }
659 /**
660  * Intercepts catchable PHP errors.
661  *
662  * @warning This function should never be called directly.
663  *
664  * @internal
665  * For catchable fatal errors, throws an Exception with the error.
666  *
667  * For non-fatal errors, depending upon the debug settings, either
668  * log the error or ignore it.
669  *
670  * @see http://www.php.net/set-error-handler
671  *
672  * @param int $errno The level of the error raised
673  * @param string $errmsg The error message
674  * @param string $filename The filename the error was raised in
675  * @param int $linenum The line number the error was raised at
676  * @param array $vars An array that points to the active symbol table where error occurred
677  *
678  * @return boolean
679  * @throws Exception
680  * @access private
681  */
682 function _ossn_php_error_handler($errno, $errmsg, $filename, $linenum, $vars) {
683  $error = date("Y-m-d H:i:s (T)") . ": \"$errmsg\" in file $filename (line $linenum)";
684  switch ($errno) {
685  case E_USER_ERROR:
686  error_log("PHP ERROR: $error");
687  ossn_trigger_message("ERROR: $error", 'error');
688 
689  // Since this is a fatal error, we want to stop any further execution but do so gracefully.
690  throw new Exception($error);
691  break;
692 
693  case E_WARNING :
694  case E_USER_WARNING :
695  case E_RECOVERABLE_ERROR: // (e.g. type hint violation)
696 
697  // check if the error wasn't suppressed by the error control operator (@)
698  if (error_reporting()) {
699  error_log("PHP WARNING: $error");
700  }
701  break;
702 
703  default:
704  global $CONFIG;
705  if (isset($CONFIG->debug) && $CONFIG->debug === 'NOTICE') {
706  error_log("PHP NOTICE: $error");
707  }
708  }
709 
710  return true;
711 }
712 /**
713  * Check ossn update version
714  *
715  * @return (bool);
716  * @access public;
717  */
718 function ossn_check_update() {
719  $url = 'https://api.github.com/repos/opensource-socialnetwork/opensource-socialnetwork/contents/opensource-socialnetwork.xml';
720  $args['method'] = 'GET';
721  $args['header'] = "Accept-language: en\r\n" . "Cookie: opensourcesocialnetwork=system\r\n" . "User-Agent: Mozilla/5.0\r\n";
722  $options['http'] = $args;
723  if (@fopen('http://github.com', 'r')) {
724  $context = stream_context_create($options);
725  $file = file_get_contents($url, false, $context);
726  $data = json_decode($file);
727  $file = simplexml_load_string(base64_decode($data->content));
728  if (!empty($file->stable_version)) {
729  return ossn_print('ossn:version:avaialbe', $file->stable_version);
730  }
731  }
732  return ossn_print('ossn:update:check:error');
733 }
734 /**
735  * Add exception handler
736  *
737  * @return (html);
738  * @access public;
739  */
740 function _ossn_exception_handler($exception){
741  $params['exception'] = $exception;
742  echo ossn_view('system/handlers/errors', $params);
743 }
744 /**
745  * Set Ajax Data
746  * Use only in action files
747  *
748  * @param array $data A data array
749  *
750  * @return void
751  */
752 function ossn_set_ajax_data(array $data = array()){
753  global $Ossn;
754  if(ossn_is_xhr()){
755  $Ossn->ajaxData = $data;
756  }
757 }
758 /**
759  * Generate .htaccess file
760  *
761  * @return ooolean;
762  */
764  if($type == 'apache'){
765  $file = ossn_route()->www . 'installation/configs/htaccess.dist';
766  $file = file_get_contents($file);
767  return file_put_contents(ossn_route()->www . '.htaccess', $file);
768  }elseif($type == 'nginx'){
769  return false;
770  }
771  return false;
772 }
773 ossn_errros();
774 ossn_register_callback('ossn', 'init', 'ossn_system');