]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Safe_DataObject.php
Merge branch 'testing' into 0.9.x
[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('STATUSNET') && !defined('LACONICA')) { 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 DB_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             throw new Exception('Call to undefined method ' .
120                 get_class($this) . '::' . $method);
121         }
122     }
123
124     /**
125      * Work around memory-leak bugs...
126      * Had to copy-paste the whole function in order to patch a couple lines of it.
127      * Would be nice if this code was better factored.
128      *     
129      * @param optional string  name of database to assign / read
130      * @param optional array   structure of database, and keys
131      * @param optional array  table links
132      *
133      * @access public
134      * @return true or PEAR:error on wrong paramenters.. or false if no file exists..
135      *              or the array(tablename => array(column_name=>type)) if called with 1 argument.. (databasename)
136      */
137     function databaseStructure()
138     {
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         
181         
182         
183         if (!$this->_database) {
184             $this->_connect();
185         }
186         
187         // loaded already?
188         if (!empty($_DB_DATAOBJECT['INI'][$this->_database])) {
189             
190             // database loaded - but this is table is not available..
191             if (
192                     empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) 
193                     && !empty($_DB_DATAOBJECT['CONFIG']['proxy'])
194                 ) {
195                 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
196                     $this->debug("Loading Generator to fetch Schema",1);
197                 }
198                 class_exists('DB_DataObject_Generator') ? '' : 
199                     require_once 'DB/DataObject/Generator.php';
200                     
201                 
202                 $x = new DB_DataObject_Generator;
203                 $x->fillTableSchema($this->_database,$this->__table);
204             }
205             return true;
206         }
207         
208         
209         if (empty($_DB_DATAOBJECT['CONFIG'])) {
210             DB_DataObject::_loadConfig();
211         }
212         
213         // if you supply this with arguments, then it will take those
214         // as the database and links array...
215          
216         $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
217             array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
218             array() ;
219                  
220         if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
221             $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
222                 $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
223                 explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
224         }
225                     
226          
227         /* BEGIN CHANGED FROM UPSTREAM */
228         $_DB_DATAOBJECT['INI'][$this->_database] = $this->parseIniFiles($schemas);
229         /* END CHANGED FROM UPSTREAM */
230
231         // now have we loaded the structure.. 
232         
233         if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
234             return true;
235         }
236         // - if not try building it..
237         if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
238             class_exists('DB_DataObject_Generator') ? '' : 
239                 require_once 'DB/DataObject/Generator.php';
240                 
241             $x = new DB_DataObject_Generator;
242             $x->fillTableSchema($this->_database,$this->__table);
243             // should this fail!!!???
244             return true;
245         }
246         $this->debug("Cant find database schema: {$this->_database}/{$this->__table} \n".
247                     "in links file data: " . print_r($_DB_DATAOBJECT['INI'],true),"databaseStructure",5);
248         // we have to die here!! - it causes chaos if we dont (including looping forever!)
249         $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);
250         return false;
251     }
252
253     /** For parseIniFiles */
254     protected static $iniCache = array();
255
256     /**
257      * When switching site configurations, DB_DataObject was loading its
258      * .ini files over and over, leaking gobs of memory.
259      * This refactored helper function uses a local cache of .ini files
260      * to minimize the leaks.
261      *
262      * @param array of .ini file names $schemas
263      * @return array
264      */
265     protected function parseIniFiles($schemas)
266     {
267         $key = implode("|", $schemas);
268         if (!isset(Safe_DataObject::$iniCache[$key])) {
269             $data = array();
270             foreach ($schemas as $ini) {
271                 if (file_exists($ini) && is_file($ini)) {
272                     $data = array_merge($data, parse_ini_file($ini, true));
273
274                     if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) { 
275                         if (!is_readable ($ini)) {
276                             $this->debug("ini file is not readable: $ini","databaseStructure",1);
277                         } else {
278                             $this->debug("Loaded ini file: $ini","databaseStructure",1);
279                         }
280                     }
281                 } else {
282                     if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
283                         $this->debug("Missing ini file: $ini","databaseStructure",1);
284                     }
285                 }
286             }
287             Safe_DataObject::$iniCache[$key] = $data;
288         }
289
290         return Safe_DataObject::$iniCache[$key];
291     }
292 }
293