]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Status_network.php
Misses this file to merge. I like the comments.
[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(191)  unique_key   not 255 because utf8mb4 takes more space
33     public $pathname;                        // varchar(191)  unique_key   not 255 because utf8mb4 takes more space
34     public $dbhost;                          // varchar(191)               not 255 because utf8mb4 takes more space
35     public $dbuser;                          // varchar(191)               not 255 because utf8mb4 takes more space
36     public $dbpass;                          // varchar(191)               not 255 because utf8mb4 takes more space
37     public $dbname;                          // varchar(191)               not 255 because utf8mb4 takes more space
38     public $sitename;                        // varchar(191)               not 255 because utf8mb4 takes more space
39     public $theme;                           // varchar(191)               not 255 because utf8mb4 takes more space
40     public $logo;                            // varchar(191)               not 255 because utf8mb4 takes more space
41     public $created;                         // datetime()   not_null
42     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
43
44     /* Static get */
45     static function getKV($k,$v=NULL) {
46         // TODO: This must probably be turned into a non-static call
47         $i = DB_DataObject::staticGet('Status_network',$k,$v);
48
49         // Don't use local process cache; if we're fetching multiple
50         // times it's because we're reloading it in a long-running
51         // process; we need a fresh copy!
52         global $_DB_DATAOBJECT;
53         unset($_DB_DATAOBJECT['CACHE']['status_network']);
54         return $i;
55     }
56
57     /* the code above is auto generated do not remove the tag below */
58     ###END_AUTOCODE
59
60     // XXX: made public so Status_network_tag can eff with it
61     public static $cache = null;
62     public static $cacheInitialized = false;
63     static $base = null;
64     static $wildcard = null;
65
66     /**
67      * @param string $dbhost
68      * @param string $dbuser
69      * @param string $dbpass
70      * @param string $dbname
71      * @param array $servers memcached servers to use for caching config info
72      */
73     static function setupDB($dbhost, $dbuser, $dbpass, $dbname, array $servers)
74     {
75         global $config;
76
77         $config['db']['database_'.$dbname] = "mysqli://$dbuser:$dbpass@$dbhost/$dbname";
78         $config['db']['ini_'.$dbname] = INSTALLDIR.'/classes/status_network.ini';
79
80         foreach (array('status_network', 'status_network_tag', 'unavailable_status_network') as $table) {
81             $config['db']['table_'.$table] = $dbname;
82         }
83
84         if (class_exists('Memcache')) {
85             self::$cache = new Memcache();
86
87             // If we're a parent command-line process we need
88             // to be able to close out the connection after
89             // forking, so disable persistence.
90             //
91             // We'll turn it back on again the second time
92             // through which will either be in a child process,
93             // or a single-process script which is switching
94             // configurations.
95             $persist = php_sapi_name() != 'cli' || self::$cacheInitialized;
96             if (!is_array($servers)) {
97                 $servers = array($servers);
98             } 
99             foreach($servers as $server) {
100                 $parts = explode(':', $server);
101                 $server = $parts[0];
102                 if (count($parts) > 1) {
103                     $port = $parts[1];
104                 } else {
105                     $port = 11211;
106                 }
107                 self::$cache->addServer($server, $port, $persist);
108             }
109             self::$cacheInitialized = true;
110         }
111
112         self::$base = $dbname;
113     }
114
115     static function cacheKey($k, $v) {
116         return 'gnusocial:' . self::$base . ':status_network:'.$k.':'.$v;
117     }
118
119     static function memGet($k, $v)
120     {
121         if (!self::$cache) {
122             return self::getKV($k, $v);
123         }
124
125         $ck = self::cacheKey($k, $v);
126
127         $sn = self::$cache->get($ck);
128
129         if (empty($sn)) {
130             $sn = self::getKV($k, $v);
131             if (!empty($sn)) {
132                 self::$cache->set($ck, clone($sn));
133             }
134         }
135
136         return $sn;
137     }
138
139     function decache()
140     {
141         if (self::$cache) {
142             $keys = array('nickname', 'hostname', 'pathname');
143             foreach ($keys as $k) {
144                 $ck = self::cacheKey($k, $this->$k);
145                 self::$cache->delete($ck);
146             }
147         }
148     }
149
150     function update($dataObject=false)
151     {
152         if (is_object($dataObject)) {
153             $dataObject->decache(); # might be different keys
154         }
155         return parent::update($dataObject);
156     }
157
158     /**
159      * DB_DataObject doesn't allow updating keys (even non-primary)
160      */
161     function updateKeys(&$orig)
162     {
163         $this->_connect();
164         foreach (array('hostname', 'pathname') as $k) {
165             if (strcmp($this->$k, $orig->$k) != 0) {
166                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
167             }
168         }
169         if (count($parts) == 0) {
170             // No changes
171             return true;
172         }
173
174         $toupdate = implode(', ', $parts);
175
176         $table = common_database_tablename($this->tableName());
177         $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
178             ' WHERE nickname = ' . $this->_quote($this->nickname);
179         $orig->decache();
180         $result = $this->query($qry);
181         $this->decache();
182
183         return $result;
184     }
185
186     function delete($useWhere=false)
187     {
188         $this->decache(); # while we still have the values!
189         return parent::delete($useWhere);
190     }
191
192     /**
193      * @param string $servername hostname
194      * @param string $wildcard hostname suffix to match wildcard config
195      * @return mixed Status_network or null
196      */
197     static function getFromHostname($servername, $wildcard)
198     {
199         $sn = null;
200         if (0 == strncasecmp(strrev($wildcard), strrev($servername), strlen($wildcard))) {
201             // special case for exact match
202             if (0 == strcasecmp($servername, $wildcard)) {
203                 $sn = self::memGet('nickname', '');
204             } else {
205                 $parts = explode('.', $servername);
206                 $sn = self::memGet('nickname', strtolower($parts[0]));
207             }
208         } else {
209             $sn = self::memGet('hostname', strtolower($servername));
210
211             if (empty($sn)) {
212                 // Try for a no-www address
213                 if (0 == strncasecmp($servername, 'www.', 4)) {
214                     $sn = self::memGet('hostname', strtolower(substr($servername, 4)));
215                 }
216             }
217         }
218         return $sn;
219     }
220
221     /**
222      * @param string $servername hostname
223      * @param string $pathname URL base path
224      * @param string $wildcard hostname suffix to match wildcard config
225      */
226     static function setupSite($servername, $pathname, $wildcard)
227     {
228         global $config;
229
230         $sn = null;
231
232         // XXX I18N, probably not crucial for hostnames
233         // XXX This probably needs a tune up
234         $sn = self::getFromHostname($servername, $wildcard);
235
236         if (!empty($sn)) {
237
238             // Redirect to the right URL
239
240             if (!empty($sn->hostname) &&
241                 empty($_SERVER['HTTPS']) &&
242                 0 != strcasecmp($sn->hostname, $servername)) {
243                 $sn->redirectTo('http://'.$sn->hostname.$_SERVER['REQUEST_URI']);
244             } else if (!empty($_SERVER['HTTPS']) &&
245                        0 != strcasecmp($sn->hostname, $servername) &&
246                        0 != strcasecmp($sn->nickname.'.'.$wildcard, $servername)) {
247                 $sn->redirectTo('https://'.$sn->nickname.'.'.$wildcard.$_SERVER['REQUEST_URI']);
248             }
249
250             $dbhost = (empty($sn->dbhost)) ? 'localhost' : $sn->dbhost;
251             $dbuser = (empty($sn->dbuser)) ? $sn->nickname : $sn->dbuser;
252             $dbpass = $sn->dbpass;
253             $dbname = (empty($sn->dbname)) ? $sn->nickname : $sn->dbname;
254
255             $config['db']['database'] = "mysqli://$dbuser:$dbpass@$dbhost/$dbname";
256
257             $config['site']['name'] = $sn->sitename;
258             $config['site']['nickname'] = $sn->nickname;
259
260             self::$wildcard = $wildcard;
261
262             $config['site']['wildcard'] =& self::$wildcard;
263
264             if (!empty($sn->hostname)) {
265                 $config['site']['server'] = $sn->hostname;
266             }
267
268             if (!empty($sn->theme)) {
269                 $config['site']['theme'] = $sn->theme;
270             }
271             if (!empty($sn->logo)) {
272                 $config['site']['logo'] = $sn->logo;
273             }
274
275             return $sn;
276         } else {
277             return null;
278         }
279     }
280
281     // Code partially mooked from http://www.richler.de/en/php-redirect/
282     // (C) 2006 by Heiko Richler  http://www.richler.de/
283     // LGPL
284
285     function redirectTo($destination)
286     {
287         $old = 'http'.
288           (($_SERVER['HTTPS'] == 'on') ? 'S' : '').
289           '://'.
290           $_SERVER['HTTP_HOST'].
291           $_SERVER['REQUEST_URI'].
292           $_SERVER['QUERY_STRING'];
293         if ($old == $destination) { // this would be a loop!
294             // error_log(...) ?
295             return false;
296         }
297
298         header('HTTP/1.1 301 Moved Permanently');
299         header("Location: $destination");
300
301         print "<a href='$destination'>$destination</a>\n";
302
303         exit;
304     }
305
306     function getServerName()
307     {
308         if (!empty($this->hostname)) {
309             return $this->hostname;
310         } else {
311             return $this->nickname . '.' . self::$wildcard;
312         }
313     }
314
315     /**
316      * Return site meta-info tags as an array
317      * @return array of strings
318      */
319     function getTags()
320     {
321         return Status_network_tag::getTags($this->site_id);
322     }
323
324     /**
325      * Save a given set of tags
326      * @param array tags
327      * @fixme only add/remove differentials
328      */
329     function setTags(array $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 }