]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - lib/util.php
Merge branch '0.7.x' of git://gitorious.org/laconica/bAvatar-clone without the uninte...
[quix0rs-gnu-social.git] / lib / util.php
index 3f4fae3a59e2d193e5001e7a41efad137b210202..e0eda0114b7101e046c55df94a3cb95919550bd4 100644 (file)
@@ -72,8 +72,7 @@ function common_timezone()
         }
     }
 
-    global $config;
-    return $config['site']['timezone'];
+    return common_config('site', 'timezone');
 }
 
 function common_language()
@@ -81,7 +80,7 @@ function common_language()
 
     // If there is a user logged in and they've set a language preference
     // then return that one...
-    if (common_logged_in()) {
+    if (_have_config() && common_logged_in()) {
         $user = common_current_user();
         $user_language = $user->language;
         if ($user_language)
@@ -315,6 +314,10 @@ function common_current_user()
 {
     global $_cur;
 
+    if (!_have_config()) {
+        return null;
+    }
+
     if ($_cur === false) {
 
         if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
@@ -394,20 +397,20 @@ function common_render_text($text)
 
 function common_replace_urls_callback($text, $callback) {
     // Start off with a regex
-    $regex = '#
-    (?:
-        (?:
-            (?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|xmpp|irc)://
-            |
-            (?:mailto|aim|tel):
-        )
-        [^.\s]+\.[^\s]+
-        |
-        (?:[^.\s/:]+\.)+
-        (?:museum|travel|[a-z]{2,4})
-        (?:[:/][^\s]*)?
-    )
-    #ix';
+    $regex = '#'.
+    '(?:'.
+        '(?:'.
+            '(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|xmpp|irc)://'.
+            '|'.
+            '(?:mailto|aim|tel):'.
+        ')'.
+        '[^.\s]+\.[^\s]+'.
+        '|'.
+        '(?:[^.\s/:]+\.)+'.
+        '(?:museum|travel|[a-z]{2,4})'.
+        '(?:[:/][^\s]*)?'.
+    ')'.
+    '#ix';
     preg_match_all($regex, $text, $matches);
 
     // Then clean up what the regex left behind
@@ -456,11 +459,14 @@ function common_replace_urls_callback($text, $callback) {
 
         if (!in_array($url_parts[2], $tlds)) continue;
 
+        // Make sure we didn't capture a hash tag
+        if (strpos($url, '#') === 0) continue;
+
         // Put the url back the way we found it.
         $url = (mb_strpos($orig_url, htmlspecialchars($url)) === FALSE) ? $url:htmlspecialchars($url);
 
         // Call user specified func
-        $modified_url = $callback($url);
+        $modified_url = call_user_func($callback, $url);
 
         // Replace it!
         $start = mb_strpos($text, $url, $offset);
@@ -472,16 +478,19 @@ function common_replace_urls_callback($text, $callback) {
 }
 
 function common_linkify($url) {
+    // It comes in special'd, so we unspecial it before passing to the stringifying
+    // functions
+    $url = htmlspecialchars_decode($url);
     $display = $url;
-    $url = (!preg_match('#^([a-z]+://|(mailto|aim|tel):)#i', $url)) ? 'http://'.$url:$url;
+    $url = (!preg_match('#^([a-z]+://|(mailto|aim|tel):)#i', $url)) ? 'http://'.$url : $url;
+
+    $attrs = array('href' => $url, 'rel' => 'external');
 
     if ($longurl = common_longurl($url)) {
-        $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
-        $title = "title=\"$longurl\"";
+        $attrs['title'] = $longurl;
     }
-    else $title = '';
 
-    return "<a href=\"$url\" $title rel=\"external\">$display</a>";
+    return XMLStringer::estring('a', $attrs, $display);
 }
 
 function common_longurl($short_url)
@@ -510,11 +519,16 @@ function common_shorten_links($text)
 
 function common_shorten_link($url, $reverse = false)
 {
+
     static $url_cache = array();
     if ($reverse) return isset($url_cache[$url]) ? $url_cache[$url] : $url;
 
     $user = common_current_user();
-
+    if (!isset($user)) {
+      // common current user does not find a user when called from the XMPP daemon
+      // therefore we'll set one here fix, so that XMPP given URLs may be shortened
+      $user->urlshorteningservice = 'ur1.ca';
+    }
     $curlh = curl_init();
     curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
     curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
@@ -572,17 +586,21 @@ function common_shorten_link($url, $reverse = false)
 
 function common_xml_safe_str($str)
 {
-    $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
-
-    // Replace control, formatting, and surrogate characters with '*', ala Twitter
-    return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
+    // Neutralize control codes and surrogates
+       return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
 }
 
 function common_tag_link($tag)
 {
     $canonical = common_canonical_tag($tag);
     $url = common_local_url('tag', array('tag' => $canonical));
-    return '<span class="tag"><a href="' . htmlspecialchars($url) . '" rel="tag">' . htmlspecialchars($tag) . '</a></span>';
+    $xs = new XMLStringer();
+    $xs->elementStart('span', 'tag');
+    $xs->element('a', array('href' => $url,
+                            'rel' => 'tag'),
+                 $tag);
+    $xs->elementEnd('span');
+    return $xs->getString();
 }
 
 function common_canonical_tag($tag)
@@ -600,7 +618,24 @@ function common_at_link($sender_id, $nickname)
     $sender = Profile::staticGet($sender_id);
     $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
     if ($recipient) {
-        return '<span class="vcard"><a href="'.htmlspecialchars($recipient->profileurl).'" class="url"><span class="fn nickname">'.$nickname.'</span></a></span>';
+        $user = User::staticGet('id', $recipient->id);
+        if ($user) {
+            $url = common_local_url('userbyid', array('id' => $user->id));
+        } else {
+            $url = $recipient->profileurl;
+        }
+        $xs = new XMLStringer(false);
+        $attrs = array('href' => $url,
+                       'class' => 'url');
+        if (!empty($recipient->fullname)) {
+            $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
+        }
+        $xs->elementStart('span', 'vcard');
+        $xs->elementStart('a', $attrs);
+        $xs->element('span', 'fn nickname', $nickname);
+        $xs->elementEnd('a');
+        $xs->elementEnd('span');
+        return $xs->getString();
     } else {
         return $nickname;
     }
@@ -611,7 +646,18 @@ function common_group_link($sender_id, $nickname)
     $sender = Profile::staticGet($sender_id);
     $group = User_group::staticGet('nickname', common_canonical_nickname($nickname));
     if ($group && $sender->isMember($group)) {
-        return '<span class="vcard"><a href="'.htmlspecialchars($group->permalink()).'" class="url"><span class="fn nickname">'.$nickname.'</span></a></span>';
+        $attrs = array('href' => $group->permalink(),
+                       'class' => 'url');
+        if (!empty($group->fullname)) {
+            $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
+        }
+        $xs = new XMLStringer();
+        $xs->elementStart('span', 'vcard');
+        $xs->elementStart('a', $attrs);
+        $xs->element('span', 'fn nickname', $nickname);
+        $xs->elementEnd('a');
+        $xs->elementEnd('span');
+        return $xs->getString();
     } else {
         return $nickname;
     }
@@ -628,7 +674,13 @@ function common_at_hash_link($sender_id, $tag)
         $url = common_local_url('subscriptions',
                                 array('nickname' => $user->nickname,
                                       'tag' => $tag));
-        return '<span class="tag"><a href="'.htmlspecialchars($url).'" rel="tag">'.$tag.'</a></span>';
+        $xs = new XMLStringer();
+        $xs->elementStart('span', 'tag');
+        $xs->element('a', array('href' => $url,
+                                'rel' => $tag),
+                     $tag);
+        $xs->elementEnd('span');
+        return $xs->getString();
     } else {
         return $tag;
     }
@@ -640,7 +692,7 @@ function common_relative_profile($sender, $nickname, $dt=null)
     $recipient = new Profile();
     // XXX: use a join instead of a subquery
     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
-    $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
+    $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
     if ($recipient->find(true)) {
         // XXX: should probably differentiate between profiles with
         // the same name by date of most recent update
@@ -650,7 +702,7 @@ function common_relative_profile($sender, $nickname, $dt=null)
     $recipient = new Profile();
     // XXX: use a join instead of a subquery
     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
-    $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
+    $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
     if ($recipient->find(true)) {
         // XXX: should probably differentiate between profiles with
         // the same name by date of most recent update
@@ -670,29 +722,48 @@ function common_relative_profile($sender, $nickname, $dt=null)
     return null;
 }
 
-function common_local_url($action, $args=null, $fragment=null)
+function common_local_url($action, $args=null, $params=null, $fragment=null)
 {
-    common_debug("Action = $action, args = " . (($args) ? '(' . implode($args, ',') . ')' : $args) . ", fragment = $fragment");
+    static $sensitive = array('login', 'register', 'passwordsettings',
+                              'twittersettings', 'finishopenidlogin',
+                              'finishaddopenid', 'api');
+
     $r = Router::get();
-    $start = microtime();
-    $path = $r->build($action, $args, $fragment);
-    $end = microtime();
-    common_debug("Pathbuilding took " . ($end - $start));
-    if ($path) {
-    }
+    $path = $r->build($action, $args, $params, $fragment);
+
+    $ssl = in_array($action, $sensitive);
+
     if (common_config('site','fancy')) {
-        $url = common_path(mb_substr($path, 1));
+        $url = common_path(mb_substr($path, 1), $ssl);
     } else {
-        $url = common_path('index.php'.$path);
+        if (mb_strpos($path, '/index.php') === 0) {
+            $url = common_path(mb_substr($path, 1), $ssl);
+        } else {
+            $url = common_path('index.php'.$path, $ssl);
+        }
     }
     return $url;
 }
 
-function common_path($relative)
+function common_path($relative, $ssl=false)
 {
-    global $config;
-    $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
-    return "http://".$config['site']['server'].'/'.$pathpart.$relative;
+    $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
+
+    if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
+        || common_config('site', 'ssl') === 'always') {
+        $proto = 'https';
+        if (is_string(common_config('site', 'sslserver')) &&
+            mb_strlen(common_config('site', 'sslserver')) > 0) {
+            $serverpart = common_config('site', 'sslserver');
+        } else {
+            $serverpart = common_config('site', 'server');
+        }
+    } else {
+        $proto = 'http';
+        $serverpart = common_config('site', 'server');
+    }
+
+    return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
 }
 
 function common_date_string($dt)
@@ -782,7 +853,7 @@ function common_redirect($url, $code=307)
                            303 => "See Other",
                            307 => "Temporary Redirect");
 
-    header("Status: ${code} $status[$code]");
+    header('HTTP/1.1 '.$code.' '.$status[$code]);
     header("Location: $url");
 
     $xo = new XMLOutputter();
@@ -808,7 +879,7 @@ function common_broadcast_notice($notice, $remote=false)
 
 function common_enqueue_notice($notice)
 {
-    foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
+    foreach (array('jabber', 'omb', 'sms', 'public', 'twitter', 'facebook', 'ping') as $transport) {
         $qi = new Queue_item();
         $qi->notice_id = $notice->id;
         $qi->transport = $transport;
@@ -861,7 +932,9 @@ function common_real_broadcast($notice, $remote=false)
             common_log(LOG_ERR, 'Error in Twitter broadcast for notice ' . $notice->id);
         }
     }
-    
+
+    // XXX: Do a real-time FB broadcast here?
+
     // XXX: broadcast notices to other IM
     return $success;
 }
@@ -882,9 +955,9 @@ function common_profile_url($nickname)
 
 // Should make up a reasonable root URL
 
-function common_root_url()
+function common_root_url($ssl=false)
 {
-    return common_path('');
+    return common_path('', $ssl);
 }
 
 // returns $bytes bytes of random data as a hexadecimal string
@@ -943,8 +1016,7 @@ function common_ensure_syslog()
 {
     static $initialized = false;
     if (!$initialized) {
-        global $config;
-        openlog($config['syslog']['appname'], 0, LOG_USER);
+        openlog(common_config('syslog', 'appname'), 0, LOG_USER);
         $initialized = true;
     }
 }
@@ -1254,3 +1326,16 @@ function common_compatible_license($from, $to)
     // XXX: better compatibility check needed here!
     return ($from == $to);
 }
+
+/**
+ * returns a quoted table name, if required according to config
+ */
+function common_database_tablename($tablename)
+{
+  
+  if(common_config('db','quote_identifiers')) {
+      $tablename = '"'. $tablename .'"';
+  }
+  //table prefixes could be added here later
+  return $tablename;
+}