Bootstrap.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. <?php
  2. use Google\Auth\HttpHandler\HttpHandlerFactory;
  3. use Google\Cloud\Core\Exception\BadRequestException;
  4. use Google\Cloud\Core\Exception\NotFoundException;
  5. use Google\Cloud\Storage\Bucket;
  6. use Google\Cloud\Storage\Connection\ConnectionInterface;
  7. use Google\Cloud\Storage\StorageClient;
  8. use Google\Cloud\Storage\StorageObject;
  9. use GuzzleHttp\Client;
  10. use PrivateBin\Data\GoogleCloudStorage;
  11. use PrivateBin\Persistence\ServerSalt;
  12. error_reporting(E_ALL | E_STRICT);
  13. // change this, if your php files and data is outside of your webservers document root
  14. if (!defined('PUBLIC_PATH')) {
  15. define('PUBLIC_PATH', '..');
  16. }
  17. if (!defined('PATH')) {
  18. define('PATH', '..' . DIRECTORY_SEPARATOR);
  19. }
  20. if (!defined('CONF')) {
  21. define('CONF', PATH . 'cfg' . DIRECTORY_SEPARATOR . 'conf.php');
  22. }
  23. if (!defined('CONF_SAMPLE')) {
  24. define('CONF_SAMPLE', PATH . 'cfg' . DIRECTORY_SEPARATOR . 'conf.sample.php');
  25. }
  26. require PATH . 'vendor/autoload.php';
  27. Helper::updateSubresourceIntegrity();
  28. /**
  29. * Class StorageClientStub provides a limited stub for performing the unit test
  30. */
  31. class StorageClientStub extends StorageClient
  32. {
  33. private $_config = null;
  34. private $_connection = null;
  35. private $_buckets = array();
  36. public function __construct(array $config = array())
  37. {
  38. $this->_config = $config;
  39. $this->_connection = new ConnectionInterfaceStub();
  40. }
  41. public function bucket($name, $userProject = false)
  42. {
  43. if (!key_exists($name, $this->_buckets)) {
  44. $b = new BucketStub($this->_connection, $name, array(), $this);
  45. $this->_buckets[$name] = $b;
  46. }
  47. return $this->_buckets[$name];
  48. }
  49. /**
  50. * @throws \Google\Cloud\Core\Exception\NotFoundException
  51. */
  52. public function deleteBucket($name)
  53. {
  54. if (key_exists($name, $this->_buckets)) {
  55. unset($this->_buckets[$name]);
  56. } else {
  57. throw new NotFoundException();
  58. }
  59. }
  60. public function buckets(array $options = array())
  61. {
  62. throw new BadMethodCallException('not supported by this stub');
  63. }
  64. public function registerStreamWrapper($protocol = null)
  65. {
  66. throw new BadMethodCallException('not supported by this stub');
  67. }
  68. public function unregisterStreamWrapper($protocol = null)
  69. {
  70. throw new BadMethodCallException('not supported by this stub');
  71. }
  72. public function signedUrlUploader($uri, $data, array $options = array())
  73. {
  74. throw new BadMethodCallException('not supported by this stub');
  75. }
  76. public function timestamp(\DateTimeInterface $timestamp, $nanoSeconds = null)
  77. {
  78. throw new BadMethodCallException('not supported by this stub');
  79. }
  80. public function getServiceAccount(array $options = array())
  81. {
  82. throw new BadMethodCallException('not supported by this stub');
  83. }
  84. public function hmacKeys(array $options = array())
  85. {
  86. throw new BadMethodCallException('not supported by this stub');
  87. }
  88. public function hmacKey($accessId, $projectId = null, array $metadata = array())
  89. {
  90. throw new BadMethodCallException('not supported by this stub');
  91. }
  92. public function createHmacKey($serviceAccountEmail, array $options = array())
  93. {
  94. throw new BadMethodCallException('not supported by this stub');
  95. }
  96. public function createBucket($name, array $options = array())
  97. {
  98. if (key_exists($name, $this->_buckets)) {
  99. throw new BadRequestException('already exists');
  100. }
  101. $b = new BucketStub($this->_connection, $name, array(), $this);
  102. $this->_buckets[$name] = $b;
  103. return $b;
  104. }
  105. }
  106. /**
  107. * Class BucketStub stubs a GCS bucket.
  108. */
  109. class BucketStub extends Bucket
  110. {
  111. public $_objects;
  112. private $_name;
  113. private $_info;
  114. private $_connection;
  115. private $_client;
  116. public function __construct(ConnectionInterface $connection, $name, array $info = array(), $client = null)
  117. {
  118. $this->_name = $name;
  119. $this->_info = $info;
  120. $this->_connection = $connection;
  121. $this->_objects = array();
  122. $this->_client = $client;
  123. }
  124. public function acl()
  125. {
  126. throw new BadMethodCallException('not supported by this stub');
  127. }
  128. public function defaultAcl()
  129. {
  130. throw new BadMethodCallException('not supported by this stub');
  131. }
  132. public function exists()
  133. {
  134. return true;
  135. }
  136. public function upload($data, array $options = array())
  137. {
  138. if (!is_string($data) || !key_exists('name', $options)) {
  139. throw new BadMethodCallException('not supported by this stub');
  140. }
  141. $name = $options['name'];
  142. $generation = '1';
  143. $o = new StorageObjectStub($this->_connection, $name, $this, $generation, $options);
  144. $this->_objects[$options['name']] = $o;
  145. $o->setData($data);
  146. }
  147. public function uploadAsync($data, array $options = array())
  148. {
  149. throw new BadMethodCallException('not supported by this stub');
  150. }
  151. public function getResumableUploader($data, array $options = array())
  152. {
  153. throw new BadMethodCallException('not supported by this stub');
  154. }
  155. public function getStreamableUploader($data, array $options = array())
  156. {
  157. throw new BadMethodCallException('not supported by this stub');
  158. }
  159. public function object($name, array $options = array())
  160. {
  161. if (key_exists($name, $this->_objects)) {
  162. return $this->_objects[$name];
  163. } else {
  164. return new StorageObjectStub($this->_connection, $name, $this, null, $options);
  165. }
  166. }
  167. public function objects(array $options = array())
  168. {
  169. $prefix = key_exists('prefix', $options) ? $options['prefix'] : '';
  170. return new CallbackFilterIterator(
  171. new ArrayIterator($this->_objects),
  172. function ($current, $key, $iterator) use ($prefix) {
  173. return substr($key, 0, strlen($prefix)) == $prefix;
  174. }
  175. );
  176. }
  177. public function createNotification($topic, array $options = array())
  178. {
  179. throw new BadMethodCallException('not supported by this stub');
  180. }
  181. public function notification($id)
  182. {
  183. throw new BadMethodCallException('not supported by this stub');
  184. }
  185. public function notifications(array $options = array())
  186. {
  187. throw new BadMethodCallException('not supported by this stub');
  188. }
  189. public function delete(array $options = array())
  190. {
  191. $this->_client->deleteBucket($this->_name);
  192. }
  193. public function update(array $options = array())
  194. {
  195. throw new BadMethodCallException('not supported by this stub');
  196. }
  197. public function compose(array $sourceObjects, $name, array $options = array())
  198. {
  199. throw new BadMethodCallException('not supported by this stub');
  200. }
  201. public function info(array $options = array())
  202. {
  203. throw new BadMethodCallException('not supported by this stub');
  204. }
  205. public function reload(array $options = array())
  206. {
  207. throw new BadMethodCallException('not supported by this stub');
  208. }
  209. public function name()
  210. {
  211. return $this->_name;
  212. }
  213. public static function lifecycle(array $lifecycle = array())
  214. {
  215. throw new BadMethodCallException('not supported by this stub');
  216. }
  217. public function currentLifecycle(array $options = array())
  218. {
  219. throw new BadMethodCallException('not supported by this stub');
  220. }
  221. public function isWritable($file = null)
  222. {
  223. throw new BadMethodCallException('not supported by this stub');
  224. }
  225. public function iam()
  226. {
  227. throw new BadMethodCallException('not supported by this stub');
  228. }
  229. public function lockRetentionPolicy(array $options = array())
  230. {
  231. throw new BadMethodCallException('not supported by this stub');
  232. }
  233. public function signedUrl($expires, array $options = array())
  234. {
  235. throw new BadMethodCallException('not supported by this stub');
  236. }
  237. public function generateSignedPostPolicyV4($objectName, $expires, array $options = array())
  238. {
  239. throw new BadMethodCallException('not supported by this stub');
  240. }
  241. }
  242. /**
  243. * Class StorageObjectStub stubs a GCS storage object.
  244. */
  245. class StorageObjectStub extends StorageObject
  246. {
  247. private $_name;
  248. private $_data;
  249. private $_info;
  250. private $_bucket;
  251. private $_generation;
  252. private $_exists = false;
  253. private $_connection;
  254. public function __construct(ConnectionInterface $connection, $name, $bucket, $generation = null, array $info = array(), $encryptionKey = null, $encryptionKeySHA256 = null)
  255. {
  256. $this->_name = $name;
  257. $this->_bucket = $bucket;
  258. $this->_generation = $generation;
  259. $this->_info = $info;
  260. $this->_connection = $connection;
  261. $timeCreated = new Datetime();
  262. $this->_info['metadata']['timeCreated'] = $timeCreated->format(GoogleCloudStorage::DATETIME_FORMAT);
  263. }
  264. public function acl()
  265. {
  266. throw new BadMethodCallException('not supported by this stub');
  267. }
  268. public function exists(array $options = array())
  269. {
  270. return key_exists($this->_name, $this->_bucket->_objects);
  271. }
  272. /**
  273. * @throws NotFoundException
  274. */
  275. public function delete(array $options = array())
  276. {
  277. if (key_exists($this->_name, $this->_bucket->_objects)) {
  278. unset($this->_bucket->_objects[$this->_name]);
  279. } else {
  280. throw new NotFoundException('key ' . $this->_name . ' not found.');
  281. }
  282. }
  283. /**
  284. * @throws NotFoundException
  285. */
  286. public function update(array $metadata, array $options = array())
  287. {
  288. if (!$this->_exists) {
  289. throw new NotFoundException('key ' . $this->_name . ' not found.');
  290. }
  291. $this->_info = $metadata;
  292. }
  293. public function copy($destination, array $options = array())
  294. {
  295. throw new BadMethodCallException('not supported by this stub');
  296. }
  297. public function rewrite($destination, array $options = array())
  298. {
  299. throw new BadMethodCallException('not supported by this stub');
  300. }
  301. public function rename($name, array $options = array())
  302. {
  303. throw new BadMethodCallException('not supported by this stub');
  304. }
  305. /**
  306. * @throws NotFoundException
  307. */
  308. public function downloadAsString(array $options = array())
  309. {
  310. if (!$this->_exists) {
  311. throw new NotFoundException('key ' . $this->_name . ' not found.');
  312. }
  313. return $this->_data;
  314. }
  315. public function downloadToFile($path, array $options = array())
  316. {
  317. throw new BadMethodCallException('not supported by this stub');
  318. }
  319. public function downloadAsStream(array $options = array())
  320. {
  321. throw new BadMethodCallException('not supported by this stub');
  322. }
  323. public function downloadAsStreamAsync(array $options = array())
  324. {
  325. throw new BadMethodCallException('not supported by this stub');
  326. }
  327. public function signedUrl($expires, array $options = array())
  328. {
  329. throw new BadMethodCallException('not supported by this stub');
  330. }
  331. public function signedUploadUrl($expires, array $options = array())
  332. {
  333. throw new BadMethodCallException('not supported by this stub');
  334. }
  335. public function beginSignedUploadSession(array $options = array())
  336. {
  337. throw new BadMethodCallException('not supported by this stub');
  338. }
  339. public function info(array $options = array())
  340. {
  341. return key_exists('metadata',$this->_info) ? $this->_info['metadata'] : array();
  342. }
  343. public function reload(array $options = array())
  344. {
  345. throw new BadMethodCallException('not supported by this stub');
  346. }
  347. public function name()
  348. {
  349. return $this->_name;
  350. }
  351. public function identity()
  352. {
  353. throw new BadMethodCallException('not supported by this stub');
  354. }
  355. public function gcsUri()
  356. {
  357. return sprintf(
  358. 'gs://%s/%s',
  359. $this->_bucket->name(),
  360. $this->_name
  361. );
  362. }
  363. public function setData($data)
  364. {
  365. $this->_data = $data;
  366. $this->_exists = true;
  367. }
  368. }
  369. /**
  370. * Class ConnectionInterfaceStub required for the stubs.
  371. */
  372. class ConnectionInterfaceStub implements ConnectionInterface
  373. {
  374. public function deleteAcl(array $args = array())
  375. {
  376. throw new BadMethodCallException('not supported by this stub');
  377. }
  378. public function getAcl(array $args = array())
  379. {
  380. throw new BadMethodCallException('not supported by this stub');
  381. }
  382. public function listAcl(array $args = array())
  383. {
  384. throw new BadMethodCallException('not supported by this stub');
  385. }
  386. public function insertAcl(array $args = array())
  387. {
  388. throw new BadMethodCallException('not supported by this stub');
  389. }
  390. public function patchAcl(array $args = array())
  391. {
  392. throw new BadMethodCallException('not supported by this stub');
  393. }
  394. public function deleteBucket(array $args = array())
  395. {
  396. throw new BadMethodCallException('not supported by this stub');
  397. }
  398. public function getBucket(array $args = array())
  399. {
  400. throw new BadMethodCallException('not supported by this stub');
  401. }
  402. public function listBuckets(array $args = array())
  403. {
  404. throw new BadMethodCallException('not supported by this stub');
  405. }
  406. public function insertBucket(array $args = array())
  407. {
  408. throw new BadMethodCallException('not supported by this stub');
  409. }
  410. public function getBucketIamPolicy(array $args)
  411. {
  412. throw new BadMethodCallException('not supported by this stub');
  413. }
  414. public function setBucketIamPolicy(array $args)
  415. {
  416. throw new BadMethodCallException('not supported by this stub');
  417. }
  418. public function testBucketIamPermissions(array $args)
  419. {
  420. throw new BadMethodCallException('not supported by this stub');
  421. }
  422. public function patchBucket(array $args = array())
  423. {
  424. throw new BadMethodCallException('not supported by this stub');
  425. }
  426. public function deleteObject(array $args = array())
  427. {
  428. throw new BadMethodCallException('not supported by this stub');
  429. }
  430. public function copyObject(array $args = array())
  431. {
  432. throw new BadMethodCallException('not supported by this stub');
  433. }
  434. public function rewriteObject(array $args = array())
  435. {
  436. throw new BadMethodCallException('not supported by this stub');
  437. }
  438. public function composeObject(array $args = array())
  439. {
  440. throw new BadMethodCallException('not supported by this stub');
  441. }
  442. public function getObject(array $args = array())
  443. {
  444. throw new BadMethodCallException('not supported by this stub');
  445. }
  446. public function listObjects(array $args = array())
  447. {
  448. throw new BadMethodCallException('not supported by this stub');
  449. }
  450. public function patchObject(array $args = array())
  451. {
  452. throw new BadMethodCallException('not supported by this stub');
  453. }
  454. public function downloadObject(array $args = array())
  455. {
  456. throw new BadMethodCallException('not supported by this stub');
  457. }
  458. public function insertObject(array $args = array())
  459. {
  460. throw new BadMethodCallException('not supported by this stub');
  461. }
  462. public function getNotification(array $args = array())
  463. {
  464. throw new BadMethodCallException('not supported by this stub');
  465. }
  466. public function deleteNotification(array $args = array())
  467. {
  468. throw new BadMethodCallException('not supported by this stub');
  469. }
  470. public function insertNotification(array $args = array())
  471. {
  472. throw new BadMethodCallException('not supported by this stub');
  473. }
  474. public function listNotifications(array $args = array())
  475. {
  476. throw new BadMethodCallException('not supported by this stub');
  477. }
  478. public function getServiceAccount(array $args = array())
  479. {
  480. throw new BadMethodCallException('not supported by this stub');
  481. }
  482. public function lockRetentionPolicy(array $args = array())
  483. {
  484. throw new BadMethodCallException('not supported by this stub');
  485. }
  486. public function createHmacKey(array $args = array())
  487. {
  488. throw new BadMethodCallException('not supported by this stub');
  489. }
  490. public function deleteHmacKey(array $args = array())
  491. {
  492. throw new BadMethodCallException('not supported by this stub');
  493. }
  494. public function getHmacKey(array $args = array())
  495. {
  496. throw new BadMethodCallException('not supported by this stub');
  497. }
  498. public function updateHmacKey(array $args = array())
  499. {
  500. throw new BadMethodCallException('not supported by this stub');
  501. }
  502. public function listHmacKeys(array $args = array())
  503. {
  504. throw new BadMethodCallException('not supported by this stub');
  505. }
  506. }
  507. /**
  508. * Class Helper provides unit tests pastes and comments of various formats
  509. */
  510. class Helper
  511. {
  512. /**
  513. * example ID of a paste
  514. *
  515. * @var string
  516. */
  517. private static $pasteid = '5b65a01b43987bc2';
  518. /**
  519. * example paste version 1
  520. *
  521. * @var array
  522. */
  523. private static $pasteV1 = array(
  524. 'data' => '{"iv":"EN39/wd5Nk8HAiSG2K5AsQ","v":1,"iter":1000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"QKN1DBXe5PI","ct":"8hA83xDdXjD7K2qfmw5NdA"}',
  525. 'attachment' => '{"iv":"Pd4pOKWkmDTT9uPwVwd5Ag","v":1,"iter":1000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"ZIUhFTliVz4","ct":"6nOCU3peNDclDDpFtJEBKA"}',
  526. 'attachmentname' => '{"iv":"76MkAtOGC4oFogX/aSMxRA","v":1,"iter":1000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"ZIUhFTliVz4","ct":"b6Ae/U1xJdsX/+lATud4sQ"}',
  527. 'meta' => array(
  528. 'formatter' => 'plaintext',
  529. 'postdate' => 1344803344,
  530. 'opendiscussion' => true,
  531. ),
  532. );
  533. /**
  534. * example paste version 2
  535. *
  536. * @var array
  537. */
  538. private static $pasteV2 = array(
  539. 'adata' => array(
  540. array(
  541. 'gMSNoLOk4z0RnmsYwXZ8mw==',
  542. 'TZO+JWuIuxs=',
  543. 100000,
  544. 256,
  545. 128,
  546. 'aes',
  547. 'gcm',
  548. 'zlib',
  549. ),
  550. 'plaintext',
  551. 1,
  552. 0,
  553. ),
  554. 'meta' => array(
  555. 'expire' => '5min',
  556. 'created' => 1344803344,
  557. ),
  558. 'v' => 2,
  559. 'ct' => 'ME5JF/YBEijp2uYMzLZozbKtWc5wfy6R59NBb7SmRig=',
  560. );
  561. /**
  562. * example ID of a comment
  563. *
  564. * @var string
  565. */
  566. private static $commentid = '5a52eebf11c4c94b';
  567. /**
  568. * example comment
  569. *
  570. * @var array
  571. */
  572. private static $commentV1 = array(
  573. 'data' => '{"iv":"Pd4pOKWkmDTT9uPwVwd5Ag","v":1,"iter":1000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"ZIUhFTliVz4","ct":"6nOCU3peNDclDDpFtJEBKA"}',
  574. 'meta' => array(
  575. 'nickname' => '{"iv":"76MkAtOGC4oFogX/aSMxRA","v":1,"iter":1000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"ZIUhFTliVz4","ct":"b6Ae/U1xJdsX/+lATud4sQ"}',
  576. 'vizhash' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGUlEQVQokWOsl5/94983CNKQMjnxaOePf98MeKwPfNjkLZ3AgARab6b9+PeNEVnDj3/ff/z7ZiHnzsDA8Pv7H2TVPJw8EAYLAwb48OaVgIgYKycLsrYv378wMDB8//qdCVMDRA9EKSsnCwRBxNsepaLboMFlyMDAICAi9uHNK24GITQ/MDAwoNhgIGMLtwGrzegaLjw5jMz9+vUdnN17uwDCQDhJgk0O07yvX9+teDX1x79v6DYIsIjgcgMaYGFgYOBg4kJx2JejkAiBxAw+PzAwMNz4dp6wDXDw4MdNNOl0rWYsNkD89OLXI/xmo9sgzatJjAYmBgYGDiauD3/ePP18nVgb4MF89+M5ZX6js293wUMpnr8KTQMAxsCJnJ30apMAAAAASUVORK5CYII=',
  577. 'postdate' => 1344803528,
  578. ),
  579. );
  580. /**
  581. * JS files and their SRI hashes
  582. *
  583. * @var array
  584. */
  585. private static $hashes = array();
  586. /**
  587. * get example paste ID
  588. *
  589. * @return string
  590. */
  591. public static function getPasteId()
  592. {
  593. return version_compare(PHP_VERSION, '5.6', '<') ? hash('fnv164', self::$pasteV2['ct']) : self::$pasteid;
  594. }
  595. /**
  596. * get example paste, as stored on server
  597. *
  598. * @param int $version
  599. * @param array $meta
  600. * @return array
  601. */
  602. public static function getPaste($version = 2, array $meta = array())
  603. {
  604. $example = self::getPasteWithAttachment($version, $meta);
  605. // v1 has the attachment stored in a separate property
  606. if ($version === 1) {
  607. unset($example['attachment'], $example['attachmentname']);
  608. }
  609. return $example;
  610. }
  611. /**
  612. * get example paste with attachment, as stored on server
  613. *
  614. * @param int $version
  615. * @param array $meta
  616. * @return array
  617. */
  618. public static function getPasteWithAttachment($version = 2, array $meta = array())
  619. {
  620. $example = $version === 1 ? self::$pasteV1 : self::$pasteV2;
  621. $example['meta']['salt'] = ServerSalt::generate();
  622. $example['meta'] = array_merge($example['meta'], $meta);
  623. return $example;
  624. }
  625. /**
  626. * get example paste, as decoded from POST by the request object
  627. *
  628. * @param int $version
  629. * @param array $meta
  630. * @return array
  631. */
  632. public static function getPastePost($version = 2, array $meta = array())
  633. {
  634. $example = self::getPaste($version, $meta);
  635. if ($version == 2) {
  636. $example['meta'] = array('expire' => $example['meta']['expire']);
  637. } else {
  638. unset($example['meta']['postdate']);
  639. }
  640. return $example;
  641. }
  642. /**
  643. * get example paste, as received via POST by the user
  644. *
  645. * @param int $version
  646. * @param array $meta
  647. * @return array
  648. */
  649. public static function getPasteJson($version = 2, array $meta = array())
  650. {
  651. return json_encode(self::getPastePost($version, $meta));
  652. }
  653. /**
  654. * get example paste ID
  655. *
  656. * @return string
  657. */
  658. public static function getCommentId()
  659. {
  660. return self::$commentid;
  661. }
  662. /**
  663. * get example comment, as stored on server
  664. *
  665. * @param int $version
  666. * @param array $meta
  667. * @return array
  668. */
  669. public static function getComment($version = 2, array $meta = array())
  670. {
  671. $example = $version === 1 ? self::$commentV1 : self::$pasteV2;
  672. if ($version === 2) {
  673. $example['adata'] = $example['adata'][0];
  674. $example['pasteid'] = $example['parentid'] = self::getPasteId();
  675. $example['meta']['created'] = self::$commentV1['meta']['postdate'];
  676. $example['meta']['icon'] = self::$commentV1['meta']['vizhash'];
  677. unset($example['meta']['expire']);
  678. }
  679. $example['meta'] = array_merge($example['meta'], $meta);
  680. return $example;
  681. }
  682. /**
  683. * get example comment, as decoded from POST by the request object
  684. *
  685. * @param int $version
  686. * @return array
  687. */
  688. public static function getCommentPost()
  689. {
  690. $example = self::getComment();
  691. unset($example['meta']);
  692. return $example;
  693. }
  694. /**
  695. * get example comment, as received via POST by user
  696. *
  697. * @param int $version
  698. * @return array
  699. */
  700. public static function getCommentJson()
  701. {
  702. return json_encode(self::getCommentPost());
  703. }
  704. /**
  705. * delete directory and all its contents recursively
  706. *
  707. * @param string $path
  708. * @throws Exception
  709. */
  710. public static function rmDir($path)
  711. {
  712. if (is_dir($path)) {
  713. $path .= DIRECTORY_SEPARATOR;
  714. $dir = dir($path);
  715. while (false !== ($file = $dir->read())) {
  716. if ($file != '.' && $file != '..') {
  717. if (is_dir($path . $file)) {
  718. self::rmDir($path . $file);
  719. } elseif (is_file($path . $file)) {
  720. if (!unlink($path . $file)) {
  721. throw new Exception('Error deleting file "' . $path . $file . '".');
  722. }
  723. }
  724. }
  725. }
  726. $dir->close();
  727. if (!rmdir($path)) {
  728. throw new Exception('Error deleting directory "' . $path . '".');
  729. }
  730. }
  731. }
  732. /**
  733. * create a backup of the config file
  734. *
  735. * @return void
  736. */
  737. public static function confBackup()
  738. {
  739. if (!is_file(CONF . '.bak') && is_file(CONF)) {
  740. rename(CONF, CONF . '.bak');
  741. }
  742. if (!is_file(CONF_SAMPLE . '.bak') && is_file(CONF_SAMPLE)) {
  743. copy(CONF_SAMPLE, CONF_SAMPLE . '.bak');
  744. }
  745. }
  746. /**
  747. * restor backup of the config file
  748. *
  749. * @return void
  750. */
  751. public static function confRestore()
  752. {
  753. if (is_file(CONF . '.bak')) {
  754. rename(CONF . '.bak', CONF);
  755. }
  756. if (is_file(CONF_SAMPLE . '.bak')) {
  757. rename(CONF_SAMPLE . '.bak', CONF_SAMPLE);
  758. }
  759. }
  760. /**
  761. * create ini file
  762. *
  763. * @param string $pathToFile
  764. * @param array $values
  765. */
  766. public static function createIniFile($pathToFile, array $values)
  767. {
  768. if (count($values)) {
  769. @unlink($pathToFile);
  770. $ini = fopen($pathToFile, 'a');
  771. foreach ($values as $section => $options) {
  772. fwrite($ini, "[$section]" . PHP_EOL);
  773. foreach ($options as $option => $setting) {
  774. if (is_null($setting)) {
  775. continue;
  776. } elseif (is_string($setting)) {
  777. $setting = '"' . $setting . '"';
  778. } elseif (is_array($setting)) {
  779. foreach ($setting as $key => $value) {
  780. if (is_null($value)) {
  781. $value = 'null';
  782. } elseif (is_string($value)) {
  783. $value = '"' . $value . '"';
  784. } else {
  785. $value = var_export($value, true);
  786. }
  787. fwrite($ini, $option . "[$key] = $value" . PHP_EOL);
  788. }
  789. continue;
  790. } else {
  791. $setting = var_export($setting, true);
  792. }
  793. fwrite($ini, "$option = $setting" . PHP_EOL);
  794. }
  795. fwrite($ini, PHP_EOL);
  796. }
  797. fclose($ini);
  798. }
  799. }
  800. /**
  801. * a var_export that returns arrays without line breaks
  802. * by linus@flowingcreativity.net via php.net
  803. *
  804. * @param mixed $var
  805. * @param bool $return
  806. * @return void|string
  807. */
  808. public static function varExportMin($var, $return = false)
  809. {
  810. if (is_array($var)) {
  811. $toImplode = array();
  812. foreach ($var as $key => $value) {
  813. $toImplode[] = var_export($key, true) . ' => ' . self::varExportMin($value, true);
  814. }
  815. $code = 'array(' . implode(', ', $toImplode) . ')';
  816. if ($return) {
  817. return $code;
  818. } else {
  819. echo $code;
  820. }
  821. } else {
  822. return var_export($var, $return);
  823. }
  824. }
  825. /**
  826. * update all templates with the latest SRI hashes for all JS files
  827. *
  828. * @return void
  829. */
  830. public static function updateSubresourceIntegrity()
  831. {
  832. $dir = dir(PATH . 'js');
  833. while (false !== ($file = $dir->read())) {
  834. if (substr($file, -3) === '.js') {
  835. self::$hashes[$file] = base64_encode(
  836. hash('sha512', file_get_contents(
  837. PATH . 'js' . DIRECTORY_SEPARATOR . $file
  838. ), true)
  839. );
  840. }
  841. }
  842. $dir = dir(PATH . 'tpl');
  843. while (false !== ($file = $dir->read())) {
  844. if (substr($file, -4) === '.php') {
  845. $content = file_get_contents(
  846. PATH . 'tpl' . DIRECTORY_SEPARATOR . $file
  847. );
  848. $content = preg_replace_callback(
  849. '#<script ([^>]+) src="js/([a-z0-9.-]+.js)([^"]*)"( integrity="[^"]+" crossorigin="[^"]+")?></script>#',
  850. function ($matches) {
  851. if (array_key_exists($matches[2], Helper::$hashes)) {
  852. return '<script ' . $matches[1] . ' src="js/' .
  853. $matches[2] . $matches[3] .
  854. '" integrity="sha512-' . Helper::$hashes[$matches[2]] .
  855. '" crossorigin="anonymous"></script>';
  856. } else {
  857. return $matches[0];
  858. }
  859. },
  860. $content
  861. );
  862. file_put_contents(
  863. PATH . 'tpl' . DIRECTORY_SEPARATOR . $file,
  864. $content
  865. );
  866. }
  867. }
  868. }
  869. }