]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Safe_DataObject.php
6aed88ae1f67501d1e1af30ffe6995b0cc469f70
[quix0rs-gnu-social.git] / classes / Safe_DataObject.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('GNUSOCIAL')) { exit(1); }
21
22 /**
23  * Extended DB_DataObject to improve a few things:
24  * - free global resources from destructor
25  * - remove bogus global references from serialized objects
26  * - don't leak memory when loading already-used .ini files
27  *   (eg when using the same schema on thousands of databases)
28  */
29 class Safe_DataObject extends GS_DataObject
30 {
31     /**
32      * Destructor to free global memory resources associated with
33      * this data object when it's unset or goes out of scope.
34      * DB_DataObject doesn't do this yet by itself.
35      */
36
37     function __destruct()
38     {
39         $this->free();
40         if (method_exists('DB_DataObject', '__destruct')) {
41             parent::__destruct();
42         }
43     }
44
45     /**
46      * Magic function called at clone() time.
47      *
48      * We use this to drop connection with some global resources.
49      * This supports the fairly common pattern where individual
50      * items being read in a loop via a single object are cloned
51      * for individual processing, then fall out of scope when the
52      * loop comes around again.
53      *
54      * As that triggers the destructor, we want to make sure that
55      * the original object doesn't have its database result killed.
56      * It will still be freed properly when the original object
57      * gets destroyed.
58      */
59     function __clone()
60     {
61         $this->_DB_resultid = false;
62     }
63
64     /**
65      * Magic function called at serialize() time.
66      *
67      * We use this to drop a couple process-specific references
68      * from DB_DataObject which can cause trouble in future
69      * processes.
70      *
71      * @return array of variable names to include in serialization.
72      */
73     function __sleep()
74     {
75         $vars = array_keys(get_object_vars($this));
76         $skip = array('_DB_resultid', '_link_loaded');
77         return array_diff($vars, $skip);
78     }
79
80     /**
81      * Magic function called at unserialize() time.
82      *
83      * Clean out some process-specific variables which might
84      * be floating around from a previous process's cached
85      * objects.
86      *
87      * Old cached objects may still have them.
88      */
89     function __wakeup()
90     {
91         // Refers to global state info from a previous process.
92         // Clear this out so we don't accidentally break global
93         // state in *this* process.
94         $this->_DB_resultid = null;
95         // We don't have any local DBO refs, so clear these out.
96         $this->_link_loaded = false;
97     }
98
99     /**
100      * Magic function called when someone attempts to call a method
101      * that doesn't exist. DB_DataObject uses this to implement
102      * setters and getters for fields, but neglects to throw an error
103      * when you just misspell an actual method name. This leads to
104      * silent failures which can cause all kinds of havoc.
105      *
106      * @param string $method
107      * @param array $params
108      * @return mixed
109      * @throws Exception
110      */
111     function __call($method, $params)
112     {
113         $return = null;
114         // Yes, that's _call with one underscore, which does the
115         // actual implementation.
116         if ($this->_call($method, $params, $return)) {
117             return $return;
118         } else {
119             // Low level exception. No need for i18n as discussed with Brion.
120             throw new Exception('Call to undefined method ' .
121                 get_class($this) . '::' . $method);
122         }
123     }
124
125     /**
126      * Work around memory-leak bugs...
127      * Had to copy-paste the whole function in order to patch a couple lines of it.
128      * Would be nice if this code was better factored.
129      *
130      * @param optional string  name of database to assign / read
131      * @param optional array   structure of database, and keys
132      * @param optional array  table links
133      *
134      * @access public
135      * @return true or PEAR:error on wrong paramenters.. or false if no file exists..
136      *              or the array(tablename => array(column_name=>type)) if called with 1 argument.. (databasename)
137      */
138     function databaseStructure()
139     {
140         global $_DB_DATAOBJECT;
141
142         // Assignment code
143
144         if ($args = func_get_args()) {
145
146             if (count($args) == 1) {
147
148                 // this returns all the tables and their structure..
149                 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
150                     $this->debug("Loading Generator as databaseStructure called with args",1);
151                 }
152
153                 $x = new DB_DataObject;
154                 $x->_database = $args[0];
155                 $this->_connect();
156                 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
157
158                 $tables = $DB->getListOf('tables');
159                 class_exists('DB_DataObject_Generator') ? '' :
160                     require_once 'DB/DataObject/Generator.php';
161
162                 foreach($tables as $table) {
163                     $y = new DB_DataObject_Generator;
164                     $y->fillTableSchema($x->_database,$table);
165                 }
166                 return $_DB_DATAOBJECT['INI'][$x->_database];
167             } else {
168
169                 $_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
170                     $_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
171
172                 if (isset($args[1])) {
173                     $_DB_DATAOBJECT['LINKS'][$args[0]] = isset($_DB_DATAOBJECT['LINKS'][$args[0]]) ?
174                         $_DB_DATAOBJECT['LINKS'][$args[0]] + $args[2] : $args[2];
175                 }
176                 return true;
177             }
178
179         }
180         if (!$this->_database) {
181             $this->_connect();
182         }
183
184         // loaded already?
185         if (!empty($_DB_DATAOBJECT['INI'][$this->_database])) {
186
187             // database loaded - but this is table is not available..
188             if (
189                     empty($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])
190                     && !empty($_DB_DATAOBJECT['CONFIG']['proxy'])
191                 ) {
192                 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
193                     $this->debug("Loading Generator to fetch Schema",1);
194                 }
195                 class_exists('DB_DataObject_Generator') ? '' :
196                     require_once 'DB/DataObject/Generator.php';
197
198
199                 $x = new DB_DataObject_Generator;
200                 $x->fillTableSchema($this->_database,$this->tableName());
201             }
202             return true;
203         }
204
205         if (empty($_DB_DATAOBJECT['CONFIG'])) {
206             self::_loadConfig();
207         }
208
209         // if you supply this with arguments, then it will take those
210         // as the database and links array...
211
212         $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
213             array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
214             array() ;
215
216         if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
217             $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
218                 $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
219                 explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
220         }
221
222         /* BEGIN CHANGED FROM UPSTREAM */
223         $_DB_DATAOBJECT['INI'][$this->_database] = $this->parseIniFiles($schemas);
224         /* END CHANGED FROM UPSTREAM */
225
226         // now have we loaded the structure..
227
228         if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
229             return true;
230         }
231         // - if not try building it..
232         if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
233             class_exists('DB_DataObject_Generator') ? '' :
234                 require_once 'DB/DataObject/Generator.php';
235
236             $x = new DB_DataObject_Generator;
237             $x->fillTableSchema($this->_database,$this->tableName());
238             // should this fail!!!???
239             return true;
240         }
241         $this->debug("Cant find database schema: {$this->_database}/{$this->tableName()} \n".
242                     "in links file data: " . print_r($_DB_DATAOBJECT['INI'],true),"databaseStructure",5);
243         // we have to die here!! - it causes chaos if we don't (including looping forever!)
244         // Low level exception. No need for i18n as discussed with Brion.
245         $this->raiseError( "Unable to load schema for database and table (turn debugging up to 5 for full error message)", DB_DATAOBJECT_ERROR_INVALIDARGS, PEAR_ERROR_DIE);
246         return false;
247     }
248
249     /** For parseIniFiles */
250     protected static $iniCache = array();
251
252     /**
253      * When switching site configurations, DB_DataObject was loading its
254      * .ini files over and over, leaking gobs of memory.
255      * This refactored helper function uses a local cache of .ini files
256      * to minimize the leaks.
257      *
258      * @param array of .ini file names $schemas
259      * @return array
260      */
261     protected function parseIniFiles(array $schemas)
262     {
263         $key = implode("|", $schemas);
264         if (!isset(Safe_DataObject::$iniCache[$key])) {
265             $data = array();
266             foreach ($schemas as $ini) {
267                 if (file_exists($ini) && is_file($ini)) {
268                     $data = array_merge($data, parse_ini_file($ini, true));
269
270                     if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
271                         if (!is_readable ($ini)) {
272                             $this->debug("ini file is not readable: $ini","databaseStructure",1);
273                         } else {
274                             $this->debug("Loaded ini file: $ini","databaseStructure",1);
275                         }
276                     }
277                 } else {
278                     if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
279                         $this->debug("Missing ini file: $ini","databaseStructure",1);
280                     }
281                 }
282             }
283             Safe_DataObject::$iniCache[$key] = $data;
284         }
285
286         return Safe_DataObject::$iniCache[$key];
287     }
288 }