3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2010, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('GNUSOCIAL')) { exit(1); }
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)
29 class Safe_DataObject extends GS_DataObject
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.
40 if (method_exists('DB_DataObject', '__destruct')) {
46 * Magic function called at clone() time.
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.
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
61 $this->_DB_resultid = false;
65 * Magic function called at serialize() time.
67 * We use this to drop a couple process-specific references
68 * from DB_DataObject which can cause trouble in future
71 * @return array of variable names to include in serialization.
75 $vars = array_keys(get_object_vars($this));
76 $skip = array('_DB_resultid', '_link_loaded');
77 return array_diff($vars, $skip);
81 * Magic function called at unserialize() time.
83 * Clean out some process-specific variables which might
84 * be floating around from a previous process's cached
87 * Old cached objects may still have them.
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;
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.
106 * @param string $method
107 * @param array $params
111 function __call($method, $params)
114 // Yes, that's _call with one underscore, which does the
115 // actual implementation.
116 if ($this->_call($method, $params, $return)) {
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);
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.
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
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)
138 function databaseStructure()
140 global $_DB_DATAOBJECT;
144 if ($args = func_get_args()) {
146 if (count($args) == 1) {
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);
153 $x = new DB_DataObject;
154 $x->_database = $args[0];
156 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
158 $tables = $DB->getListOf('tables');
159 class_exists('DB_DataObject_Generator') ? '' :
160 require_once 'DB/DataObject/Generator.php';
162 foreach($tables as $table) {
163 $y = new DB_DataObject_Generator;
164 $y->fillTableSchema($x->_database,$table);
166 return $_DB_DATAOBJECT['INI'][$x->_database];
169 $_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
170 $_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
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];
180 if (!$this->_database) {
185 if (!empty($_DB_DATAOBJECT['INI'][$this->_database])) {
187 // database loaded - but this is table is not available..
189 empty($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])
190 && !empty($_DB_DATAOBJECT['CONFIG']['proxy'])
192 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
193 $this->debug("Loading Generator to fetch Schema",1);
195 class_exists('DB_DataObject_Generator') ? '' :
196 require_once 'DB/DataObject/Generator.php';
199 $x = new DB_DataObject_Generator;
200 $x->fillTableSchema($this->_database,$this->tableName());
205 if (empty($_DB_DATAOBJECT['CONFIG'])) {
209 // if you supply this with arguments, then it will take those
210 // as the database and links array...
212 $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
213 array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
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}"]);
222 /* BEGIN CHANGED FROM UPSTREAM */
223 $_DB_DATAOBJECT['INI'][$this->_database] = $this->parseIniFiles($schemas);
224 /* END CHANGED FROM UPSTREAM */
226 // now have we loaded the structure..
228 if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
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';
236 $x = new DB_DataObject_Generator;
237 $x->fillTableSchema($this->_database,$this->tableName());
238 // should this fail!!!???
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);
249 /** For parseIniFiles */
250 protected static $iniCache = array();
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.
258 * @param array of .ini file names $schemas
261 protected function parseIniFiles(array $schemas)
263 $key = implode("|", $schemas);
264 if (!isset(Safe_DataObject::$iniCache[$key])) {
266 foreach ($schemas as $ini) {
267 if (file_exists($ini) && is_file($ini)) {
268 $data = array_merge($data, parse_ini_file($ini, true));
270 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
271 if (!is_readable ($ini)) {
272 $this->debug("ini file is not readable: $ini","databaseStructure",1);
274 $this->debug("Loaded ini file: $ini","databaseStructure",1);
278 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
279 $this->debug("Missing ini file: $ini","databaseStructure",1);
283 Safe_DataObject::$iniCache[$key] = $data;
286 return Safe_DataObject::$iniCache[$key];