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