]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Safe_DataObject.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into testing
[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     /**
101      * Work around memory-leak bugs...
102      * Had to copy-paste the whole function in order to patch a couple lines of it.
103      * Would be nice if this code was better factored.
104      *     
105      * @param optional string  name of database to assign / read
106      * @param optional array   structure of database, and keys
107      * @param optional array  table links
108      *
109      * @access public
110      * @return true or PEAR:error on wrong paramenters.. or false if no file exists..
111      *              or the array(tablename => array(column_name=>type)) if called with 1 argument.. (databasename)
112      */
113     function databaseStructure()
114     {
115
116         global $_DB_DATAOBJECT;
117         
118         // Assignment code 
119         
120         if ($args = func_get_args()) {
121         
122             if (count($args) == 1) {
123                 
124                 // this returns all the tables and their structure..
125                 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
126                     $this->debug("Loading Generator as databaseStructure called with args",1);
127                 }
128                 
129                 $x = new DB_DataObject;
130                 $x->_database = $args[0];
131                 $this->_connect();
132                 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
133        
134                 $tables = $DB->getListOf('tables');
135                 class_exists('DB_DataObject_Generator') ? '' : 
136                     require_once 'DB/DataObject/Generator.php';
137                     
138                 foreach($tables as $table) {
139                     $y = new DB_DataObject_Generator;
140                     $y->fillTableSchema($x->_database,$table);
141                 }
142                 return $_DB_DATAOBJECT['INI'][$x->_database];            
143             } else {
144         
145                 $_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
146                     $_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
147                 
148                 if (isset($args[1])) {
149                     $_DB_DATAOBJECT['LINKS'][$args[0]] = isset($_DB_DATAOBJECT['LINKS'][$args[0]]) ?
150                         $_DB_DATAOBJECT['LINKS'][$args[0]] + $args[2] : $args[2];
151                 }
152                 return true;
153             }
154           
155         }
156         
157         
158         
159         if (!$this->_database) {
160             $this->_connect();
161         }
162         
163         // loaded already?
164         if (!empty($_DB_DATAOBJECT['INI'][$this->_database])) {
165             
166             // database loaded - but this is table is not available..
167             if (
168                     empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) 
169                     && !empty($_DB_DATAOBJECT['CONFIG']['proxy'])
170                 ) {
171                 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
172                     $this->debug("Loading Generator to fetch Schema",1);
173                 }
174                 class_exists('DB_DataObject_Generator') ? '' : 
175                     require_once 'DB/DataObject/Generator.php';
176                     
177                 
178                 $x = new DB_DataObject_Generator;
179                 $x->fillTableSchema($this->_database,$this->__table);
180             }
181             return true;
182         }
183         
184         
185         if (empty($_DB_DATAOBJECT['CONFIG'])) {
186             DB_DataObject::_loadConfig();
187         }
188         
189         // if you supply this with arguments, then it will take those
190         // as the database and links array...
191          
192         $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
193             array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
194             array() ;
195                  
196         if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
197             $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
198                 $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
199                 explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
200         }
201                     
202          
203         /* BEGIN CHANGED FROM UPSTREAM */
204         $_DB_DATAOBJECT['INI'][$this->_database] = $this->parseIniFiles($schemas);
205         /* END CHANGED FROM UPSTREAM */
206
207         // now have we loaded the structure.. 
208         
209         if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
210             return true;
211         }
212         // - if not try building it..
213         if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
214             class_exists('DB_DataObject_Generator') ? '' : 
215                 require_once 'DB/DataObject/Generator.php';
216                 
217             $x = new DB_DataObject_Generator;
218             $x->fillTableSchema($this->_database,$this->__table);
219             // should this fail!!!???
220             return true;
221         }
222         $this->debug("Cant find database schema: {$this->_database}/{$this->__table} \n".
223                     "in links file data: " . print_r($_DB_DATAOBJECT['INI'],true),"databaseStructure",5);
224         // we have to die here!! - it causes chaos if we dont (including looping forever!)
225         $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);
226         return false;
227     }
228
229     /** For parseIniFiles */
230     protected static $iniCache = array();
231
232     /**
233      * When switching site configurations, DB_DataObject was loading its
234      * .ini files over and over, leaking gobs of memory.
235      * This refactored helper function uses a local cache of .ini files
236      * to minimize the leaks.
237      *
238      * @param array of .ini file names $schemas
239      * @return array
240      */
241     protected function parseIniFiles($schemas)
242     {
243         $key = implode("|", $schemas);
244         if (!isset(Safe_DataObject::$iniCache[$key])) {
245             $data = array();
246             foreach ($schemas as $ini) {
247                 if (file_exists($ini) && is_file($ini)) {
248                     $data = array_merge($data, parse_ini_file($ini, true));
249
250                     if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) { 
251                         if (!is_readable ($ini)) {
252                             $this->debug("ini file is not readable: $ini","databaseStructure",1);
253                         } else {
254                             $this->debug("Loaded ini file: $ini","databaseStructure",1);
255                         }
256                     }
257                 } else {
258                     if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
259                         $this->debug("Missing ini file: $ini","databaseStructure",1);
260                     }
261                 }
262             }
263             Safe_DataObject::$iniCache[$key] = $data;
264         }
265
266         return Safe_DataObject::$iniCache[$key];
267     }
268 }
269