Bitrix-D7  20.0.0
main/lib/config/option.php
См. документацию.
1 <?php
2 /**
3  * Bitrix Framework
4  * @package bitrix
5  * @subpackage main
6  * @copyright 2001-2015 Bitrix
7  */
8 namespace Bitrix\Main\Config;
9 
10 use Bitrix\Main;
11 
12 class Option
13 {
14  const CACHE_DIR = "b_option";
15 
16  protected static $options = array();
17 
18  /**
19  * Returns a value of an option.
20  *
21  * @param string $moduleId The module ID.
22  * @param string $name The option name.
23  * @param string $default The default value to return, if a value doesn't exist.
24  * @param bool|string $siteId The site ID, if the option differs for sites.
25  * @return string
26  * @throws Main\ArgumentNullException
27  * @throws Main\ArgumentOutOfRangeException
28  */
29  public static function get($moduleId, $name, $default = "", $siteId = false)
30  {
31  if ($moduleId == '')
32  throw new Main\ArgumentNullException("moduleId");
33  if ($name == '')
34  throw new Main\ArgumentNullException("name");
35 
36  if (!isset(self::$options[$moduleId]))
37  {
38  static::load($moduleId);
39  }
40 
41  if ($siteId === false)
42  {
43  $siteId = static::getDefaultSite();
44  }
45 
46  $siteKey = ($siteId == ""? "-" : $siteId);
47 
48  if (isset(self::$options[$moduleId][$siteKey][$name]))
49  {
50  return self::$options[$moduleId][$siteKey][$name];
51  }
52 
53  if (isset(self::$options[$moduleId]["-"][$name]))
54  {
55  return self::$options[$moduleId]["-"][$name];
56  }
57 
58  if ($default == "")
59  {
60  $moduleDefaults = static::getDefaults($moduleId);
61  if (isset($moduleDefaults[$name]))
62  {
63  return $moduleDefaults[$name];
64  }
65  }
66 
67  return $default;
68  }
69 
70  /**
71  * Returns the real value of an option as it's written in a DB.
72  *
73  * @param string $moduleId The module ID.
74  * @param string $name The option name.
75  * @param bool|string $siteId The site ID.
76  * @return null|string
77  * @throws Main\ArgumentNullException
78  */
79  public static function getRealValue($moduleId, $name, $siteId = false)
80  {
81  if ($moduleId == '')
82  throw new Main\ArgumentNullException("moduleId");
83  if ($name == '')
84  throw new Main\ArgumentNullException("name");
85 
86  if (!isset(self::$options[$moduleId]))
87  {
88  static::load($moduleId);
89  }
90 
91  if ($siteId === false)
92  {
93  $siteId = static::getDefaultSite();
94  }
95 
96  $siteKey = ($siteId == ""? "-" : $siteId);
97 
98  if (isset(self::$options[$moduleId][$siteKey][$name]))
99  {
100  return self::$options[$moduleId][$siteKey][$name];
101  }
102 
103  return null;
104  }
105 
106  /**
107  * Returns an array with default values of a module options (from a default_option.php file).
108  *
109  * @param string $moduleId The module ID.
110  * @return array
111  * @throws Main\ArgumentOutOfRangeException
112  */
113  public static function getDefaults($moduleId)
114  {
115  static $defaultsCache = array();
116  if (isset($defaultsCache[$moduleId]))
117  return $defaultsCache[$moduleId];
118 
119  if (preg_match("#[^a-zA-Z0-9._]#", $moduleId))
120  throw new Main\ArgumentOutOfRangeException("moduleId");
121 
122  $path = Main\Loader::getLocal("modules/".$moduleId."/default_option.php");
123  if ($path === false)
124  return $defaultsCache[$moduleId] = array();
125 
126  include($path);
127 
128  $varName = str_replace(".", "_", $moduleId)."_default_option";
129  if (isset(${$varName}) && is_array(${$varName}))
130  return $defaultsCache[$moduleId] = ${$varName};
131 
132  return $defaultsCache[$moduleId] = array();
133  }
134  /**
135  * Returns an array of set options array(name => value).
136  *
137  * @param string $moduleId The module ID.
138  * @param bool|string $siteId The site ID, if the option differs for sites.
139  * @return array
140  * @throws Main\ArgumentNullException
141  */
142  public static function getForModule($moduleId, $siteId = false)
143  {
144  if ($moduleId == '')
145  throw new Main\ArgumentNullException("moduleId");
146 
147  if (!isset(self::$options[$moduleId]))
148  {
149  static::load($moduleId);
150  }
151 
152  if ($siteId === false)
153  {
154  $siteId = static::getDefaultSite();
155  }
156 
157  $result = self::$options[$moduleId]["-"];
158 
159  if($siteId <> "" && !empty(self::$options[$moduleId][$siteId]))
160  {
161  //options for the site override general ones
162  $result = array_replace($result, self::$options[$moduleId][$siteId]);
163  }
164 
165  return $result;
166  }
167 
168  protected static function load($moduleId)
169  {
170  $cache = Main\Application::getInstance()->getManagedCache();
171  $cacheTtl = static::getCacheTtl();
172  $loadFromDb = true;
173 
174  if ($cacheTtl !== false)
175  {
176  if($cache->read($cacheTtl, "b_option:{$moduleId}", self::CACHE_DIR))
177  {
178  self::$options[$moduleId] = $cache->get("b_option:{$moduleId}");
179  $loadFromDb = false;
180  }
181  }
182 
183  if($loadFromDb)
184  {
186  $sqlHelper = $con->getSqlHelper();
187 
188  self::$options[$moduleId] = ["-" => []];
189 
190  $query = "
191  SELECT NAME, VALUE
192  FROM b_option
193  WHERE MODULE_ID = '{$sqlHelper->forSql($moduleId)}'
194  ";
195 
196  $res = $con->query($query);
197  while ($ar = $res->fetch())
198  {
199  self::$options[$moduleId]["-"][$ar["NAME"]] = $ar["VALUE"];
200  }
201 
202  try
203  {
204  //b_option_site possibly doesn't exist
205 
206  $query = "
207  SELECT SITE_ID, NAME, VALUE
208  FROM b_option_site
209  WHERE MODULE_ID = '{$sqlHelper->forSql($moduleId)}'
210  ";
211 
212  $res = $con->query($query);
213  while ($ar = $res->fetch())
214  {
215  self::$options[$moduleId][$ar["SITE_ID"]][$ar["NAME"]] = $ar["VALUE"];
216  }
217  }
218  catch(Main\DB\SqlQueryException $e){}
219 
220  if($cacheTtl !== false)
221  {
222  $cache->set("b_option:{$moduleId}", self::$options[$moduleId]);
223  }
224  }
225 
226  /*patchvalidationoptions4*/
227  }
228 
229  /**
230  * Sets an option value and saves it into a DB. After saving the OnAfterSetOption event is triggered.
231  *
232  * @param string $moduleId The module ID.
233  * @param string $name The option name.
234  * @param string $value The option value.
235  * @param string $siteId The site ID, if the option depends on a site.
236  * @throws Main\ArgumentOutOfRangeException
237  */
238  public static function set($moduleId, $name, $value = "", $siteId = "")
239  {
240  if ($moduleId == '')
241  throw new Main\ArgumentNullException("moduleId");
242  if ($name == '')
243  throw new Main\ArgumentNullException("name");
244 
245  if ($siteId === false)
246  {
247  $siteId = static::getDefaultSite();
248  }
249 
251  $sqlHelper = $con->getSqlHelper();
252 
253  $updateFields = [
254  "VALUE" => $value,
255  ];
256 
257  if($siteId == "")
258  {
259  $insertFields = [
260  "MODULE_ID" => $moduleId,
261  "NAME" => $name,
262  "VALUE" => $value,
263  ];
264 
265  $keyFields = ["MODULE_ID", "NAME"];
266 
267  $sql = $sqlHelper->prepareMerge("b_option", $keyFields, $insertFields, $updateFields);
268  }
269  else
270  {
271  $insertFields = [
272  "MODULE_ID" => $moduleId,
273  "NAME" => $name,
274  "SITE_ID" => $siteId,
275  "VALUE" => $value,
276  ];
277 
278  $keyFields = ["MODULE_ID", "NAME", "SITE_ID"];
279 
280  $sql = $sqlHelper->prepareMerge("b_option_site", $keyFields, $insertFields, $updateFields);
281  }
282 
283  $con->queryExecute(current($sql));
284 
285  static::clearCache($moduleId);
286 
287  static::loadTriggers($moduleId);
288 
289  $event = new Main\Event(
290  "main",
291  "OnAfterSetOption_".$name,
292  array("value" => $value)
293  );
294  $event->send();
295 
296  $event = new Main\Event(
297  "main",
298  "OnAfterSetOption",
299  array(
300  "moduleId" => $moduleId,
301  "name" => $name,
302  "value" => $value,
303  "siteId" => $siteId,
304  )
305  );
306  $event->send();
307  }
308 
309  protected static function loadTriggers($moduleId)
310  {
311  static $triggersCache = array();
312  if (isset($triggersCache[$moduleId]))
313  return;
314 
315  if (preg_match("#[^a-zA-Z0-9._]#", $moduleId))
316  throw new Main\ArgumentOutOfRangeException("moduleId");
317 
318  $triggersCache[$moduleId] = true;
319 
320  $path = Main\Loader::getLocal("modules/".$moduleId."/option_triggers.php");
321  if ($path === false)
322  return;
323 
324  include($path);
325  }
326 
327  protected static function getCacheTtl()
328  {
329  static $cacheTtl = null;
330 
331  if($cacheTtl === null)
332  {
333  $cacheFlags = Configuration::getValue("cache_flags");
334  if (isset($cacheFlags["config_options"]))
335  {
336  $cacheTtl = $cacheFlags["config_options"];
337  }
338  else
339  {
340  $cacheTtl = 0;
341  }
342  }
343  return $cacheTtl;
344  }
345 
346  /**
347  * Deletes options from a DB.
348  *
349  * @param string $moduleId The module ID.
350  * @param array $filter The array with filter keys:
351  * name - the name of the option;
352  * site_id - the site ID (can be empty).
353  * @throws Main\ArgumentNullException
354  */
355  public static function delete($moduleId, array $filter = array())
356  {
357  if ($moduleId == '')
358  throw new Main\ArgumentNullException("moduleId");
359 
361  $sqlHelper = $con->getSqlHelper();
362 
363  $deleteForSites = true;
364  $sqlWhere = $sqlWhereSite = "";
365 
366  if (isset($filter["name"]))
367  {
368  if ($filter["name"] == '')
369  {
370  throw new Main\ArgumentNullException("filter[name]");
371  }
372  $sqlWhere .= " AND NAME = '{$sqlHelper->forSql($filter["name"])}'";
373  }
374  if (isset($filter["site_id"]))
375  {
376  if($filter["site_id"] <> "")
377  {
378  $sqlWhereSite = " AND SITE_ID = '{$sqlHelper->forSql($filter["site_id"], 2)}'";
379  }
380  else
381  {
382  $deleteForSites = false;
383  }
384  }
385  if($moduleId == 'main')
386  {
387  $sqlWhere .= "
388  AND NAME NOT LIKE '~%'
389  AND NAME NOT IN ('crc_code', 'admin_passwordh', 'server_uniq_id','PARAM_MAX_SITES', 'PARAM_MAX_USERS')
390  ";
391  }
392  else
393  {
394  $sqlWhere .= " AND NAME <> '~bsm_stop_date'";
395  }
396 
397  if($sqlWhereSite == '')
398  {
399  $con->queryExecute("
400  DELETE FROM b_option
401  WHERE MODULE_ID = '{$sqlHelper->forSql($moduleId)}'
402  {$sqlWhere}
403  ");
404  }
405 
406  if($deleteForSites)
407  {
408  $con->queryExecute("
409  DELETE FROM b_option_site
410  WHERE MODULE_ID = '{$sqlHelper->forSql($moduleId)}'
411  {$sqlWhere}
412  {$sqlWhereSite}
413  ");
414  }
415 
416  static::clearCache($moduleId);
417  }
418 
419  protected static function clearCache($moduleId)
420  {
421  unset(self::$options[$moduleId]);
422 
423  if (static::getCacheTtl() !== false)
424  {
425  $cache = Main\Application::getInstance()->getManagedCache();
426  $cache->clean("b_option:{$moduleId}", self::CACHE_DIR);
427  }
428  }
429 
430  protected static function getDefaultSite()
431  {
432  static $defaultSite;
433 
434  if ($defaultSite === null)
435  {
436  $context = Main\Application::getInstance()->getContext();
437  if ($context != null)
438  {
439  $defaultSite = $context->getSite();
440  }
441  }
442  return $defaultSite;
443  }
444 }
Bitrix\Main\Config
Definition: main/lib/config/configuration.php:2
Bitrix\Main\Config\Option\load
static load($moduleId)
Definition: main/lib/config/option.php:168
Bitrix\Main
Bitrix\Main\Config\Option\getRealValue
static getRealValue($moduleId, $name, $siteId=false)
Returns the real value of an option as it's written in a DB.
Definition: main/lib/config/option.php:79
Bitrix\Main\Config\Option\$options
static $options
Definition: main/lib/config/option.php:16
Bitrix\Main\Config\Option\clearCache
static clearCache($moduleId)
Definition: main/lib/config/option.php:419
Bitrix\Main\Event
Definition: main/lib/event.php:4
Bitrix\Main\Application\getConnection
static getConnection($name="")
Static method returns database connection for the specified name.
Definition: main/lib/application.php:381
Bitrix\Main\ArgumentOutOfRangeException
Exception is thrown when the value of an argument is outside the allowable range of values.
Definition: main/lib/exception.php:66
Bitrix\Main\Config\Option\getCacheTtl
static getCacheTtl()
Definition: main/lib/config/option.php:327
Bitrix\Main\Config\Option
Definition: main/lib/config/option.php:12
Bitrix\Main\Config\Option\getDefaultSite
static getDefaultSite()
Definition: main/lib/config/option.php:430
Bitrix\Main\Application\getInstance
static getInstance()
Returns current instance of the Application.
Definition: main/lib/application.php:86
Bitrix\Main\Config\Option\CACHE_DIR
const CACHE_DIR
Definition: main/lib/config/option.php:14
Bitrix\Main\ArgumentNullException
Exception is thrown when "empty" value is passed to a function that does not accept it as a valid arg...
Definition: main/lib/exception.php:53
Bitrix\Main\Config\Option\getForModule
static getForModule($moduleId, $siteId=false)
Returns an array of set options array(name => value).
Definition: main/lib/config/option.php:142
Bitrix\Main\Config\Option\loadTriggers
static loadTriggers($moduleId)
Definition: main/lib/config/option.php:309
Bitrix\Main\Loader\getLocal
static getLocal($path, $root=null)
Checks if file exists in /local or /bitrix directories.
Definition: main/lib/loader.php:439
Bitrix\Main\Config\Option\getDefaults
static getDefaults($moduleId)
Returns an array with default values of a module options (from a default_option.php file).
Definition: main/lib/config/option.php:113