]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Safe_DataObject.php
Merge branch 'master' 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 serialize() time.
47      *
48      * We use this to drop a couple process-specific references
49      * from DB_DataObject which can cause trouble in future
50      * processes.
51      *
52      * @return array of variable names to include in serialization.
53      */
54     function __sleep()
55     {
56         $vars = array_keys(get_object_vars($this));
57         $skip = array('_DB_resultid', '_link_loaded');
58         return array_diff($vars, $skip);
59     }
60
61     /**
62      * Magic function called at unserialize() time.
63      *
64      * Clean out some process-specific variables which might
65      * be floating around from a previous process's cached
66      * objects.
67      *
68      * Old cached objects may still have them.
69      */
70     function __wakeup()
71     {
72         // Refers to global state info from a previous process.
73         // Clear this out so we don't accidentally break global
74         // state in *this* process.
75         $this->_DB_resultid = null;
76         // We don't have any local DBO refs, so clear these out.
77         $this->_link_loaded = false;
78     }
79
80
81     /**
82      * Work around memory-leak bugs...
83      * Had to copy-paste the whole function in order to patch a couple lines of it.
84      * Would be nice if this code was better factored.
85      *     
86      * @param optional string  name of database to assign / read
87      * @param optional array   structure of database, and keys
88      * @param optional array  table links
89      *
90      * @access public
91      * @return true or PEAR:error on wrong paramenters.. or false if no file exists..
92      *              or the array(tablename => array(column_name=>type)) if called with 1 argument.. (databasename)
93      */
94     function databaseStructure()
95     {
96
97         global $_DB_DATAOBJECT;
98         
99         // Assignment code 
100         
101         if ($args = func_get_args()) {
102         
103             if (count($args) == 1) {
104                 
105                 // this returns all the tables and their structure..
106                 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
107                     $this->debug("Loading Generator as databaseStructure called with args",1);
108                 }
109                 
110                 $x = new DB_DataObject;
111                 $x->_database = $args[0];
112                 $this->_connect();
113                 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
114        
115                 $tables = $DB->getListOf('tables');
116                 class_exists('DB_DataObject_Generator') ? '' : 
117                     require_once 'DB/DataObject/Generator.php';
118                     
119                 foreach($tables as $table) {
120                     $y = new DB_DataObject_Generator;
121                     $y->fillTableSchema($x->_database,$table);
122                 }
123                 return $_DB_DATAOBJECT['INI'][$x->_database];            
124             } else {
125         
126                 $_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
127                     $_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
128                 
129                 if (isset($args[1])) {
130                     $_DB_DATAOBJECT['LINKS'][$args[0]] = isset($_DB_DATAOBJECT['LINKS'][$args[0]]) ?
131                         $_DB_DATAOBJECT['LINKS'][$args[0]] + $args[2] : $args[2];
132                 }
133                 return true;
134             }
135           
136         }
137         
138         
139         
140         if (!$this->_database) {
141             $this->_connect();
142         }
143         
144         // loaded already?
145         if (!empty($_DB_DATAOBJECT['INI'][$this->_database])) {
146             
147             // database loaded - but this is table is not available..
148             if (
149                     empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) 
150                     && !empty($_DB_DATAOBJECT['CONFIG']['proxy'])
151                 ) {
152                 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
153                     $this->debug("Loading Generator to fetch Schema",1);
154                 }
155                 class_exists('DB_DataObject_Generator') ? '' : 
156                     require_once 'DB/DataObject/Generator.php';
157                     
158                 
159                 $x = new DB_DataObject_Generator;
160                 $x->fillTableSchema($this->_database,$this->__table);
161             }
162             return true;
163         }
164         
165         
166         if (empty($_DB_DATAOBJECT['CONFIG'])) {
167             DB_DataObject::_loadConfig();
168         }
169         
170         // if you supply this with arguments, then it will take those
171         // as the database and links array...
172          
173         $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
174             array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
175             array() ;
176                  
177         if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
178             $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
179                 $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
180                 explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
181         }
182                     
183          
184         /* BEGIN CHANGED FROM UPSTREAM */
185         $_DB_DATAOBJECT['INI'][$this->_database] = $this->parseIniFiles($schemas);
186         /* END CHANGED FROM UPSTREAM */
187
188         // now have we loaded the structure.. 
189         
190         if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
191             return true;
192         }
193         // - if not try building it..
194         if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
195             class_exists('DB_DataObject_Generator') ? '' : 
196                 require_once 'DB/DataObject/Generator.php';
197                 
198             $x = new DB_DataObject_Generator;
199             $x->fillTableSchema($this->_database,$this->__table);
200             // should this fail!!!???
201             return true;
202         }
203         $this->debug("Cant find database schema: {$this->_database}/{$this->__table} \n".
204                     "in links file data: " . print_r($_DB_DATAOBJECT['INI'],true),"databaseStructure",5);
205         // we have to die here!! - it causes chaos if we dont (including looping forever!)
206         $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);
207         return false;
208     }
209
210     /** For parseIniFiles */
211     protected static $iniCache = array();
212
213     /**
214      * When switching site configurations, DB_DataObject was loading its
215      * .ini files over and over, leaking gobs of memory.
216      * This refactored helper function uses a local cache of .ini files
217      * to minimize the leaks.
218      *
219      * @param array of .ini file names $schemas
220      * @return array
221      */
222     protected function parseIniFiles($schemas)
223     {
224         $key = implode("|", $schemas);
225         if (!isset(Safe_DataObject::$iniCache[$key])) {
226             $data = array();
227             foreach ($schemas as $ini) {
228                 if (file_exists($ini) && is_file($ini)) {
229                     $data = array_merge($data, parse_ini_file($ini, true));
230
231                     if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) { 
232                         if (!is_readable ($ini)) {
233                             $this->debug("ini file is not readable: $ini","databaseStructure",1);
234                         } else {
235                             $this->debug("Loaded ini file: $ini","databaseStructure",1);
236                         }
237                     }
238                 } else {
239                     if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
240                         $this->debug("Missing ini file: $ini","databaseStructure",1);
241                     }
242                 }
243             }
244             Safe_DataObject::$iniCache[$key] = $data;
245         }
246
247         return Safe_DataObject::$iniCache[$key];
248     }
249 }
250