extension.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  1. <?php
  2. /**
  3. * DokuWiki Plugin extension (Helper Component)
  4. *
  5. * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
  6. * @author Michael Hamann <michael@content-space.de>
  7. */
  8. use dokuwiki\HTTP\DokuHTTPClient;
  9. use dokuwiki\Extension\PluginController;
  10. /**
  11. * Class helper_plugin_extension_extension represents a single extension (plugin or template)
  12. */
  13. class helper_plugin_extension_extension extends DokuWiki_Plugin
  14. {
  15. private $id;
  16. private $base;
  17. private $is_template = false;
  18. private $localInfo;
  19. private $remoteInfo;
  20. private $managerData;
  21. /** @var helper_plugin_extension_repository $repository */
  22. private $repository = null;
  23. /** @var array list of temporary directories */
  24. private $temporary = array();
  25. /** @var string where templates are installed to */
  26. private $tpllib = '';
  27. /**
  28. * helper_plugin_extension_extension constructor.
  29. */
  30. public function __construct()
  31. {
  32. $this->tpllib = dirname(tpl_incdir()).'/';
  33. }
  34. /**
  35. * Destructor
  36. *
  37. * deletes any dangling temporary directories
  38. */
  39. public function __destruct()
  40. {
  41. foreach ($this->temporary as $dir) {
  42. io_rmdir($dir, true);
  43. }
  44. }
  45. /**
  46. * @return bool false, this component is not a singleton
  47. */
  48. public function isSingleton()
  49. {
  50. return false;
  51. }
  52. /**
  53. * Set the name of the extension this instance shall represents, triggers loading the local and remote data
  54. *
  55. * @param string $id The id of the extension (prefixed with template: for templates)
  56. * @return bool If some (local or remote) data was found
  57. */
  58. public function setExtension($id)
  59. {
  60. $id = cleanID($id);
  61. $this->id = $id;
  62. $this->base = $id;
  63. if (substr($id, 0, 9) == 'template:') {
  64. $this->base = substr($id, 9);
  65. $this->is_template = true;
  66. } else {
  67. $this->is_template = false;
  68. }
  69. $this->localInfo = array();
  70. $this->managerData = array();
  71. $this->remoteInfo = array();
  72. if ($this->isInstalled()) {
  73. $this->readLocalData();
  74. $this->readManagerData();
  75. }
  76. if ($this->repository == null) {
  77. $this->repository = $this->loadHelper('extension_repository');
  78. }
  79. $this->remoteInfo = $this->repository->getData($this->getID());
  80. return ($this->localInfo || $this->remoteInfo);
  81. }
  82. /**
  83. * If the extension is installed locally
  84. *
  85. * @return bool If the extension is installed locally
  86. */
  87. public function isInstalled()
  88. {
  89. return is_dir($this->getInstallDir());
  90. }
  91. /**
  92. * If the extension is under git control
  93. *
  94. * @return bool
  95. */
  96. public function isGitControlled()
  97. {
  98. if (!$this->isInstalled()) return false;
  99. return file_exists($this->getInstallDir().'/.git');
  100. }
  101. /**
  102. * If the extension is bundled
  103. *
  104. * @return bool If the extension is bundled
  105. */
  106. public function isBundled()
  107. {
  108. if (!empty($this->remoteInfo['bundled'])) return $this->remoteInfo['bundled'];
  109. return in_array(
  110. $this->id,
  111. array(
  112. 'authad', 'authldap', 'authpdo', 'authplain',
  113. 'acl', 'config', 'extension', 'info', 'popularity', 'revert',
  114. 'safefnrecode', 'styling', 'testing', 'usermanager', 'logviewer',
  115. 'template:dokuwiki',
  116. )
  117. );
  118. }
  119. /**
  120. * If the extension is protected against any modification (disable/uninstall)
  121. *
  122. * @return bool if the extension is protected
  123. */
  124. public function isProtected()
  125. {
  126. // never allow deinstalling the current auth plugin:
  127. global $conf;
  128. if ($this->id == $conf['authtype']) return true;
  129. /** @var PluginController $plugin_controller */
  130. global $plugin_controller;
  131. $cascade = $plugin_controller->getCascade();
  132. return (isset($cascade['protected'][$this->id]) && $cascade['protected'][$this->id]);
  133. }
  134. /**
  135. * If the extension is installed in the correct directory
  136. *
  137. * @return bool If the extension is installed in the correct directory
  138. */
  139. public function isInWrongFolder()
  140. {
  141. return $this->base != $this->getBase();
  142. }
  143. /**
  144. * If the extension is enabled
  145. *
  146. * @return bool If the extension is enabled
  147. */
  148. public function isEnabled()
  149. {
  150. global $conf;
  151. if ($this->isTemplate()) {
  152. return ($conf['template'] == $this->getBase());
  153. }
  154. /* @var PluginController $plugin_controller */
  155. global $plugin_controller;
  156. return $plugin_controller->isEnabled($this->base);
  157. }
  158. /**
  159. * If the extension should be updated, i.e. if an updated version is available
  160. *
  161. * @return bool If an update is available
  162. */
  163. public function updateAvailable()
  164. {
  165. if (!$this->isInstalled()) return false;
  166. if ($this->isBundled()) return false;
  167. $lastupdate = $this->getLastUpdate();
  168. if ($lastupdate === false) return false;
  169. $installed = $this->getInstalledVersion();
  170. if ($installed === false || $installed === $this->getLang('unknownversion')) return true;
  171. return $this->getInstalledVersion() < $this->getLastUpdate();
  172. }
  173. /**
  174. * If the extension is a template
  175. *
  176. * @return bool If this extension is a template
  177. */
  178. public function isTemplate()
  179. {
  180. return $this->is_template;
  181. }
  182. /**
  183. * Get the ID of the extension
  184. *
  185. * This is the same as getName() for plugins, for templates it's getName() prefixed with 'template:'
  186. *
  187. * @return string
  188. */
  189. public function getID()
  190. {
  191. return $this->id;
  192. }
  193. /**
  194. * Get the name of the installation directory
  195. *
  196. * @return string The name of the installation directory
  197. */
  198. public function getInstallName()
  199. {
  200. return $this->base;
  201. }
  202. // Data from plugin.info.txt/template.info.txt or the repo when not available locally
  203. /**
  204. * Get the basename of the extension
  205. *
  206. * @return string The basename
  207. */
  208. public function getBase()
  209. {
  210. if (!empty($this->localInfo['base'])) return $this->localInfo['base'];
  211. return $this->base;
  212. }
  213. /**
  214. * Get the display name of the extension
  215. *
  216. * @return string The display name
  217. */
  218. public function getDisplayName()
  219. {
  220. if (!empty($this->localInfo['name'])) return $this->localInfo['name'];
  221. if (!empty($this->remoteInfo['name'])) return $this->remoteInfo['name'];
  222. return $this->base;
  223. }
  224. /**
  225. * Get the author name of the extension
  226. *
  227. * @return string|bool The name of the author or false if there is none
  228. */
  229. public function getAuthor()
  230. {
  231. if (!empty($this->localInfo['author'])) return $this->localInfo['author'];
  232. if (!empty($this->remoteInfo['author'])) return $this->remoteInfo['author'];
  233. return false;
  234. }
  235. /**
  236. * Get the email of the author of the extension if there is any
  237. *
  238. * @return string|bool The email address or false if there is none
  239. */
  240. public function getEmail()
  241. {
  242. // email is only in the local data
  243. if (!empty($this->localInfo['email'])) return $this->localInfo['email'];
  244. return false;
  245. }
  246. /**
  247. * Get the email id, i.e. the md5sum of the email
  248. *
  249. * @return string|bool The md5sum of the email if there is any, false otherwise
  250. */
  251. public function getEmailID()
  252. {
  253. if (!empty($this->remoteInfo['emailid'])) return $this->remoteInfo['emailid'];
  254. if (!empty($this->localInfo['email'])) return md5($this->localInfo['email']);
  255. return false;
  256. }
  257. /**
  258. * Get the description of the extension
  259. *
  260. * @return string The description
  261. */
  262. public function getDescription()
  263. {
  264. if (!empty($this->localInfo['desc'])) return $this->localInfo['desc'];
  265. if (!empty($this->remoteInfo['description'])) return $this->remoteInfo['description'];
  266. return '';
  267. }
  268. /**
  269. * Get the URL of the extension, usually a page on dokuwiki.org
  270. *
  271. * @return string The URL
  272. */
  273. public function getURL()
  274. {
  275. if (!empty($this->localInfo['url'])) return $this->localInfo['url'];
  276. return 'https://www.dokuwiki.org/'.
  277. ($this->isTemplate() ? 'template' : 'plugin').':'.$this->getBase();
  278. }
  279. /**
  280. * Get the installed version of the extension
  281. *
  282. * @return string|bool The version, usually in the form yyyy-mm-dd if there is any
  283. */
  284. public function getInstalledVersion()
  285. {
  286. if (!empty($this->localInfo['date'])) return $this->localInfo['date'];
  287. if ($this->isInstalled()) return $this->getLang('unknownversion');
  288. return false;
  289. }
  290. /**
  291. * Get the install date of the current version
  292. *
  293. * @return string|bool The date of the last update or false if not available
  294. */
  295. public function getUpdateDate()
  296. {
  297. if (!empty($this->managerData['updated'])) return $this->managerData['updated'];
  298. return $this->getInstallDate();
  299. }
  300. /**
  301. * Get the date of the installation of the plugin
  302. *
  303. * @return string|bool The date of the installation or false if not available
  304. */
  305. public function getInstallDate()
  306. {
  307. if (!empty($this->managerData['installed'])) return $this->managerData['installed'];
  308. return false;
  309. }
  310. /**
  311. * Get the names of the dependencies of this extension
  312. *
  313. * @return array The base names of the dependencies
  314. */
  315. public function getDependencies()
  316. {
  317. if (!empty($this->remoteInfo['dependencies'])) return $this->remoteInfo['dependencies'];
  318. return array();
  319. }
  320. /**
  321. * Get the names of the missing dependencies
  322. *
  323. * @return array The base names of the missing dependencies
  324. */
  325. public function getMissingDependencies()
  326. {
  327. /* @var PluginController $plugin_controller */
  328. global $plugin_controller;
  329. $dependencies = $this->getDependencies();
  330. $missing_dependencies = array();
  331. foreach ($dependencies as $dependency) {
  332. if (!$plugin_controller->isEnabled($dependency)) {
  333. $missing_dependencies[] = $dependency;
  334. }
  335. }
  336. return $missing_dependencies;
  337. }
  338. /**
  339. * Get the names of all conflicting extensions
  340. *
  341. * @return array The names of the conflicting extensions
  342. */
  343. public function getConflicts()
  344. {
  345. if (!empty($this->remoteInfo['conflicts'])) return $this->remoteInfo['conflicts'];
  346. return array();
  347. }
  348. /**
  349. * Get the names of similar extensions
  350. *
  351. * @return array The names of similar extensions
  352. */
  353. public function getSimilarExtensions()
  354. {
  355. if (!empty($this->remoteInfo['similar'])) return $this->remoteInfo['similar'];
  356. return array();
  357. }
  358. /**
  359. * Get the names of the tags of the extension
  360. *
  361. * @return array The names of the tags of the extension
  362. */
  363. public function getTags()
  364. {
  365. if (!empty($this->remoteInfo['tags'])) return $this->remoteInfo['tags'];
  366. return array();
  367. }
  368. /**
  369. * Get the popularity information as floating point number [0,1]
  370. *
  371. * @return float|bool The popularity information or false if it isn't available
  372. */
  373. public function getPopularity()
  374. {
  375. if (!empty($this->remoteInfo['popularity'])) return $this->remoteInfo['popularity'];
  376. return false;
  377. }
  378. /**
  379. * Get the text of the security warning if there is any
  380. *
  381. * @return string|bool The security warning if there is any, false otherwise
  382. */
  383. public function getSecurityWarning()
  384. {
  385. if (!empty($this->remoteInfo['securitywarning'])) return $this->remoteInfo['securitywarning'];
  386. return false;
  387. }
  388. /**
  389. * Get the text of the security issue if there is any
  390. *
  391. * @return string|bool The security issue if there is any, false otherwise
  392. */
  393. public function getSecurityIssue()
  394. {
  395. if (!empty($this->remoteInfo['securityissue'])) return $this->remoteInfo['securityissue'];
  396. return false;
  397. }
  398. /**
  399. * Get the URL of the screenshot of the extension if there is any
  400. *
  401. * @return string|bool The screenshot URL if there is any, false otherwise
  402. */
  403. public function getScreenshotURL()
  404. {
  405. if (!empty($this->remoteInfo['screenshoturl'])) return $this->remoteInfo['screenshoturl'];
  406. return false;
  407. }
  408. /**
  409. * Get the URL of the thumbnail of the extension if there is any
  410. *
  411. * @return string|bool The thumbnail URL if there is any, false otherwise
  412. */
  413. public function getThumbnailURL()
  414. {
  415. if (!empty($this->remoteInfo['thumbnailurl'])) return $this->remoteInfo['thumbnailurl'];
  416. return false;
  417. }
  418. /**
  419. * Get the last used download URL of the extension if there is any
  420. *
  421. * @return string|bool The previously used download URL, false if the extension has been installed manually
  422. */
  423. public function getLastDownloadURL()
  424. {
  425. if (!empty($this->managerData['downloadurl'])) return $this->managerData['downloadurl'];
  426. return false;
  427. }
  428. /**
  429. * Get the download URL of the extension if there is any
  430. *
  431. * @return string|bool The download URL if there is any, false otherwise
  432. */
  433. public function getDownloadURL()
  434. {
  435. if (!empty($this->remoteInfo['downloadurl'])) return $this->remoteInfo['downloadurl'];
  436. return false;
  437. }
  438. /**
  439. * If the download URL has changed since the last download
  440. *
  441. * @return bool If the download URL has changed
  442. */
  443. public function hasDownloadURLChanged()
  444. {
  445. $lasturl = $this->getLastDownloadURL();
  446. $currenturl = $this->getDownloadURL();
  447. return ($lasturl && $currenturl && $lasturl != $currenturl);
  448. }
  449. /**
  450. * Get the bug tracker URL of the extension if there is any
  451. *
  452. * @return string|bool The bug tracker URL if there is any, false otherwise
  453. */
  454. public function getBugtrackerURL()
  455. {
  456. if (!empty($this->remoteInfo['bugtracker'])) return $this->remoteInfo['bugtracker'];
  457. return false;
  458. }
  459. /**
  460. * Get the URL of the source repository if there is any
  461. *
  462. * @return string|bool The URL of the source repository if there is any, false otherwise
  463. */
  464. public function getSourcerepoURL()
  465. {
  466. if (!empty($this->remoteInfo['sourcerepo'])) return $this->remoteInfo['sourcerepo'];
  467. return false;
  468. }
  469. /**
  470. * Get the donation URL of the extension if there is any
  471. *
  472. * @return string|bool The donation URL if there is any, false otherwise
  473. */
  474. public function getDonationURL()
  475. {
  476. if (!empty($this->remoteInfo['donationurl'])) return $this->remoteInfo['donationurl'];
  477. return false;
  478. }
  479. /**
  480. * Get the extension type(s)
  481. *
  482. * @return array The type(s) as array of strings
  483. */
  484. public function getTypes()
  485. {
  486. if (!empty($this->remoteInfo['types'])) return $this->remoteInfo['types'];
  487. if ($this->isTemplate()) return array(32 => 'template');
  488. return array();
  489. }
  490. /**
  491. * Get a list of all DokuWiki versions this extension is compatible with
  492. *
  493. * @return array The versions in the form yyyy-mm-dd => ('label' => label, 'implicit' => implicit)
  494. */
  495. public function getCompatibleVersions()
  496. {
  497. if (!empty($this->remoteInfo['compatible'])) return $this->remoteInfo['compatible'];
  498. return array();
  499. }
  500. /**
  501. * Get the date of the last available update
  502. *
  503. * @return string|bool The last available update in the form yyyy-mm-dd if there is any, false otherwise
  504. */
  505. public function getLastUpdate()
  506. {
  507. if (!empty($this->remoteInfo['lastupdate'])) return $this->remoteInfo['lastupdate'];
  508. return false;
  509. }
  510. /**
  511. * Get the base path of the extension
  512. *
  513. * @return string The base path of the extension
  514. */
  515. public function getInstallDir()
  516. {
  517. if ($this->isTemplate()) {
  518. return $this->tpllib.$this->base;
  519. } else {
  520. return DOKU_PLUGIN.$this->base;
  521. }
  522. }
  523. /**
  524. * The type of extension installation
  525. *
  526. * @return string One of "none", "manual", "git" or "automatic"
  527. */
  528. public function getInstallType()
  529. {
  530. if (!$this->isInstalled()) return 'none';
  531. if (!empty($this->managerData)) return 'automatic';
  532. if (is_dir($this->getInstallDir().'/.git')) return 'git';
  533. return 'manual';
  534. }
  535. /**
  536. * If the extension can probably be installed/updated or uninstalled
  537. *
  538. * @return bool|string True or error string
  539. */
  540. public function canModify()
  541. {
  542. if ($this->isInstalled()) {
  543. if (!is_writable($this->getInstallDir())) {
  544. return 'noperms';
  545. }
  546. }
  547. if ($this->isTemplate() && !is_writable($this->tpllib)) {
  548. return 'notplperms';
  549. } elseif (!is_writable(DOKU_PLUGIN)) {
  550. return 'nopluginperms';
  551. }
  552. return true;
  553. }
  554. /**
  555. * Install an extension from a user upload
  556. *
  557. * @param string $field name of the upload file
  558. * @param boolean $overwrite overwrite folder if the extension name is the same
  559. * @throws Exception when something goes wrong
  560. * @return array The list of installed extensions
  561. */
  562. public function installFromUpload($field, $overwrite = true)
  563. {
  564. if ($_FILES[$field]['error']) {
  565. throw new Exception($this->getLang('msg_upload_failed').' ('.$_FILES[$field]['error'].')');
  566. }
  567. $tmp = $this->mkTmpDir();
  568. if (!$tmp) throw new Exception($this->getLang('error_dircreate'));
  569. // filename may contain the plugin name for old style plugins...
  570. $basename = basename($_FILES[$field]['name']);
  571. $basename = preg_replace('/\.(tar\.gz|tar\.bz|tar\.bz2|tar|tgz|tbz|zip)$/', '', $basename);
  572. $basename = preg_replace('/[\W]+/', '', $basename);
  573. if (!move_uploaded_file($_FILES[$field]['tmp_name'], "$tmp/upload.archive")) {
  574. throw new Exception($this->getLang('msg_upload_failed'));
  575. }
  576. try {
  577. $installed = $this->installArchive("$tmp/upload.archive", $overwrite, $basename);
  578. $this->updateManagerData('', $installed);
  579. $this->removeDeletedfiles($installed);
  580. // purge cache
  581. $this->purgeCache();
  582. } catch (Exception $e) {
  583. throw $e;
  584. }
  585. return $installed;
  586. }
  587. /**
  588. * Install an extension from a remote URL
  589. *
  590. * @param string $url
  591. * @param boolean $overwrite overwrite folder if the extension name is the same
  592. * @throws Exception when something goes wrong
  593. * @return array The list of installed extensions
  594. */
  595. public function installFromURL($url, $overwrite = true)
  596. {
  597. try {
  598. $path = $this->download($url);
  599. $installed = $this->installArchive($path, $overwrite);
  600. $this->updateManagerData($url, $installed);
  601. $this->removeDeletedfiles($installed);
  602. // purge cache
  603. $this->purgeCache();
  604. } catch (Exception $e) {
  605. throw $e;
  606. }
  607. return $installed;
  608. }
  609. /**
  610. * Install or update the extension
  611. *
  612. * @throws \Exception when something goes wrong
  613. * @return array The list of installed extensions
  614. */
  615. public function installOrUpdate()
  616. {
  617. $url = $this->getDownloadURL();
  618. $path = $this->download($url);
  619. $installed = $this->installArchive($path, $this->isInstalled(), $this->getBase());
  620. $this->updateManagerData($url, $installed);
  621. // refresh extension information
  622. if (!isset($installed[$this->getID()])) {
  623. throw new Exception('Error, the requested extension hasn\'t been installed or updated');
  624. }
  625. $this->removeDeletedfiles($installed);
  626. $this->setExtension($this->getID());
  627. $this->purgeCache();
  628. return $installed;
  629. }
  630. /**
  631. * Uninstall the extension
  632. *
  633. * @return bool If the plugin was sucessfully uninstalled
  634. */
  635. public function uninstall()
  636. {
  637. $this->purgeCache();
  638. return io_rmdir($this->getInstallDir(), true);
  639. }
  640. /**
  641. * Enable the extension
  642. *
  643. * @return bool|string True or an error message
  644. */
  645. public function enable()
  646. {
  647. if ($this->isTemplate()) return $this->getLang('notimplemented');
  648. if (!$this->isInstalled()) return $this->getLang('notinstalled');
  649. if ($this->isEnabled()) return $this->getLang('alreadyenabled');
  650. /* @var PluginController $plugin_controller */
  651. global $plugin_controller;
  652. if ($plugin_controller->enable($this->base)) {
  653. $this->purgeCache();
  654. return true;
  655. } else {
  656. return $this->getLang('pluginlistsaveerror');
  657. }
  658. }
  659. /**
  660. * Disable the extension
  661. *
  662. * @return bool|string True or an error message
  663. */
  664. public function disable()
  665. {
  666. if ($this->isTemplate()) return $this->getLang('notimplemented');
  667. /* @var PluginController $plugin_controller */
  668. global $plugin_controller;
  669. if (!$this->isInstalled()) return $this->getLang('notinstalled');
  670. if (!$this->isEnabled()) return $this->getLang('alreadydisabled');
  671. if ($plugin_controller->disable($this->base)) {
  672. $this->purgeCache();
  673. return true;
  674. } else {
  675. return $this->getLang('pluginlistsaveerror');
  676. }
  677. }
  678. /**
  679. * Purge the cache by touching the main configuration file
  680. */
  681. protected function purgeCache()
  682. {
  683. global $config_cascade;
  684. // expire dokuwiki caches
  685. // touching local.php expires wiki page, JS and CSS caches
  686. @touch(reset($config_cascade['main']['local']));
  687. }
  688. /**
  689. * Read local extension data either from info.txt or getInfo()
  690. */
  691. protected function readLocalData()
  692. {
  693. if ($this->isTemplate()) {
  694. $infopath = $this->getInstallDir().'/template.info.txt';
  695. } else {
  696. $infopath = $this->getInstallDir().'/plugin.info.txt';
  697. }
  698. if (is_readable($infopath)) {
  699. $this->localInfo = confToHash($infopath);
  700. } elseif (!$this->isTemplate() && $this->isEnabled()) {
  701. $path = $this->getInstallDir().'/';
  702. $plugin = null;
  703. foreach (PluginController::PLUGIN_TYPES as $type) {
  704. if (file_exists($path.$type.'.php')) {
  705. $plugin = plugin_load($type, $this->base);
  706. if ($plugin) break;
  707. }
  708. if ($dh = @opendir($path.$type.'/')) {
  709. while (false !== ($cp = readdir($dh))) {
  710. if ($cp == '.' || $cp == '..' || strtolower(substr($cp, -4)) != '.php') continue;
  711. $plugin = plugin_load($type, $this->base.'_'.substr($cp, 0, -4));
  712. if ($plugin) break;
  713. }
  714. if ($plugin) break;
  715. closedir($dh);
  716. }
  717. }
  718. if ($plugin) {
  719. /* @var DokuWiki_Plugin $plugin */
  720. $this->localInfo = $plugin->getInfo();
  721. }
  722. }
  723. }
  724. /**
  725. * Save the given URL and current datetime in the manager.dat file of all installed extensions
  726. *
  727. * @param string $url Where the extension was downloaded from. (empty for manual installs via upload)
  728. * @param array $installed Optional list of installed plugins
  729. */
  730. protected function updateManagerData($url = '', $installed = null)
  731. {
  732. $origID = $this->getID();
  733. if (is_null($installed)) {
  734. $installed = array($origID);
  735. }
  736. foreach ($installed as $ext => $info) {
  737. if ($this->getID() != $ext) $this->setExtension($ext);
  738. if ($url) {
  739. $this->managerData['downloadurl'] = $url;
  740. } elseif (isset($this->managerData['downloadurl'])) {
  741. unset($this->managerData['downloadurl']);
  742. }
  743. if (isset($this->managerData['installed'])) {
  744. $this->managerData['updated'] = date('r');
  745. } else {
  746. $this->managerData['installed'] = date('r');
  747. }
  748. $this->writeManagerData();
  749. }
  750. if ($this->getID() != $origID) $this->setExtension($origID);
  751. }
  752. /**
  753. * Read the manager.dat file
  754. */
  755. protected function readManagerData()
  756. {
  757. $managerpath = $this->getInstallDir().'/manager.dat';
  758. if (is_readable($managerpath)) {
  759. $file = @file($managerpath);
  760. if (!empty($file)) {
  761. foreach ($file as $line) {
  762. list($key, $value) = sexplode('=', trim($line, DOKU_LF), 2, '');
  763. $key = trim($key);
  764. $value = trim($value);
  765. // backwards compatible with old plugin manager
  766. if ($key == 'url') $key = 'downloadurl';
  767. $this->managerData[$key] = $value;
  768. }
  769. }
  770. }
  771. }
  772. /**
  773. * Write the manager.data file
  774. */
  775. protected function writeManagerData()
  776. {
  777. $managerpath = $this->getInstallDir().'/manager.dat';
  778. $data = '';
  779. foreach ($this->managerData as $k => $v) {
  780. $data .= $k.'='.$v.DOKU_LF;
  781. }
  782. io_saveFile($managerpath, $data);
  783. }
  784. /**
  785. * Returns a temporary directory
  786. *
  787. * The directory is registered for cleanup when the class is destroyed
  788. *
  789. * @return false|string
  790. */
  791. protected function mkTmpDir()
  792. {
  793. $dir = io_mktmpdir();
  794. if (!$dir) return false;
  795. $this->temporary[] = $dir;
  796. return $dir;
  797. }
  798. /**
  799. * downloads a file from the net and saves it
  800. *
  801. * - $file is the directory where the file should be saved
  802. * - if successful will return the name used for the saved file, false otherwise
  803. *
  804. * @author Andreas Gohr <andi@splitbrain.org>
  805. * @author Chris Smith <chris@jalakai.co.uk>
  806. *
  807. * @param string $url url to download
  808. * @param string $file path to file or directory where to save
  809. * @param string $defaultName fallback for name of download
  810. * @return bool|string if failed false, otherwise true or the name of the file in the given dir
  811. */
  812. protected function downloadToFile($url, $file, $defaultName = '')
  813. {
  814. global $conf;
  815. $http = new DokuHTTPClient();
  816. $http->max_bodysize = 0;
  817. $http->timeout = 25; //max. 25 sec
  818. $http->keep_alive = false; // we do single ops here, no need for keep-alive
  819. $http->agent = 'DokuWiki HTTP Client (Extension Manager)';
  820. $data = $http->get($url);
  821. if ($data === false) return false;
  822. $name = '';
  823. if (isset($http->resp_headers['content-disposition'])) {
  824. $content_disposition = $http->resp_headers['content-disposition'];
  825. $match = array();
  826. if (is_string($content_disposition) &&
  827. preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)
  828. ) {
  829. $name = \dokuwiki\Utf8\PhpString::basename($match[1]);
  830. }
  831. }
  832. if (!$name) {
  833. if (!$defaultName) return false;
  834. $name = $defaultName;
  835. }
  836. $file = $file.$name;
  837. $fileexists = file_exists($file);
  838. $fp = @fopen($file,"w");
  839. if (!$fp) return false;
  840. fwrite($fp, $data);
  841. fclose($fp);
  842. if (!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
  843. return $name;
  844. }
  845. /**
  846. * Download an archive to a protected path
  847. *
  848. * @param string $url The url to get the archive from
  849. * @throws Exception when something goes wrong
  850. * @return string The path where the archive was saved
  851. */
  852. public function download($url)
  853. {
  854. // check the url
  855. if (!preg_match('/https?:\/\//i', $url)) {
  856. throw new Exception($this->getLang('error_badurl'));
  857. }
  858. // try to get the file from the path (used as plugin name fallback)
  859. $file = parse_url($url, PHP_URL_PATH);
  860. if (is_null($file)) {
  861. $file = md5($url);
  862. } else {
  863. $file = \dokuwiki\Utf8\PhpString::basename($file);
  864. }
  865. // create tmp directory for download
  866. if (!($tmp = $this->mkTmpDir())) {
  867. throw new Exception($this->getLang('error_dircreate'));
  868. }
  869. // download
  870. if (!$file = $this->downloadToFile($url, $tmp.'/', $file)) {
  871. io_rmdir($tmp, true);
  872. throw new Exception(sprintf($this->getLang('error_download'),
  873. '<bdi>'.hsc($url).'</bdi>')
  874. );
  875. }
  876. return $tmp.'/'.$file;
  877. }
  878. /**
  879. * @param string $file The path to the archive that shall be installed
  880. * @param bool $overwrite If an already installed plugin should be overwritten
  881. * @param string $base The basename of the plugin if it's known
  882. * @throws Exception when something went wrong
  883. * @return array list of installed extensions
  884. */
  885. public function installArchive($file, $overwrite = false, $base = '')
  886. {
  887. $installed_extensions = array();
  888. // create tmp directory for decompression
  889. if (!($tmp = $this->mkTmpDir())) {
  890. throw new Exception($this->getLang('error_dircreate'));
  891. }
  892. // add default base folder if specified to handle case where zip doesn't contain this
  893. if ($base && !@mkdir($tmp.'/'.$base)) {
  894. throw new Exception($this->getLang('error_dircreate'));
  895. }
  896. // decompress
  897. $this->decompress($file, "$tmp/".$base);
  898. // search $tmp/$base for the folder(s) that has been created
  899. // move the folder(s) to lib/..
  900. $result = array('old'=>array(), 'new'=>array());
  901. $default = ($this->isTemplate() ? 'template' : 'plugin');
  902. if (!$this->findFolders($result, $tmp.'/'.$base, $default)) {
  903. throw new Exception($this->getLang('error_findfolder'));
  904. }
  905. // choose correct result array
  906. if (count($result['new'])) {
  907. $install = $result['new'];
  908. } else {
  909. $install = $result['old'];
  910. }
  911. if (!count($install)) {
  912. throw new Exception($this->getLang('error_findfolder'));
  913. }
  914. // now install all found items
  915. foreach ($install as $item) {
  916. // where to install?
  917. if ($item['type'] == 'template') {
  918. $target_base_dir = $this->tpllib;
  919. } else {
  920. $target_base_dir = DOKU_PLUGIN;
  921. }
  922. if (!empty($item['base'])) {
  923. // use base set in info.txt
  924. } elseif ($base && count($install) == 1) {
  925. $item['base'] = $base;
  926. } else {
  927. // default - use directory as found in zip
  928. // plugins from github/master without *.info.txt will install in wrong folder
  929. // but using $info->id will make 'code3' fail (which should install in lib/code/..)
  930. $item['base'] = basename($item['tmp']);
  931. }
  932. // check to make sure we aren't overwriting anything
  933. $target = $target_base_dir.$item['base'];
  934. if (!$overwrite && file_exists($target)) {
  935. // this info message is not being exposed via exception,
  936. // so that it's not interrupting the installation
  937. msg(sprintf($this->getLang('msg_nooverwrite'), $item['base']));
  938. continue;
  939. }
  940. $action = file_exists($target) ? 'update' : 'install';
  941. // copy action
  942. if ($this->dircopy($item['tmp'], $target)) {
  943. // return info
  944. $id = $item['base'];
  945. if ($item['type'] == 'template') {
  946. $id = 'template:'.$id;
  947. }
  948. $installed_extensions[$id] = array(
  949. 'base' => $item['base'],
  950. 'type' => $item['type'],
  951. 'action' => $action
  952. );
  953. } else {
  954. throw new Exception(sprintf($this->getLang('error_copy').DOKU_LF,
  955. '<bdi>'.$item['base'].'</bdi>')
  956. );
  957. }
  958. }
  959. // cleanup
  960. if ($tmp) io_rmdir($tmp, true);
  961. return $installed_extensions;
  962. }
  963. /**
  964. * Find out what was in the extracted directory
  965. *
  966. * Correct folders are searched recursively using the "*.info.txt" configs
  967. * as indicator for a root folder. When such a file is found, it's base
  968. * setting is used (when set). All folders found by this method are stored
  969. * in the 'new' key of the $result array.
  970. *
  971. * For backwards compatibility all found top level folders are stored as
  972. * in the 'old' key of the $result array.
  973. *
  974. * When no items are found in 'new' the copy mechanism should fall back
  975. * the 'old' list.
  976. *
  977. * @author Andreas Gohr <andi@splitbrain.org>
  978. * @param array $result - results are stored here
  979. * @param string $directory - the temp directory where the package was unpacked to
  980. * @param string $default_type - type used if no info.txt available
  981. * @param string $subdir - a subdirectory. do not set. used by recursion
  982. * @return bool - false on error
  983. */
  984. protected function findFolders(&$result, $directory, $default_type = 'plugin', $subdir = '')
  985. {
  986. $this_dir = "$directory$subdir";
  987. $dh = @opendir($this_dir);
  988. if (!$dh) return false;
  989. $found_dirs = array();
  990. $found_files = 0;
  991. $found_template_parts = 0;
  992. while (false !== ($f = readdir($dh))) {
  993. if ($f == '.' || $f == '..') continue;
  994. if (is_dir("$this_dir/$f")) {
  995. $found_dirs[] = "$subdir/$f";
  996. } else {
  997. // it's a file -> check for config
  998. $found_files++;
  999. switch ($f) {
  1000. case 'plugin.info.txt':
  1001. case 'template.info.txt':
  1002. // we have found a clear marker, save and return
  1003. $info = array();
  1004. $type = explode('.', $f, 2);
  1005. $info['type'] = $type[0];
  1006. $info['tmp'] = $this_dir;
  1007. $conf = confToHash("$this_dir/$f");
  1008. $info['base'] = basename($conf['base']);
  1009. $result['new'][] = $info;
  1010. return true;
  1011. case 'main.php':
  1012. case 'details.php':
  1013. case 'mediamanager.php':
  1014. case 'style.ini':
  1015. $found_template_parts++;
  1016. break;
  1017. }
  1018. }
  1019. }
  1020. closedir($dh);
  1021. // files where found but no info.txt - use old method
  1022. if ($found_files) {
  1023. $info = array();
  1024. $info['tmp'] = $this_dir;
  1025. // does this look like a template or should we use the default type?
  1026. if ($found_template_parts >= 2) {
  1027. $info['type'] = 'template';
  1028. } else {
  1029. $info['type'] = $default_type;
  1030. }
  1031. $result['old'][] = $info;
  1032. return true;
  1033. }
  1034. // we have no files yet -> recurse
  1035. foreach ($found_dirs as $found_dir) {
  1036. $this->findFolders($result, $directory, $default_type, "$found_dir");
  1037. }
  1038. return true;
  1039. }
  1040. /**
  1041. * Decompress a given file to the given target directory
  1042. *
  1043. * Determines the compression type from the file extension
  1044. *
  1045. * @param string $file archive to extract
  1046. * @param string $target directory to extract to
  1047. * @throws Exception
  1048. * @return bool
  1049. */
  1050. private function decompress($file, $target)
  1051. {
  1052. // decompression library doesn't like target folders ending in "/"
  1053. if (substr($target, -1) == "/") $target = substr($target, 0, -1);
  1054. $ext = $this->guessArchiveType($file);
  1055. if (in_array($ext, array('tar', 'bz', 'gz'))) {
  1056. try {
  1057. $tar = new \splitbrain\PHPArchive\Tar();
  1058. $tar->open($file);
  1059. $tar->extract($target);
  1060. } catch (\splitbrain\PHPArchive\ArchiveIOException $e) {
  1061. throw new Exception($this->getLang('error_decompress').' '.$e->getMessage());
  1062. }
  1063. return true;
  1064. } elseif ($ext == 'zip') {
  1065. try {
  1066. $zip = new \splitbrain\PHPArchive\Zip();
  1067. $zip->open($file);
  1068. $zip->extract($target);
  1069. } catch (\splitbrain\PHPArchive\ArchiveIOException $e) {
  1070. throw new Exception($this->getLang('error_decompress').' '.$e->getMessage());
  1071. }
  1072. return true;
  1073. }
  1074. // the only case when we don't get one of the recognized archive types is
  1075. // when the archive file can't be read
  1076. throw new Exception($this->getLang('error_decompress').' Couldn\'t read archive file');
  1077. }
  1078. /**
  1079. * Determine the archive type of the given file
  1080. *
  1081. * Reads the first magic bytes of the given file for content type guessing,
  1082. * if neither bz, gz or zip are recognized, tar is assumed.
  1083. *
  1084. * @author Andreas Gohr <andi@splitbrain.org>
  1085. * @param string $file The file to analyze
  1086. * @return string|false false if the file can't be read, otherwise an "extension"
  1087. */
  1088. private function guessArchiveType($file)
  1089. {
  1090. $fh = fopen($file, 'rb');
  1091. if (!$fh) return false;
  1092. $magic = fread($fh, 5);
  1093. fclose($fh);
  1094. if (strpos($magic, "\x42\x5a") === 0) return 'bz';
  1095. if (strpos($magic, "\x1f\x8b") === 0) return 'gz';
  1096. if (strpos($magic, "\x50\x4b\x03\x04") === 0) return 'zip';
  1097. return 'tar';
  1098. }
  1099. /**
  1100. * Copy with recursive sub-directory support
  1101. *
  1102. * @param string $src filename path to file
  1103. * @param string $dst filename path to file
  1104. * @return bool|int|string
  1105. */
  1106. private function dircopy($src, $dst)
  1107. {
  1108. global $conf;
  1109. if (is_dir($src)) {
  1110. if (!$dh = @opendir($src)) return false;
  1111. if ($ok = io_mkdir_p($dst)) {
  1112. while ($ok && (false !== ($f = readdir($dh)))) {
  1113. if ($f == '..' || $f == '.') continue;
  1114. $ok = $this->dircopy("$src/$f", "$dst/$f");
  1115. }
  1116. }
  1117. closedir($dh);
  1118. return $ok;
  1119. } else {
  1120. $existed = file_exists($dst);
  1121. if (!@copy($src, $dst)) return false;
  1122. if (!$existed && $conf['fperm']) chmod($dst, $conf['fperm']);
  1123. @touch($dst, filemtime($src));
  1124. }
  1125. return true;
  1126. }
  1127. /**
  1128. * Delete outdated files from updated plugins
  1129. *
  1130. * @param array $installed
  1131. */
  1132. private function removeDeletedfiles($installed)
  1133. {
  1134. foreach ($installed as $id => $extension) {
  1135. // only on update
  1136. if ($extension['action'] == 'install') continue;
  1137. // get definition file
  1138. if ($extension['type'] == 'template') {
  1139. $extensiondir = $this->tpllib;
  1140. } else {
  1141. $extensiondir = DOKU_PLUGIN;
  1142. }
  1143. $extensiondir = $extensiondir . $extension['base'] .'/';
  1144. $definitionfile = $extensiondir . 'deleted.files';
  1145. if (!file_exists($definitionfile)) continue;
  1146. // delete the old files
  1147. $list = file($definitionfile);
  1148. foreach ($list as $line) {
  1149. $line = trim(preg_replace('/#.*$/', '', $line));
  1150. if (!$line) continue;
  1151. $file = $extensiondir . $line;
  1152. if (!file_exists($file)) continue;
  1153. io_rmdir($file, true);
  1154. }
  1155. }
  1156. }
  1157. }
  1158. // vim:ts=4:sw=4:et: