]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Status_network.php
Merge branch 'master' 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     static $cache = null;
60     static $cacheInitialized = false;
61     static $base = null;
62     static $wildcard = null;
63
64     /**
65      * @param string $dbhost
66      * @param string $dbuser
67      * @param string $dbpass
68      * @param string $dbname
69      * @param array $servers memcached servers to use for caching config info
70      */
71     static function setupDB($dbhost, $dbuser, $dbpass, $dbname, $servers)
72     {
73         global $config;
74
75         $config['db']['database_'.$dbname] = "mysqli://$dbuser:$dbpass@$dbhost/$dbname";
76         $config['db']['ini_'.$dbname] = INSTALLDIR.'/classes/status_network.ini';
77
78         foreach (array('status_network', 'status_network_tag', 'unavailable_status_network') as $table) {
79             $config['db']['table_'.$table] = $dbname;
80         }
81
82         if (class_exists('Memcache')) {
83             self::$cache = new Memcache();
84
85             // If we're a parent command-line process we need
86             // to be able to close out the connection after
87             // forking, so disable persistence.
88             //
89             // We'll turn it back on again the second time
90             // through which will either be in a child process,
91             // or a single-process script which is switching
92             // configurations.
93             $persist = php_sapi_name() != 'cli' || self::$cacheInitialized;
94             if (is_array($servers)) {
95                 foreach($servers as $server) {
96                     self::$cache->addServer($server, 11211, $persist);
97                 }
98             } else {
99                 self::$cache->addServer($servers, 11211, $persist);
100             }
101             self::$cacheInitialized = true;
102         }
103
104         self::$base = $dbname;
105     }
106
107     static function cacheKey($k, $v) {
108         return 'statusnet:' . self::$base . ':status_network:'.$k.':'.$v;
109     }
110
111     static function memGet($k, $v)
112     {
113         if (!self::$cache) {
114             return self::staticGet($k, $v);
115         }
116
117         $ck = self::cacheKey($k, $v);
118
119         $sn = self::$cache->get($ck);
120
121         if (empty($sn)) {
122             $sn = self::staticGet($k, $v);
123             if (!empty($sn)) {
124                 self::$cache->set($ck, clone($sn));
125             }
126         }
127
128         return $sn;
129     }
130
131     function decache()
132     {
133         if (self::$cache) {
134             $keys = array('nickname', 'hostname', 'pathname');
135             foreach ($keys as $k) {
136                 $ck = self::cacheKey($k, $this->$k);
137                 self::$cache->delete($ck);
138             }
139         }
140     }
141
142     function update($orig=null)
143     {
144         if (is_object($orig)) {
145             $orig->decache(); # might be different keys
146         }
147         return parent::update($orig);
148     }
149
150     /**
151      * DB_DataObject doesn't allow updating keys (even non-primary)
152      */
153     function updateKeys(&$orig)
154     {
155         $this->_connect();
156         foreach (array('hostname', 'pathname') as $k) {
157             if (strcmp($this->$k, $orig->$k) != 0) {
158                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
159             }
160         }
161         if (count($parts) == 0) {
162             // No changes
163             return true;
164         }
165
166         $toupdate = implode(', ', $parts);
167
168         $table = common_database_tablename($this->tableName());
169         $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
170             ' WHERE nickname = ' . $this->_quote($this->nickname);
171         $orig->decache();
172         $result = $this->query($qry);
173         $this->decache();
174
175         return $result;
176     }
177
178     function delete()
179     {
180         $this->decache(); # while we still have the values!
181         return parent::delete();
182     }
183
184     /**
185      * @param string $servername hostname
186      * @param string $wildcard hostname suffix to match wildcard config
187      * @return mixed Status_network or null
188      */
189     static function getFromHostname($servername, $wildcard)
190     {
191         $sn = null;
192         if (0 == strncasecmp(strrev($wildcard), strrev($servername), strlen($wildcard))) {
193             // special case for exact match
194             if (0 == strcasecmp($servername, $wildcard)) {
195                 $sn = self::memGet('nickname', '');
196             } else {
197                 $parts = explode('.', $servername);
198                 $sn = self::memGet('nickname', strtolower($parts[0]));
199             }
200         } else {
201             $sn = self::memGet('hostname', strtolower($servername));
202
203             if (empty($sn)) {
204                 // Try for a no-www address
205                 if (0 == strncasecmp($servername, 'www.', 4)) {
206                     $sn = self::memGet('hostname', strtolower(substr($servername, 4)));
207                 }
208             }
209         }
210         return $sn;
211     }
212
213     /**
214      * @param string $servername hostname
215      * @param string $pathname URL base path
216      * @param string $wildcard hostname suffix to match wildcard config
217      */
218     static function setupSite($servername, $pathname, $wildcard)
219     {
220         global $config;
221
222         $sn = null;
223
224         // XXX I18N, probably not crucial for hostnames
225         // XXX This probably needs a tune up
226         $sn = self::getFromHostname($servername, $wildcard);
227
228         if (!empty($sn)) {
229
230             // Redirect to the right URL
231
232             if (!empty($sn->hostname) &&
233                 empty($_SERVER['HTTPS']) &&
234                 0 != strcasecmp($sn->hostname, $servername)) {
235                 $sn->redirectTo('http://'.$sn->hostname.$_SERVER['REQUEST_URI']);
236             } else if (!empty($_SERVER['HTTPS']) &&
237                        0 != strcasecmp($sn->hostname, $servername) &&
238                        0 != strcasecmp($sn->nickname.'.'.$wildcard, $servername)) {
239                 $sn->redirectTo('https://'.$sn->nickname.'.'.$wildcard.$_SERVER['REQUEST_URI']);
240             }
241
242             $dbhost = (empty($sn->dbhost)) ? 'localhost' : $sn->dbhost;
243             $dbuser = (empty($sn->dbuser)) ? $sn->nickname : $sn->dbuser;
244             $dbpass = $sn->dbpass;
245             $dbname = (empty($sn->dbname)) ? $sn->nickname : $sn->dbname;
246
247             $config['db']['database'] = "mysqli://$dbuser:$dbpass@$dbhost/$dbname";
248
249             $config['site']['name'] = $sn->sitename;
250             $config['site']['nickname'] = $sn->nickname;
251
252             self::$wildcard = $wildcard;
253
254             $config['site']['wildcard'] =& self::$wildcard;
255
256             if (!empty($sn->hostname)) {
257                 $config['site']['server'] = $sn->hostname;
258             }
259
260             if (!empty($sn->theme)) {
261                 $config['site']['theme'] = $sn->theme;
262             }
263             if (!empty($sn->logo)) {
264                 $config['site']['logo'] = $sn->logo;
265             }
266
267             return $sn;
268         } else {
269             return null;
270         }
271     }
272
273     // Code partially mooked from http://www.richler.de/en/php-redirect/
274     // (C) 2006 by Heiko Richler  http://www.richler.de/
275     // LGPL
276
277     function redirectTo($destination)
278     {
279         $old = 'http'.
280           (($_SERVER['HTTPS'] == 'on') ? 'S' : '').
281           '://'.
282           $_SERVER['HTTP_HOST'].
283           $_SERVER['REQUEST_URI'].
284           $_SERVER['QUERY_STRING'];
285         if ($old == $destination) { // this would be a loop!
286             // error_log(...) ?
287             return false;
288         }
289
290         header('HTTP/1.1 301 Moved Permanently');
291         header("Location: $destination");
292
293         print "<a href='$destination'>$destination</a>\n";
294
295         exit;
296     }
297
298     function getServerName()
299     {
300         if (!empty($this->hostname)) {
301             return $this->hostname;
302         } else {
303             return $this->nickname . '.' . self::$wildcard;
304         }
305     }
306
307     /**
308      * Return site meta-info tags as an array
309      * @return array of strings
310      */
311     function getTags()
312     {
313         $result = Status_network_tag::getTags($this->site_id);
314
315         // XXX : for backwards compatibility
316         if (empty($result)) {
317             return explode('|', $this->tags);
318         }
319
320         return $result;
321     }
322
323     /**
324      * Save a given set of tags
325      * @param array tags
326      * @fixme only add/remove differentials
327      */
328     function setTags($tags)
329     {
330         $this->clearTags();
331         foreach ($tags as $tag) {
332             if (!empty($tag)) {
333                 $snt = new Status_network_tag();
334                 $snt->site_id = $this->site_id;
335                 $snt->tag = $tag;
336                 $snt->created = common_sql_now();
337
338                 $id = $snt->insert();
339                 if (!$id) {
340                     // TRANS: Exception thrown when a tag cannot be saved.
341                     throw new Exception(_("Unable to save tag."));
342                 }
343             }
344         }
345
346         return true;
347     }
348
349     function clearTags()
350     {
351         $tag = new Status_network_tag();
352         $tag->site_id = $this->site_id;
353
354         if ($tag->find()) {
355             while($tag->fetch()) {
356                 $tag->delete();
357             }
358         }
359
360         $tag->free();
361     }
362
363     /**
364      * Check if this site record has a particular meta-info tag attached.
365      * @param string $tag
366      * @return bool
367      */
368     function hasTag($tag)
369     {
370         return in_array($tag, $this->getTags());
371     }
372 }