]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Status_network.php
Merge branch '1.0.x' into testing
[quix0rs-gnu-social.git] / classes / Status_network.php
1 <?php
2 /**
3  * Table Definition for status_network
4  *
5  * StatusNet - the distributed open-source microblogging tool
6  * Copyright (C) 2009, StatusNet, Inc.
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU Affero General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU Affero General Public License for more details.
17  *
18  * You should have received a copy of the GNU Affero General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
23
24 class Status_network extends Safe_DataObject
25 {
26     ###START_AUTOCODE
27     /* the code below is auto generated do not remove the above tag */
28
29     public $__table = 'status_network';                  // table name
30     public $site_id;                         // int(4) primary_key not_null
31     public $nickname;                        // varchar(64)   unique_key not_null
32     public $hostname;                        // varchar(255)  unique_key
33     public $pathname;                        // varchar(255)  unique_key
34     public $dbhost;                          // varchar(255)
35     public $dbuser;                          // varchar(255)
36     public $dbpass;                          // varchar(255)
37     public $dbname;                          // varchar(255)
38     public $sitename;                        // varchar(255)
39     public $theme;                           // varchar(255)
40     public $logo;                            // varchar(255)
41     public $created;                         // datetime()   not_null
42     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
43
44     /* Static get */
45     function staticGet($k,$v=NULL) {
46         $i = DB_DataObject::staticGet('Status_network',$k,$v);
47
48         // Don't use local process cache; if we're fetching multiple
49         // times it's because we're reloading it in a long-running
50         // process; we need a fresh copy!
51         global $_DB_DATAOBJECT;
52         unset($_DB_DATAOBJECT['CACHE']['status_network']);
53         return $i;
54     }
55
56     /* the code above is auto generated do not remove the tag below */
57     ###END_AUTOCODE
58
59     // XXX: made public so Status_network_tag can eff with it
60     public static $cache = null;
61     public static $cacheInitialized = false;
62     static $base = null;
63     static $wildcard = null;
64
65     /**
66      * @param string $dbhost
67      * @param string $dbuser
68      * @param string $dbpass
69      * @param string $dbname
70      * @param array $servers memcached servers to use for caching config info
71      */
72     static function setupDB($dbhost, $dbuser, $dbpass, $dbname, $servers)
73     {
74         global $config;
75
76         $config['db']['database_'.$dbname] = "mysqli://$dbuser:$dbpass@$dbhost/$dbname";
77         $config['db']['ini_'.$dbname] = INSTALLDIR.'/classes/status_network.ini';
78
79         foreach (array('status_network', 'status_network_tag', 'unavailable_status_network') as $table) {
80             $config['db']['table_'.$table] = $dbname;
81         }
82
83         if (class_exists('Memcache')) {
84             self::$cache = new Memcache();
85
86             // If we're a parent command-line process we need
87             // to be able to close out the connection after
88             // forking, so disable persistence.
89             //
90             // We'll turn it back on again the second time
91             // through which will either be in a child process,
92             // or a single-process script which is switching
93             // configurations.
94             $persist = php_sapi_name() != 'cli' || self::$cacheInitialized;
95             if (!is_array($servers)) {
96                 $servers = array($servers);
97             } 
98             foreach($servers as $server) {
99                 $parts = explode(':', $server);
100                 $server = $parts[0];
101                 if (count($parts) > 1) {
102                     $port = $parts[1];
103                 } else {
104                     $port = 11211;
105                 }
106                 self::$cache->addServer($server, $port, $persist);
107             }
108             self::$cacheInitialized = true;
109         }
110
111         self::$base = $dbname;
112     }
113
114     static function cacheKey($k, $v) {
115         return 'statusnet:' . self::$base . ':status_network:'.$k.':'.$v;
116     }
117
118     static function memGet($k, $v)
119     {
120         if (!self::$cache) {
121             return self::staticGet($k, $v);
122         }
123
124         $ck = self::cacheKey($k, $v);
125
126         $sn = self::$cache->get($ck);
127
128         if (empty($sn)) {
129             $sn = self::staticGet($k, $v);
130             if (!empty($sn)) {
131                 self::$cache->set($ck, clone($sn));
132             }
133         }
134
135         return $sn;
136     }
137
138     function decache()
139     {
140         if (self::$cache) {
141             $keys = array('nickname', 'hostname', 'pathname');
142             foreach ($keys as $k) {
143                 $ck = self::cacheKey($k, $this->$k);
144                 self::$cache->delete($ck);
145             }
146         }
147     }
148
149     function update($orig=null)
150     {
151         if (is_object($orig)) {
152             $orig->decache(); # might be different keys
153         }
154         return parent::update($orig);
155     }
156
157     /**
158      * DB_DataObject doesn't allow updating keys (even non-primary)
159      */
160     function updateKeys(&$orig)
161     {
162         $this->_connect();
163         foreach (array('hostname', 'pathname') as $k) {
164             if (strcmp($this->$k, $orig->$k) != 0) {
165                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
166             }
167         }
168         if (count($parts) == 0) {
169             // No changes
170             return true;
171         }
172
173         $toupdate = implode(', ', $parts);
174
175         $table = common_database_tablename($this->tableName());
176         $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
177             ' WHERE nickname = ' . $this->_quote($this->nickname);
178         $orig->decache();
179         $result = $this->query($qry);
180         $this->decache();
181
182         return $result;
183     }
184
185     function delete()
186     {
187         $this->decache(); # while we still have the values!
188         return parent::delete();
189     }
190
191     /**
192      * @param string $servername hostname
193      * @param string $wildcard hostname suffix to match wildcard config
194      * @return mixed Status_network or null
195      */
196     static function getFromHostname($servername, $wildcard)
197     {
198         $sn = null;
199         if (0 == strncasecmp(strrev($wildcard), strrev($servername), strlen($wildcard))) {
200             // special case for exact match
201             if (0 == strcasecmp($servername, $wildcard)) {
202                 $sn = self::memGet('nickname', '');
203             } else {
204                 $parts = explode('.', $servername);
205                 $sn = self::memGet('nickname', strtolower($parts[0]));
206             }
207         } else {
208             $sn = self::memGet('hostname', strtolower($servername));
209
210             if (empty($sn)) {
211                 // Try for a no-www address
212                 if (0 == strncasecmp($servername, 'www.', 4)) {
213                     $sn = self::memGet('hostname', strtolower(substr($servername, 4)));
214                 }
215             }
216         }
217         return $sn;
218     }
219
220     /**
221      * @param string $servername hostname
222      * @param string $pathname URL base path
223      * @param string $wildcard hostname suffix to match wildcard config
224      */
225     static function setupSite($servername, $pathname, $wildcard)
226     {
227         global $config;
228
229         $sn = null;
230
231         // XXX I18N, probably not crucial for hostnames
232         // XXX This probably needs a tune up
233         $sn = self::getFromHostname($servername, $wildcard);
234
235         if (!empty($sn)) {
236
237             // Redirect to the right URL
238
239             if (!empty($sn->hostname) &&
240                 empty($_SERVER['HTTPS']) &&
241                 0 != strcasecmp($sn->hostname, $servername)) {
242                 $sn->redirectTo('http://'.$sn->hostname.$_SERVER['REQUEST_URI']);
243             } else if (!empty($_SERVER['HTTPS']) &&
244                        0 != strcasecmp($sn->hostname, $servername) &&
245                        0 != strcasecmp($sn->nickname.'.'.$wildcard, $servername)) {
246                 $sn->redirectTo('https://'.$sn->nickname.'.'.$wildcard.$_SERVER['REQUEST_URI']);
247             }
248
249             $dbhost = (empty($sn->dbhost)) ? 'localhost' : $sn->dbhost;
250             $dbuser = (empty($sn->dbuser)) ? $sn->nickname : $sn->dbuser;
251             $dbpass = $sn->dbpass;
252             $dbname = (empty($sn->dbname)) ? $sn->nickname : $sn->dbname;
253
254             $config['db']['database'] = "mysqli://$dbuser:$dbpass@$dbhost/$dbname";
255
256             $config['site']['name'] = $sn->sitename;
257             $config['site']['nickname'] = $sn->nickname;
258
259             self::$wildcard = $wildcard;
260
261             $config['site']['wildcard'] =& self::$wildcard;
262
263             if (!empty($sn->hostname)) {
264                 $config['site']['server'] = $sn->hostname;
265             }
266
267             if (!empty($sn->theme)) {
268                 $config['site']['theme'] = $sn->theme;
269             }
270             if (!empty($sn->logo)) {
271                 $config['site']['logo'] = $sn->logo;
272             }
273
274             return $sn;
275         } else {
276             return null;
277         }
278     }
279
280     // Code partially mooked from http://www.richler.de/en/php-redirect/
281     // (C) 2006 by Heiko Richler  http://www.richler.de/
282     // LGPL
283
284     function redirectTo($destination)
285     {
286         $old = 'http'.
287           (($_SERVER['HTTPS'] == 'on') ? 'S' : '').
288           '://'.
289           $_SERVER['HTTP_HOST'].
290           $_SERVER['REQUEST_URI'].
291           $_SERVER['QUERY_STRING'];
292         if ($old == $destination) { // this would be a loop!
293             // error_log(...) ?
294             return false;
295         }
296
297         header('HTTP/1.1 301 Moved Permanently');
298         header("Location: $destination");
299
300         print "<a href='$destination'>$destination</a>\n";
301
302         exit;
303     }
304
305     function getServerName()
306     {
307         if (!empty($this->hostname)) {
308             return $this->hostname;
309         } else {
310             return $this->nickname . '.' . self::$wildcard;
311         }
312     }
313
314     /**
315      * Return site meta-info tags as an array
316      * @return array of strings
317      */
318     function getTags()
319     {
320         $result = Status_network_tag::getTags($this->site_id);
321
322         // XXX : for backwards compatibility
323         if (empty($result)) {
324             return explode('|', $this->tags);
325         }
326
327         return $result;
328     }
329
330     /**
331      * Save a given set of tags
332      * @param array tags
333      * @fixme only add/remove differentials
334      */
335     function setTags($tags)
336     {
337         $this->clearTags();
338         foreach ($tags as $tag) {
339             if (!empty($tag)) {
340                 $snt = new Status_network_tag();
341                 $snt->site_id = $this->site_id;
342                 $snt->tag = $tag;
343                 $snt->created = common_sql_now();
344
345                 $id = $snt->insert();
346                 if (!$id) {
347                     // TRANS: Exception thrown when a tag cannot be saved.
348                     throw new Exception(_("Unable to save tag."));
349                 }
350             }
351         }
352
353         return true;
354     }
355
356     function clearTags()
357     {
358         $tag = new Status_network_tag();
359         $tag->site_id = $this->site_id;
360
361         if ($tag->find()) {
362             while($tag->fetch()) {
363                 $tag->delete();
364             }
365         }
366
367         $tag->free();
368     }
369
370     /**
371      * Check if this site record has a particular meta-info tag attached.
372      * @param string $tag
373      * @return bool
374      */
375     function hasTag($tag)
376     {
377         return in_array($tag, $this->getTags());
378     }
379 }