Bootstrap.php 29 KB

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