PageRenderTime 41ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/ezutils/classes/ezphpcreator.php

http://github.com/ezsystems/ezpublish
PHP | 1347 lines | 850 code | 79 blank | 418 comment | 123 complexity | fd946e253554f6dae171699ba1443a6d MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * File containing the eZPHPCreator class.
  4. *
  5. * @copyright Copyright (C) eZ Systems AS. All rights reserved.
  6. * @license For full copyright and license information view LICENSE file distributed with this source code.
  7. * @version //autogentag//
  8. * @package lib
  9. */
  10. /*!
  11. \class eZPHPCreator ezphpcreator.php
  12. \ingroup eZUtils
  13. \brief eZPHPCreator provides a simple interface for creating and executing PHP code.
  14. To create PHP code you must create an instance of this class,
  15. add any number of elements you choose with
  16. addDefine(), addVariable(), addVariableUnset(), addVariableUnsetList(),
  17. addSpace(), addText(), addMethodCall(), addCodePiece(), addComment() and
  18. addInclude().
  19. After that you call store() to write all changes to disk.
  20. \code
  21. $php = new eZPHPCreator( 'cache', 'code.php' );
  22. $php->addComment( 'Auto generated' );
  23. $php->addInclude( 'inc.php' );
  24. $php->addVariable( 'count', 10 );
  25. $php->store();
  26. \endcode
  27. To restore PHP code you must create an instance of this class,
  28. check if you can restore it with canRestore() then restore variables with restore().
  29. The class will include PHP file and run all code, once the file is done it will
  30. catch any variables you require and return it to you.
  31. \code
  32. $php = new eZPHPCreator( 'cache', 'code.php' );
  33. if ( $php->canRestore() )
  34. {
  35. $variables = $php->restore( array( 'max_count' => 'count' ) );
  36. print( "Max count was " . $variables['max_count'] );
  37. }
  38. $php->close();
  39. \endcode
  40. */
  41. class eZPHPCreator
  42. {
  43. const VARIABLE = 1;
  44. const SPACE = 2;
  45. const TEXT = 3;
  46. const METHOD_CALL = 4;
  47. const CODE_PIECE = 5;
  48. const EOL_COMMENT = 6;
  49. const INCLUDE_STATEMENT = 7;
  50. const VARIABLE_UNSET = 8;
  51. const DEFINE = 9;
  52. const VARIABLE_UNSET_LIST = 10;
  53. const RAW_VARIABLE = 11;
  54. const VARIABLE_ASSIGNMENT = 1;
  55. const VARIABLE_APPEND_TEXT = 2;
  56. const VARIABLE_APPEND_ELEMENT = 3;
  57. const INCLUDE_ONCE_STATEMENT = 1;
  58. const INCLUDE_ALWAYS_STATEMENT = 2;
  59. const METHOD_CALL_PARAMETER_VALUE = 1;
  60. const METHOD_CALL_PARAMETER_VARIABLE = 2;
  61. /**
  62. * Initializes the creator with the directory path $dir and filename $file.
  63. *
  64. * @param string $dir
  65. * @param string $file
  66. * @param string $prefix
  67. * @param array $options
  68. */
  69. public function __construct( $dir, $file, $prefix = '', $options = array() )
  70. {
  71. $this->PHPDir = $dir;
  72. $this->PHPFile = $file;
  73. $this->FilePrefix = $prefix;
  74. $this->FileResource = false;
  75. $this->Elements = array();
  76. $this->TextChunks = array();
  77. $this->TemporaryCounter = 0;
  78. if ( isset( $options['spacing'] ) and ( $options['spacing'] == 'disabled') )
  79. {
  80. $this->Spacing = false;
  81. }
  82. else
  83. {
  84. $this->Spacing = true;
  85. }
  86. if ( isset( $options['clustering'] ) )
  87. {
  88. $this->ClusteringEnabled = true;
  89. $this->ClusterFileScope = $options['clustering'];
  90. }
  91. else
  92. {
  93. $this->ClusteringEnabled = false;
  94. }
  95. $this->ClusterHandler = null;
  96. }
  97. //@{
  98. /*!
  99. Adds a new define statement to the code with the name \a $name and value \a $value.
  100. The parameter \a $caseSensitive determines if the define should be made case sensitive or not.
  101. Example:
  102. \code
  103. $php->addDefine( 'MY_CONSTANT', 5 );
  104. \endcode
  105. Would result in the PHP code.
  106. \code
  107. define( 'MY_CONSTANT', 5 );
  108. \endcode
  109. \param $parameters Optional parameters, can be any of the following:
  110. - \a spacing, The number of spaces to place before each code line, default is \c 0.
  111. \note \a $name must start with a letter or underscore, followed by any number of letters, numbers, or underscores.
  112. See http://php.net/manual/en/language.constants.php for more information.
  113. \sa http://php.net/manual/en/function.define.php
  114. */
  115. function addDefine( $name, $value, $caseSensitive = true, $parameters = array() )
  116. {
  117. $element = array( eZPHPCreator::DEFINE,
  118. $name,
  119. $value,
  120. $caseSensitive,
  121. $parameters );
  122. $this->Elements[] = $element;
  123. }
  124. /*!
  125. Adds a new raw variable tothe code with the name \a $name and value \a $value.
  126. Example:
  127. \code
  128. $php->addVariable( 'TransLationRoot', $cache['root'] );
  129. \endcode
  130. This function makes use of PHP's var_export() function which is optimized
  131. for this task.
  132. */
  133. function addRawVariable( $name, $value )
  134. {
  135. $element = array( eZPHPCreator::RAW_VARIABLE, $name, $value );
  136. $this->Elements[] = $element;
  137. }
  138. /*!
  139. Adds a new variable to the code with the name \a $name and value \a $value.
  140. Example:
  141. \code
  142. $php->addVariable( 'offset', 5 );
  143. $php->addVariable( 'text', 'some more text', eZPHPCreator::VARIABLE_APPEND_TEXT );
  144. $php->addVariable( 'array', 42, eZPHPCreator::VARIABLE_APPEND_ELEMENT );
  145. \endcode
  146. Would result in the PHP code.
  147. \code
  148. $offset = 5;
  149. $text .= 'some more text';
  150. $array[] = 42;
  151. \endcode
  152. \param $assignmentType Controls the way the value is assigned, choose one of the following:
  153. - \b eZPHPCreator::VARIABLE_ASSIGNMENT, assign using \c = (default)
  154. - \b eZPHPCreator::VARIABLE_APPEND_TEXT, append using text concat operator \c .
  155. - \b eZPHPCreator::VARIABLE_APPEND_ELEMENT, append element to array using append operator \c []
  156. \param $parameters Optional parameters, can be any of the following:
  157. - \a spacing, The number of spaces to place before each code line, default is \c 0.
  158. - \a full-tree, Whether to displays array values as one large expression (\c true) or
  159. split it up into multiple variables (\c false)
  160. */
  161. function addVariable( $name, $value, $assignmentType = eZPHPCreator::VARIABLE_ASSIGNMENT,
  162. $parameters = array() )
  163. {
  164. $element = array( eZPHPCreator::VARIABLE,
  165. $name,
  166. $value,
  167. $assignmentType,
  168. $parameters );
  169. $this->Elements[] = $element;
  170. }
  171. /*!
  172. Adds code to unset a variable with the name \a $name.
  173. Example:
  174. \code
  175. $php->addVariableUnset( 'offset' );
  176. \endcode
  177. Would result in the PHP code.
  178. \code
  179. unset( $offset );
  180. \endcode
  181. \param $parameters Optional parameters, can be any of the following:
  182. - \a spacing, The number of spaces to place before each code line, default is \c 0.
  183. \sa http://php.net/manual/en/function.unset.php
  184. */
  185. function addVariableUnset( $name,
  186. $parameters = array() )
  187. {
  188. $element = array( eZPHPCreator::VARIABLE_UNSET,
  189. $name,
  190. $parameters );
  191. $this->Elements[] = $element;
  192. }
  193. /*!
  194. Adds code to unset a list of variables with name from \a $list.
  195. Example:
  196. \code
  197. $php->addVariableUnsetList( array ( 'var1', 'var2' ) );
  198. \endcode
  199. Would result in the PHP code.
  200. \code
  201. unset( $var1, $var2 );
  202. \endcode
  203. \param $parameters Optional parameters, can be any of the following:
  204. - \a spacing, The number of spaces to place before each code line, default is \c 0.
  205. \sa http://php.net/manual/en/function.unset.php
  206. */
  207. function addVariableUnsetList( $list,
  208. $parameters = array() )
  209. {
  210. $element = array( eZPHPCreator::VARIABLE_UNSET_LIST,
  211. $list,
  212. $parameters );
  213. $this->Elements[] = $element;
  214. }
  215. /*!
  216. Adds some space to the code in form of newlines. The number of lines
  217. is controlled with \a $lines which is \c 1 by default.
  218. You can use this to get more readable PHP code.
  219. Example:
  220. \code
  221. $php->addSpace( 1 );
  222. \endcode
  223. */
  224. function addSpace( $lines = 1 )
  225. {
  226. $element = array( eZPHPCreator::SPACE,
  227. $lines );
  228. $this->Elements[] = $element;
  229. }
  230. /*!
  231. Adds some plain text to the code. The text will be placed
  232. outside of PHP start and end markers and will in principle
  233. work as printing the text.
  234. Example:
  235. \code
  236. $php->addText( 'Print me!' );
  237. \endcode
  238. */
  239. function addText( $text )
  240. {
  241. $element = array( eZPHPCreator::TEXT,
  242. $text );
  243. $this->Elements[] = $element;
  244. }
  245. /*!
  246. Adds code to call the method \a $methodName on the object named \a $objectName,
  247. \a $methodParameters should be an array with parameter entries where each entry contains:
  248. - \a 0, The parameter value
  249. - \a 1 (\em optional), The type of parameter, is one of:
  250. - \b eZPHPCreator::METHOD_CALL_PARAMETER_VALUE, Use value directly (default if this entry is missing)
  251. - \b eZPHPCreator::METHOD_CALL_PARAMETER_VARIABLE, Use value as the name of the variable.
  252. Optionally the \a $returnValue parameter can be used to decide what should be done
  253. with the return value of the method call. It can either be \c false which means
  254. to do nothing or an array with the following entries.
  255. - \a 0, The name of the variable to assign the value to
  256. - \a 1 (\em optional), The type of assignment, uses the same value as addVariable().
  257. \param $parameters Optional parameters, can be any of the following:
  258. - \a spacing, The number of spaces to place before each code line, default is \c 0.
  259. Example:
  260. \code
  261. $php->addMethodCall( 'node', 'name', array(), array( 'name' ) );
  262. $php->addMethodCall( 'php', 'addMethodCall',
  263. array( array( 'node' ), array( 'name' ) ) );
  264. \endcode
  265. Would result in the PHP code.
  266. \code
  267. $name = $node->name();
  268. $php->addMethodCall( 'node', 'name' );
  269. \endcode
  270. */
  271. function addMethodCall( $objectName, $methodName, $methodParameters, $returnValue = false, $parameters = array() )
  272. {
  273. $element = array( eZPHPCreator::METHOD_CALL,
  274. $objectName,
  275. $methodName,
  276. $methodParameters,
  277. $returnValue,
  278. $parameters );
  279. $this->Elements[] = $element;
  280. }
  281. /*!
  282. Adds custom PHP code to the file, you should only use this a last resort if any
  283. of the other \em add functions done give you the required result.
  284. \param $code Contains the code as text, the text will not be modified (except for spacing).
  285. This means that each expression must be ended with a newline even if it's just one.
  286. \param $parameters Optional parameters, can be any of the following:
  287. - \a spacing, The number of spaces to place before each code line, default is \c 0.
  288. Example:
  289. \code
  290. $php->addCodePiece( "if ( \$value > 2 )\n{\n \$value = 2;\n}\n" );
  291. \endcode
  292. Would result in the PHP code.
  293. \code
  294. if ( $value > 2 )
  295. {
  296. $value = 2;
  297. }
  298. \endcode
  299. */
  300. function addCodePiece( $code, $parameters = array() )
  301. {
  302. $element = array( eZPHPCreator::CODE_PIECE,
  303. $code,
  304. $parameters );
  305. $this->Elements[] = $element;
  306. }
  307. /*!
  308. Adds a comment to the code, the comment will be display using multiple end-of-line
  309. comments (//), one for each newline in the text \a $comment.
  310. \param $eol Whether to add a newline at the last comment line
  311. \param $whitespaceHandling Whether to remove trailing whitespace from each line
  312. \param $parameters Optional parameters, can be any of the following:
  313. - \a spacing, The number of spaces to place before each code line, default is \c 0.
  314. Example:
  315. \code
  316. $php->addComment( "This file is auto generated\nDo not edit!" );
  317. \endcode
  318. Would result in the PHP code.
  319. \code
  320. // This file is auto generated
  321. // Do not edit!
  322. \endcode
  323. */
  324. function addComment( $comment, $eol = true, $whitespaceHandling = true, $parameters = array() )
  325. {
  326. $element = array( eZPHPCreator::EOL_COMMENT,
  327. $comment,
  328. array_merge( $parameters,
  329. array( 'eol' => $eol,
  330. 'whitespace-handling' => $whitespaceHandling ) ) );
  331. $this->Elements[] = $element;
  332. }
  333. /*!
  334. Adds an include statement to the code, the file to include is \a $file.
  335. \param $type What type of include statement to use, can be one of the following:
  336. - \b eZPHPCreator::INCLUDE_ONCE_STATEMENT, use \em include_once()
  337. - \b eZPHPCreator::INCLUDE_ALWAYS_STATEMENT, use \em include()
  338. \param $parameters Optional parameters, can be any of the following:
  339. - \a spacing, The number of spaces to place before each code line, default is \c 0.
  340. Example:
  341. \code
  342. $php->addInclude( 'lib/ezutils/classes/ezphpcreator.php' );
  343. \endcode
  344. Would result in the PHP code.
  345. \code
  346. //include_once( 'lib/ezutils/classes/ezphpcreator.php' );
  347. \endcode
  348. */
  349. function addInclude( $file, $type = eZPHPCreator::INCLUDE_ONCE_STATEMENT, $parameters = array() )
  350. {
  351. $element = array( eZPHPCreator::INCLUDE_STATEMENT,
  352. $file,
  353. $type,
  354. $parameters );
  355. $this->Elements[] = $element;
  356. }
  357. //@}
  358. /*!
  359. \static
  360. Creates a variable statement with an assignment type and returns it.
  361. \param $variableName The name of the variable
  362. \param $assignmentType What kind of assignment to use, is one of the following;
  363. - \b eZPHPCreator::VARIABLE_ASSIGNMENT, assign using \c =
  364. - \b eZPHPCreator::VARIABLE_APPEND_TEXT, append to text using \c .
  365. - \b eZPHPCreator::VARIABLE_APPEND_ELEMENT, append to array using \c []
  366. \param $variableParameters Optional parameters for the statement
  367. */
  368. static function variableNameText( $variableName, $assignmentType, $variableParameters = array() )
  369. {
  370. $text = '$' . $variableName;
  371. if ( $assignmentType == eZPHPCreator::VARIABLE_ASSIGNMENT )
  372. {
  373. $text .= ' = ';
  374. }
  375. else if ( $assignmentType == eZPHPCreator::VARIABLE_APPEND_TEXT )
  376. {
  377. $text .= ' .= ';
  378. }
  379. else if ( $assignmentType == eZPHPCreator::VARIABLE_APPEND_ELEMENT )
  380. {
  381. $text .= '[] = ';
  382. }
  383. return $text;
  384. }
  385. /*!
  386. Creates a text representation of the value \a $value which can
  387. be placed in files and be read back by a PHP parser as it was.
  388. The type of the values determines the output, it can be one of the following.
  389. - boolean, becomes \c true or \c false
  390. - null, becomes \c null
  391. - string, adds \ (backslash) to backslashes, double quotes, dollar signs and newlines.
  392. Then wraps the whole string in " (double quotes).
  393. - numeric, displays the value as-is.
  394. - array, expands all value recursively using this function
  395. - object, creates a representation of an object creation if the object has \c serializeData implemented.
  396. \param $column Determines the starting column in which the text will be placed.
  397. This is used for expanding arrays and objects which can span multiple lines.
  398. \param $iteration The current iteration, starts at 0 and increases with 1 for each recursive call
  399. \param $maxIterations The maximum number of iterations to allow, if the iteration
  400. exceeds this the array or object will be split into multiple variables.
  401. Can be set to \c false to the array or object as-is.
  402. \note This function can be called statically if \a $maxIterations is set to \c false
  403. */
  404. function thisVariableText( $value, $column = 0, $iteration = 0, $maxIterations = 2 )
  405. {
  406. if ( isset( $this->Spacing ) and !$this->Spacing )
  407. {
  408. return var_export( $value, true );
  409. }
  410. if ( $value === true )
  411. $text = 'true';
  412. else if ( $value === false )
  413. $text = 'false';
  414. else if ( $value === null )
  415. $text = 'null';
  416. else if ( is_string( $value ) )
  417. {
  418. $valueText = str_replace( array( "\\",
  419. "\"",
  420. "\$",
  421. "\n" ),
  422. array( "\\\\",
  423. "\\\"",
  424. "\\$",
  425. "\\n" ),
  426. $value );
  427. $text = "\"$valueText\"";
  428. }
  429. else if ( is_numeric( $value ) )
  430. $text = $value;
  431. else if ( is_object( $value ) )
  432. {
  433. if ( $maxIterations !== false and
  434. $iteration > $maxIterations )
  435. {
  436. $temporaryVariableName = $this->temporaryVariableName( 'obj' );
  437. $this->writeVariable( $temporaryVariableName, $value );
  438. $text = '$' . $temporaryVariableName;
  439. }
  440. else
  441. {
  442. $text = '';
  443. if ( method_exists( $value, 'serializeData' ) )
  444. {
  445. $serializeData = $value->serializeData();
  446. $className = $serializeData['class_name'];
  447. $text = "new $className(";
  448. $column += strlen( $text );
  449. $parameters = $serializeData['parameters'];
  450. $variables = $serializeData['variables'];
  451. $i = 0;
  452. foreach ( $parameters as $parameter )
  453. {
  454. if ( $i > 0 )
  455. {
  456. $text .= ",\n" . str_repeat( ' ', $column );
  457. }
  458. $variableName = $variables[$parameter];
  459. $variableValue = $value->$variableName;
  460. $keyText = " ";
  461. $text .= $keyText . $this->thisVariableText( $variableValue, $column + strlen( $keyText ), $iteration + 1, $maxIterations );
  462. ++$i;
  463. }
  464. if ( $i > 0 )
  465. $text .= ' ';
  466. $text .= ')';
  467. }
  468. }
  469. }
  470. else if ( is_array( $value ) )
  471. {
  472. if ( $maxIterations !== false and
  473. $iteration > $maxIterations )
  474. {
  475. $temporaryVariableName = $this->temporaryVariableName( 'arr' );
  476. $this->writeVariable( $temporaryVariableName, $value );
  477. $text = '$' . $temporaryVariableName;
  478. }
  479. else
  480. {
  481. $text = 'array(';
  482. $column += strlen( $text );
  483. $valueKeys = array_keys( $value );
  484. $isIndexed = true;
  485. for ( $i = 0, $count = count( $valueKeys ); $i < $count; ++$i )
  486. {
  487. if ( $i !== $valueKeys[$i] )
  488. {
  489. $isIndexed = false;
  490. break;
  491. }
  492. }
  493. $i = 0;
  494. foreach ( $valueKeys as $key )
  495. {
  496. if ( $i > 0 )
  497. {
  498. $text .= ",\n" . str_repeat( ' ', $column );
  499. }
  500. $element = $value[$key];
  501. $keyText = ' ';
  502. if ( !$isIndexed )
  503. {
  504. if ( is_int( $key ) )
  505. $keyText = $key;
  506. else
  507. $keyText = "\"" . str_replace( array( "\\",
  508. "\"",
  509. "\n" ),
  510. array( "\\\\",
  511. "\\\"",
  512. "\\n" ),
  513. $key ) . "\"";
  514. $keyText = " $keyText => ";
  515. }
  516. $text .= $keyText . $this->thisVariableText( $element, $column + strlen( $keyText ), $iteration + 1, $maxIterations );
  517. ++$i;
  518. }
  519. if ( $i > 0 )
  520. $text .= ' ';
  521. $text .= ')';
  522. }
  523. }
  524. else
  525. $text = 'null';
  526. return $text;
  527. }
  528. static function variableText( $value, $column = 0, $iteration = 0, $maxIterations = false )
  529. {
  530. // the last parameter will always be ignored
  531. $maxIterations = false;
  532. if ( $value === true )
  533. $text = 'true';
  534. else if ( $value === false )
  535. $text = 'false';
  536. else if ( $value === null )
  537. $text = 'null';
  538. else if ( is_string( $value ) )
  539. {
  540. $valueText = str_replace( array( "\\",
  541. "\"",
  542. "\$",
  543. "\n" ),
  544. array( "\\\\",
  545. "\\\"",
  546. "\\$",
  547. "\\n" ),
  548. $value );
  549. $text = "\"$valueText\"";
  550. }
  551. else if ( is_numeric( $value ) )
  552. $text = $value;
  553. else if ( is_object( $value ) )
  554. {
  555. $text = '';
  556. if ( method_exists( $value, 'serializeData' ) )
  557. {
  558. $serializeData = $value->serializeData();
  559. $className = $serializeData['class_name'];
  560. $text = "new $className(";
  561. $column += strlen( $text );
  562. $parameters = $serializeData['parameters'];
  563. $variables = $serializeData['variables'];
  564. $i = 0;
  565. foreach ( $parameters as $parameter )
  566. {
  567. if ( $i > 0 )
  568. {
  569. $text .= ",\n" . str_repeat( ' ', $column );
  570. }
  571. $variableName = $variables[$parameter];
  572. $variableValue = $value->$variableName;
  573. $keyText = " ";
  574. $text .= $keyText . eZPHPCreator::variableText( $variableValue, $column + strlen( $keyText ), $iteration + 1 );
  575. ++$i;
  576. }
  577. if ( $i > 0 )
  578. $text .= ' ';
  579. $text .= ')';
  580. }
  581. }
  582. else if ( is_array( $value ) )
  583. {
  584. $text = 'array(';
  585. $column += strlen( $text );
  586. $valueKeys = array_keys( $value );
  587. $isIndexed = true;
  588. for ( $i = 0, $count = count( $valueKeys ); $i < $count; ++$i )
  589. {
  590. if ( $i !== $valueKeys[$i] )
  591. {
  592. $isIndexed = false;
  593. break;
  594. }
  595. }
  596. $i = 0;
  597. foreach ( $valueKeys as $key )
  598. {
  599. if ( $i > 0 )
  600. {
  601. $text .= ",\n" . str_repeat( ' ', $column );
  602. }
  603. $element = $value[$key];
  604. $keyText = ' ';
  605. if ( !$isIndexed )
  606. {
  607. if ( is_int( $key ) )
  608. $keyText = $key;
  609. else
  610. $keyText = "\"" . str_replace( array( "\\",
  611. "\"",
  612. "\n" ),
  613. array( "\\\\",
  614. "\\\"",
  615. "\\n" ),
  616. $key ) . "\"";
  617. $keyText = " $keyText => ";
  618. }
  619. $text .= $keyText . eZPHPCreator::variableText( $element, $column + strlen( $keyText ), $iteration + 1 );
  620. ++$i;
  621. }
  622. if ( $i > 0 )
  623. $text .= ' ';
  624. $text .= ')';
  625. }
  626. else
  627. $text = 'null';
  628. return $text;
  629. }
  630. /*!
  631. \static
  632. Splits \a $text into multiple lines using \a $splitString for splitting.
  633. For each line it will prepend the string \a $spacingString n times as specified by \a $spacing.
  634. It will try to be smart and not do anything when \a $spacing is set to \c 0.
  635. \param $skipEmptyLines If \c true it will not prepend the string for empty lines.
  636. \param $spacing Must be a positive number, \c 0 means to not prepend anything.
  637. */
  638. static function prependSpacing( $text, $spacing, $skipEmptyLines = true, $spacingString = " ", $splitString = "\n" )
  639. {
  640. if ( $spacing == 0 )
  641. return $text;
  642. $textArray = explode( $splitString, $text );
  643. $newTextArray = array();
  644. foreach ( $textArray as $text )
  645. {
  646. if ( trim( $text ) != '' )
  647. $textLine = str_repeat( $spacingString, $spacing ) . $text;
  648. else
  649. $textLine = $text;
  650. $newTextArray[] = $textLine;
  651. }
  652. return implode( $splitString, $newTextArray );
  653. }
  654. //@{
  655. /*!
  656. Opens the file for writing and sets correct file permissions.
  657. \return The current file resource or \c false if it failed to open the file.
  658. \note The file name and path is supplied to the constructor of this class.
  659. \note Multiple calls to this method will only open the file once.
  660. */
  661. function open( $atomic = false )
  662. {
  663. if ( $this->ClusteringEnabled )
  664. return true;
  665. if ( !$this->FileResource )
  666. {
  667. if ( !file_exists( $this->PHPDir ) )
  668. {
  669. eZDir::mkdir( $this->PHPDir, false, true );
  670. }
  671. $path = $this->PHPDir . '/' . $this->PHPFile;
  672. $oldumask = umask( 0 );
  673. $pathExisted = file_exists( $path );
  674. if ( $atomic )
  675. {
  676. $this->isAtomic = true;
  677. $this->requestedFilename = $path;
  678. $uniqid = md5( uniqid( "ezp". getmypid(), true ) );
  679. $path .= ".$uniqid";
  680. $this->tmpFilename = $path;
  681. }
  682. $ini = eZINI::instance();
  683. $perm = octdec( $ini->variable( 'FileSettings', 'StorageFilePermissions' ) );
  684. $this->FileResource = @fopen( $this->FilePrefix . $path, "w" );
  685. if ( !$this->FileResource )
  686. eZDebug::writeError( "Could not open file '$path' for writing, perhaps wrong permissions" );
  687. if ( $this->FileResource and
  688. !$pathExisted )
  689. chmod( $path, $perm );
  690. umask( $oldumask );
  691. }
  692. return $this->FileResource;
  693. }
  694. /*!
  695. Closes the currently open file if any.
  696. */
  697. function close()
  698. {
  699. if ( $this->ClusteringEnabled )
  700. {
  701. $this->ClusterHandler = null;
  702. return;
  703. }
  704. if ( $this->FileResource )
  705. {
  706. fclose( $this->FileResource );
  707. if ( $this->isAtomic )
  708. {
  709. eZFile::rename( $this->tmpFilename, $this->requestedFilename, false, eZFile::CLEAN_ON_FAILURE );
  710. }
  711. $this->FileResource = false;
  712. }
  713. }
  714. /*!
  715. \return \c true if the file and path already exists.
  716. \note The file name and path is supplied to the constructor of this class.
  717. */
  718. function exists()
  719. {
  720. $path = $this->PHPDir . '/' . $this->PHPFile;
  721. if ( !$this->ClusteringEnabled )
  722. return file_exists( $path );
  723. if ( !$this->ClusterHandler )
  724. {
  725. $this->ClusterHandler = eZClusterFileHandler::instance();
  726. }
  727. return $this->ClusterHandler->fileExists( $path );
  728. }
  729. /*!
  730. \return \c true if file exists and can be restored.
  731. \param $timestamp The timestamp to check the modification time of the file against,
  732. if the modification time is larger or equal to \a $timestamp
  733. the file can be restored. Otherwise the file is considered too old.
  734. \note The file name and path is supplied to the constructor of this class.
  735. */
  736. function canRestore( $timestamp = false )
  737. {
  738. $path = $this->PHPDir . '/' . $this->PHPFile;
  739. if ( $this->ClusteringEnabled )
  740. {
  741. if ( !$this->ClusterHandler )
  742. {
  743. $this->ClusterHandler = eZClusterFileHandler::instance( $path );
  744. }
  745. // isExpired() expects -1 to disable expiry check
  746. $expiry = ( $timestamp === false ) ? -1 : $timestamp;
  747. return !$this->ClusterHandler->isExpired( $expiry, time(), null );
  748. }
  749. $canRestore = file_exists( $path );
  750. if ( $timestamp !== false and
  751. $canRestore )
  752. {
  753. $cacheModifierTime = filemtime( $path );
  754. $canRestore = ( $cacheModifierTime >= $timestamp );
  755. }
  756. return $canRestore;
  757. }
  758. /*!
  759. Tries to restore the PHP file and fetch the defined variables in \a $variableDefinitions.
  760. This basically means including the file using include().
  761. \param $variableDefinitions Associative array with the return variable name being the key
  762. matched variable as value.
  763. \return An associatve array with the variables that were found according to \a $variableDefinitions.
  764. Example:
  765. \code
  766. $values = $php->restore( array( 'MyValue' => 'node' ) );
  767. print( $values['MyValue'] );
  768. \endcode
  769. \note The file name and path is supplied to the constructor of this class.
  770. */
  771. function restore( $variableDefinitions )
  772. {
  773. $returnVariables = array();
  774. $path = $this->PHPDir . '/' . $this->PHPFile;
  775. if ( !$this->ClusteringEnabled )
  776. {
  777. $returnVariables = $this->_restoreCall( $path, false, $variableDefinitions );
  778. }
  779. else
  780. {
  781. if ( !$this->ClusterHandler )
  782. {
  783. $this->ClusterHandler = eZClusterFileHandler::instance( $path );
  784. }
  785. $returnVariables = $this->ClusterHandler->processFile( array( $this, '_restoreCall' ), null, $variableDefinitions );
  786. }
  787. return $returnVariables;
  788. }
  789. /*!
  790. \private
  791. Processes the PHP file and returns the specified data.
  792. */
  793. function _restoreCall( $path, $mtime, $variableDefinitions )
  794. {
  795. $returnVariables = array();
  796. include( $path );
  797. foreach ( $variableDefinitions as $variableReturnName => $variableName )
  798. {
  799. $variableRequired = true;
  800. $variableDefault = false;
  801. if ( is_array( $variableName ) )
  802. {
  803. $variableDefinition = $variableName;
  804. $variableName = $variableDefinition['name'];
  805. $variableRequired = $variableDefinition['required'];
  806. if ( isset( $variableDefinition['default'] ) )
  807. $variableDefault = $variableDefinition['default'];
  808. }
  809. if ( isset( $$variableName ) )
  810. {
  811. $returnVariables[$variableReturnName] = $$variableName;
  812. }
  813. else if ( $variableRequired )
  814. {
  815. eZDebug::writeError( "Variable '$variableName' is not present in cache '$path'", __METHOD__ );
  816. }
  817. else
  818. {
  819. $returnVariables[$variableReturnName] = $variableDefault;
  820. }
  821. }
  822. return $returnVariables;
  823. }
  824. /*!
  825. Stores the PHP cache, returns false if the cache file could not be created.
  826. */
  827. function store( $atomic = false )
  828. {
  829. if ( $this->open( $atomic ) )
  830. {
  831. $this->write( "<?php\n" );
  832. $this->writeElements();
  833. $this->write( "?>\n" );
  834. $this->writeChunks();
  835. $this->flushChunks();
  836. $this->close();
  837. if ( !$this->ClusteringEnabled )
  838. {
  839. $perm = octdec( eZINI::instance()->variable( 'FileSettings', 'StorageFilePermissions' ) );
  840. chmod( eZDir::path( array( $this->PHPDir, $this->PHPFile ) ), $perm );
  841. }
  842. // Write log message to storage.log
  843. eZLog::writeStorageLog( $this->PHPFile, $this->PHPDir . '/' );
  844. return true;
  845. }
  846. else
  847. {
  848. eZDebug::writeError( "Failed to open file '" . $this->PHPDir . '/' . $this->PHPFile . "'", __METHOD__ );
  849. return false;
  850. }
  851. }
  852. /*!
  853. Creates a text string out of all elements and returns it.
  854. \note Calling this multiple times will resulting text processing each time.
  855. */
  856. function fetch( $addPHPMarkers = true )
  857. {
  858. if ( $addPHPMarkers )
  859. $this->write( "<?php\n" );
  860. $this->writeElements();
  861. if ( $addPHPMarkers )
  862. $this->write( "?>\n" );
  863. $text = implode( '', $this->TextChunks );
  864. $this->flushChunks();
  865. return $text;
  866. }
  867. //@}
  868. /*!
  869. \private
  870. */
  871. function writeChunks()
  872. {
  873. $count = count( $this->TextChunks );
  874. if ( $this->ClusteringEnabled )
  875. {
  876. $text = '';
  877. for ( $i = 0; $i < $count; ++$i )
  878. $text .= $this->TextChunks[$i];
  879. $filePath = $this->FilePrefix . $this->PHPDir . '/' . $this->PHPFile;
  880. if ( !$this->ClusterHandler )
  881. {
  882. $this->ClusterHandler = eZClusterFileHandler::instance();
  883. }
  884. $this->ClusterHandler->fileStoreContents( $filePath, $text, $this->ClusterFileScope, 'php' );
  885. return;
  886. }
  887. for ( $i = 0; $i < $count; ++$i )
  888. {
  889. $text = $this->TextChunks[$i];
  890. fwrite( $this->FileResource, $text );
  891. }
  892. }
  893. /*!
  894. \private
  895. */
  896. function flushChunks()
  897. {
  898. $this->TextChunks = array();
  899. }
  900. /*!
  901. \private
  902. */
  903. function write( $text )
  904. {
  905. $this->TextChunks[] = $text;
  906. }
  907. /*!
  908. \private
  909. */
  910. function writeElements()
  911. {
  912. foreach( $this->Elements as $element )
  913. {
  914. if ( $element[0] == eZPHPCreator::DEFINE )
  915. {
  916. $this->writeDefine( $element );
  917. }
  918. else if ( $element[0] == eZPHPCreator::RAW_VARIABLE )
  919. {
  920. $this->writeRawVariable( $element[1], $element[2] );
  921. }
  922. else if ( $element[0] == eZPHPCreator::VARIABLE )
  923. {
  924. $this->writeVariable( $element[1], $element[2], $element[3], $element[4] );
  925. }
  926. else if ( $element[0] == eZPHPCreator::VARIABLE_UNSET )
  927. {
  928. $this->writeVariableUnset( $element );
  929. }
  930. else if ( $element[0] == eZPHPCreator::VARIABLE_UNSET_LIST )
  931. {
  932. $this->writeVariableUnsetList( $element );
  933. }
  934. else if ( $element[0] == eZPHPCreator::SPACE )
  935. {
  936. $this->writeSpace( $element );
  937. }
  938. else if ( $element[0] == eZPHPCreator::TEXT )
  939. {
  940. $this->writeText( $element );
  941. }
  942. else if ( $element[0] == eZPHPCreator::METHOD_CALL )
  943. {
  944. $this->writeMethodCall( $element );
  945. }
  946. else if ( $element[0] == eZPHPCreator::CODE_PIECE )
  947. {
  948. $this->writeCodePiece( $element );
  949. }
  950. else if ( $element[0] == eZPHPCreator::EOL_COMMENT )
  951. {
  952. $this->writeComment( $element );
  953. }
  954. else if ( $element[0] == eZPHPCreator::INCLUDE_STATEMENT )
  955. {
  956. $this->writeInclude( $element );
  957. }
  958. }
  959. }
  960. /*!
  961. \private
  962. */
  963. function writeDefine( $element )
  964. {
  965. $name = $element[1];
  966. $value = $element[2];
  967. $caseSensitive = $element[3];
  968. $parameters = $element[4];
  969. $text = '';
  970. if ( $this->Spacing )
  971. {
  972. $spacing = 0;
  973. if ( isset( $parameters['spacing'] ) )
  974. $spacing = $parameters['spacing'];
  975. $text = str_repeat( ' ', $spacing );
  976. }
  977. $nameText = $this->thisVariableText( $name, 0 );
  978. $valueText = $this->thisVariableText( $value, 0 );
  979. $text .= "define( $nameText, $valueText";
  980. if ( !$caseSensitive )
  981. $text .= ", true";
  982. $text .= " );\n";
  983. $this->write( $text );
  984. }
  985. /*!
  986. \private
  987. */
  988. function writeInclude( $element )
  989. {
  990. $includeFile = $element[1];
  991. $includeType = $element[2];
  992. $parameters = $element[3];
  993. if ( $includeType == eZPHPCreator::INCLUDE_ONCE_STATEMENT )
  994. $includeName = 'include_once';
  995. else if ( $includeType == eZPHPCreator::INCLUDE_ALWAYS_STATEMENT )
  996. $includeName = 'include';
  997. $includeFileText = $this->thisVariableText( $includeFile, 0 );
  998. $text = "$includeName( $includeFileText );\n";
  999. if ( $this->Spacing )
  1000. {
  1001. $spacing = 0;
  1002. if ( isset( $parameters['spacing'] ) )
  1003. $spacing = $parameters['spacing'];
  1004. $text = str_repeat( ' ', $spacing ) . $text;
  1005. }
  1006. $this->write( $text );
  1007. }
  1008. /*!
  1009. \private
  1010. */
  1011. function writeComment( $element )
  1012. {
  1013. $elementAttributes = $element[2];
  1014. $spacing = 0;
  1015. if ( isset( $elementAttributes['spacing'] ) and $this->Spacing )
  1016. $spacing = $elementAttributes['spacing'];
  1017. $whitespaceHandling = $elementAttributes['whitespace-handling'];
  1018. $eol = $elementAttributes['eol'];
  1019. $newCommentArray = array();
  1020. $commentArray = preg_split( "/\r\n|\r|\n/", $element[1] );
  1021. foreach ( $commentArray as $comment )
  1022. {
  1023. $textLine = '// ' . $comment;
  1024. if ( $whitespaceHandling )
  1025. {
  1026. $textLine = rtrim( $textLine );
  1027. $textLine = str_replace( "\t", ' ', $textLine );
  1028. }
  1029. $textLine = str_repeat( ' ', $spacing ) . $textLine;
  1030. $newCommentArray[] = $textLine;
  1031. }
  1032. $text = implode( "\n", $newCommentArray );
  1033. if ( $eol )
  1034. $text .= "\n";
  1035. $this->write( $text );
  1036. }
  1037. /*!
  1038. \private
  1039. */
  1040. function writeSpace( $element )
  1041. {
  1042. $text = str_repeat( "\n", $element[1] );
  1043. $this->write( $text );
  1044. }
  1045. /*!
  1046. \private
  1047. */
  1048. function writeCodePiece( $element )
  1049. {
  1050. $code = $element[1];
  1051. $parameters = $element[2];
  1052. $spacing = 0;
  1053. if ( isset( $parameters['spacing'] ) and $this->Spacing )
  1054. $spacing = $parameters['spacing'];
  1055. $text = eZPHPCreator::prependSpacing( $code, $spacing );
  1056. $this->write( $text );
  1057. }
  1058. /*!
  1059. \private
  1060. */
  1061. function writeText( $element )
  1062. {
  1063. $text = $element[1];
  1064. $this->write( "\n?>" );
  1065. $this->write( $text );
  1066. $this->write( "<?php\n" );
  1067. }
  1068. /*!
  1069. \private
  1070. */
  1071. function writeMethodCall( $element )
  1072. {
  1073. $objectName = $element[1];
  1074. $methodName = $element[2];
  1075. $methodParameters = $element[3];
  1076. $returnValue = $element[4];
  1077. $parameters = $element[5];
  1078. $text = '';
  1079. $spacing = 0;
  1080. if ( isset( $parameters['spacing'] ) and $this->Spacing )
  1081. $spacing = $parameters['spacing'];
  1082. if ( is_array( $returnValue ) )
  1083. {
  1084. $variableName = $returnValue[0];
  1085. $assignmentType = eZPHPCreator::VARIABLE_ASSIGNMENT;
  1086. if ( isset( $variableValue[1] ) )
  1087. $assignmentType = $variableValue[1];
  1088. $text = $this->variableNameText( $variableName, $assignmentType );
  1089. }
  1090. $text .= '$' . $objectName . '->' . $methodName . '(';
  1091. $column = strlen( $text );
  1092. $i = 0;
  1093. foreach ( $methodParameters as $parameterData )
  1094. {
  1095. if ( $i > 0 )
  1096. $text .= ",\n" . str_repeat( ' ', $column );
  1097. $parameterType = eZPHPCreator::METHOD_CALL_PARAMETER_VALUE;
  1098. $parameterValue = $parameterData[0];
  1099. if ( isset( $parameterData[1] ) )
  1100. $parameterType = $parameterData[1];
  1101. if ( $parameterType == eZPHPCreator::METHOD_CALL_PARAMETER_VALUE )
  1102. $text .= ' ' . $this->thisVariableText( $parameterValue, $column + 1 );
  1103. else if ( $parameterType == eZPHPCreator::METHOD_CALL_PARAMETER_VARIABLE )
  1104. $text .= ' $' . $parameterValue;
  1105. ++$i;
  1106. }
  1107. if ( $i > 0 )
  1108. $text .= ' ';
  1109. $text .= ");\n";
  1110. $text = eZPHPCreator::prependSpacing( $text, $spacing );
  1111. $this->write( $text );
  1112. }
  1113. /*!
  1114. \private
  1115. */
  1116. function writeVariableUnset( $element )
  1117. {
  1118. $variableName = $element[1];
  1119. $parameters = $element[2];
  1120. $spacing = 0;
  1121. if ( isset( $parameters['spacing'] ) and $this->Spacing )
  1122. $spacing = $parameters['spacing'];
  1123. $text = "unset( \$$variableName );\n";
  1124. $text = eZPHPCreator::prependSpacing( $text, $spacing );
  1125. $this->write( $text );
  1126. }
  1127. /*!
  1128. \private
  1129. */
  1130. function writeVariableUnsetList( $element )
  1131. {
  1132. $variableNames = $element[1];
  1133. if ( count( $variableNames ) )
  1134. {
  1135. $parameters = $element[2];
  1136. $spacing = 0;
  1137. if ( isset( $parameters['spacing'] ) and $this->Spacing )
  1138. $spacing = $parameters['spacing'];
  1139. $text = 'unset( ';
  1140. array_walk( $variableNames, function ( &$variableName ) {
  1141. $variableName = "\$" . $variableName;
  1142. });
  1143. $text .= join( ', ', $variableNames );
  1144. $text .= " );\n";
  1145. $text = eZPHPCreator::prependSpacing( $text, $spacing );
  1146. $this->write( $text );
  1147. }
  1148. }
  1149. /*!
  1150. \private
  1151. */
  1152. function writeRawVariable( $variableName, $variableValue )
  1153. {
  1154. $this->write( "\${$variableName} = ". var_export( $variableValue, true). ";\n" );
  1155. }
  1156. /*!
  1157. \private
  1158. */
  1159. function writeVariable( $variableName, $variableValue, $assignmentType = eZPHPCreator::VARIABLE_ASSIGNMENT,
  1160. $variableParameters = array() )
  1161. {
  1162. $variableParameters = array_merge( array( 'full-tree' => false,
  1163. 'spacing' => 0 ),
  1164. $variableParameters );
  1165. $fullTree = $variableParameters['full-tree'];
  1166. $spacing = $this->Spacing ? $variableParameters['spacing'] : 0;
  1167. $text = $this->variableNameText( $variableName, $assignmentType, $variableParameters );
  1168. $maxIterations = 2;
  1169. if ( $fullTree )
  1170. $maxIterations = false;
  1171. $text .= $this->thisVariableText( $variableValue, strlen( $text ), 0, $maxIterations );
  1172. $text .= ";\n";
  1173. $text = eZPHPCreator::prependSpacing( $text, $spacing );
  1174. $this->write( $text );
  1175. }
  1176. /*!
  1177. \private
  1178. */
  1179. function temporaryVariableName( $prefix )
  1180. {
  1181. $variableName = $prefix . '_' . $this->TemporaryCounter;
  1182. ++$this->TemporaryCounter;
  1183. return $variableName;
  1184. }
  1185. /// \privatesection
  1186. public $PHPDir;
  1187. public $PHPFile;
  1188. public $FileResource;
  1189. public $Elements;
  1190. public $TextChunks;
  1191. public $isAtomic;
  1192. public $tmpFilename;
  1193. public $requestedFilename;
  1194. public $Spacing = true;
  1195. public $ClusteringEnabled = false;
  1196. public $ClusterFileScope = false;
  1197. }
  1198. ?>