media.php 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156
  1. <?php
  2. /**
  3. * All output and handler function needed for the media management popup
  4. *
  5. * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
  6. * @author Andreas Gohr <andi@splitbrain.org>
  7. */
  8. use dokuwiki\ChangeLog\MediaChangeLog;
  9. use dokuwiki\Extension\Event;
  10. use dokuwiki\Form\Form;
  11. use dokuwiki\HTTP\DokuHTTPClient;
  12. use dokuwiki\Logger;
  13. use dokuwiki\Subscriptions\MediaSubscriptionSender;
  14. use dokuwiki\Ui\Media\DisplayRow;
  15. use dokuwiki\Ui\Media\DisplayTile;
  16. use dokuwiki\Ui\MediaDiff;
  17. use dokuwiki\Utf8\PhpString;
  18. use dokuwiki\Utf8\Sort;
  19. use splitbrain\slika\Slika;
  20. /**
  21. * Lists pages which currently use a media file selected for deletion
  22. *
  23. * References uses the same visual as search results and share
  24. * their CSS tags except pagenames won't be links.
  25. *
  26. * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
  27. *
  28. * @param array $data
  29. * @param string $id
  30. */
  31. function media_filesinuse($data,$id){
  32. global $lang;
  33. echo '<h1>'.$lang['reference'].' <code>'.hsc(noNS($id)).'</code></h1>';
  34. echo '<p>'.hsc($lang['ref_inuse']).'</p>';
  35. $hidden=0; //count of hits without read permission
  36. foreach($data as $row){
  37. if(auth_quickaclcheck($row) >= AUTH_READ && isVisiblePage($row)){
  38. echo '<div class="search_result">';
  39. echo '<span class="mediaref_ref">'.hsc($row).'</span>';
  40. echo '</div>';
  41. }else
  42. $hidden++;
  43. }
  44. if ($hidden){
  45. print '<div class="mediaref_hidden">'.$lang['ref_hidden'].'</div>';
  46. }
  47. }
  48. /**
  49. * Handles the saving of image meta data
  50. *
  51. * @author Andreas Gohr <andi@splitbrain.org>
  52. * @author Kate Arzamastseva <pshns@ukr.net>
  53. *
  54. * @param string $id media id
  55. * @param int $auth permission level
  56. * @param array $data
  57. * @return false|string
  58. */
  59. function media_metasave($id,$auth,$data){
  60. if($auth < AUTH_UPLOAD) return false;
  61. if(!checkSecurityToken()) return false;
  62. global $lang;
  63. global $conf;
  64. $src = mediaFN($id);
  65. $meta = new JpegMeta($src);
  66. $meta->_parseAll();
  67. foreach($data as $key => $val){
  68. $val=trim($val);
  69. if(empty($val)){
  70. $meta->deleteField($key);
  71. }else{
  72. $meta->setField($key,$val);
  73. }
  74. }
  75. $old = @filemtime($src);
  76. if(!file_exists(mediaFN($id, $old)) && file_exists($src)) {
  77. // add old revision to the attic
  78. media_saveOldRevision($id);
  79. }
  80. $filesize_old = filesize($src);
  81. if($meta->save()){
  82. if($conf['fperm']) chmod($src, $conf['fperm']);
  83. @clearstatcache(true, $src);
  84. $new = @filemtime($src);
  85. $filesize_new = filesize($src);
  86. $sizechange = $filesize_new - $filesize_old;
  87. // add a log entry to the media changelog
  88. addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT, $lang['media_meta_edited'], '', null, $sizechange);
  89. msg($lang['metasaveok'],1);
  90. return $id;
  91. }else{
  92. msg($lang['metasaveerr'],-1);
  93. return false;
  94. }
  95. }
  96. /**
  97. * check if a media is external source
  98. *
  99. * @author Gerrit Uitslag <klapinklapin@gmail.com>
  100. *
  101. * @param string $id the media ID or URL
  102. * @return bool
  103. */
  104. function media_isexternal($id){
  105. if (preg_match('#^(?:https?|ftp)://#i', $id)) return true;
  106. return false;
  107. }
  108. /**
  109. * Check if a media item is public (eg, external URL or readable by @ALL)
  110. *
  111. * @author Andreas Gohr <andi@splitbrain.org>
  112. *
  113. * @param string $id the media ID or URL
  114. * @return bool
  115. */
  116. function media_ispublic($id){
  117. if(media_isexternal($id)) return true;
  118. $id = cleanID($id);
  119. if(auth_aclcheck(getNS($id).':*', '', array()) >= AUTH_READ) return true;
  120. return false;
  121. }
  122. /**
  123. * Display the form to edit image meta data
  124. *
  125. * @author Andreas Gohr <andi@splitbrain.org>
  126. * @author Kate Arzamastseva <pshns@ukr.net>
  127. *
  128. * @param string $id media id
  129. * @param int $auth permission level
  130. * @return bool
  131. */
  132. function media_metaform($id, $auth) {
  133. global $lang;
  134. if ($auth < AUTH_UPLOAD) {
  135. echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.DOKU_LF;
  136. return false;
  137. }
  138. // load the field descriptions
  139. static $fields = null;
  140. if ($fields === null) {
  141. $config_files = getConfigFiles('mediameta');
  142. foreach ($config_files as $config_file) {
  143. if (file_exists($config_file)) include($config_file);
  144. }
  145. }
  146. $src = mediaFN($id);
  147. // output
  148. $form = new Form([
  149. 'action' => media_managerURL(['tab_details' => 'view'], '&'),
  150. 'class' => 'meta'
  151. ]);
  152. $form->addTagOpen('div')->addClass('no');
  153. $form->setHiddenField('img', $id);
  154. $form->setHiddenField('mediado', 'save');
  155. foreach ($fields as $key => $field) {
  156. // get current value
  157. if (empty($field[0])) continue;
  158. $tags = array($field[0]);
  159. if (is_array($field[3])) $tags = array_merge($tags, $field[3]);
  160. $value = tpl_img_getTag($tags, '', $src);
  161. $value = cleanText($value);
  162. // prepare attributes
  163. $p = array(
  164. 'class' => 'edit',
  165. 'id' => 'meta__'.$key,
  166. 'name' => 'meta['.$field[0].']',
  167. );
  168. $form->addTagOpen('div')->addClass('row');
  169. if ($field[2] == 'text') {
  170. $form->addTextInput(
  171. $p['name'],
  172. ($lang[$field[1]] ?: $field[1] . ':')
  173. )->id($p['id'])->addClass($p['class'])->val($value);
  174. } else {
  175. $form->addTextarea($p['name'], $lang[$field[1]])->id($p['id'])
  176. ->val(formText($value))
  177. ->addClass($p['class'])
  178. ->attr('rows', '6')->attr('cols', '50');
  179. }
  180. $form->addTagClose('div');
  181. }
  182. $form->addTagOpen('div')->addClass('buttons');
  183. $form->addButton('mediado[save]', $lang['btn_save'])->attr('type', 'submit')
  184. ->attrs(['accesskey' => 's']);
  185. $form->addTagClose('div');
  186. $form->addTagClose('div');
  187. echo $form->toHTML();
  188. return true;
  189. }
  190. /**
  191. * Convenience function to check if a media file is still in use
  192. *
  193. * @author Michael Klier <chi@chimeric.de>
  194. *
  195. * @param string $id media id
  196. * @return array|bool
  197. */
  198. function media_inuse($id) {
  199. global $conf;
  200. if($conf['refcheck']){
  201. $mediareferences = ft_mediause($id,true);
  202. if(!count($mediareferences)) {
  203. return false;
  204. } else {
  205. return $mediareferences;
  206. }
  207. } else {
  208. return false;
  209. }
  210. }
  211. /**
  212. * Handles media file deletions
  213. *
  214. * If configured, checks for media references before deletion
  215. *
  216. * @author Andreas Gohr <andi@splitbrain.org>
  217. *
  218. * @param string $id media id
  219. * @param int $auth no longer used
  220. * @return int One of: 0,
  221. * DOKU_MEDIA_DELETED,
  222. * DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS,
  223. * DOKU_MEDIA_NOT_AUTH,
  224. * DOKU_MEDIA_INUSE
  225. */
  226. function media_delete($id,$auth){
  227. global $lang;
  228. $auth = auth_quickaclcheck(ltrim(getNS($id).':*', ':'));
  229. if($auth < AUTH_DELETE) return DOKU_MEDIA_NOT_AUTH;
  230. if(media_inuse($id)) return DOKU_MEDIA_INUSE;
  231. $file = mediaFN($id);
  232. // trigger an event - MEDIA_DELETE_FILE
  233. $data = array();
  234. $data['id'] = $id;
  235. $data['name'] = PhpString::basename($file);
  236. $data['path'] = $file;
  237. $data['size'] = (file_exists($file)) ? filesize($file) : 0;
  238. $data['unl'] = false;
  239. $data['del'] = false;
  240. $evt = new Event('MEDIA_DELETE_FILE',$data);
  241. if ($evt->advise_before()) {
  242. $old = @filemtime($file);
  243. if(!file_exists(mediaFN($id, $old)) && file_exists($file)) {
  244. // add old revision to the attic
  245. media_saveOldRevision($id);
  246. }
  247. $data['unl'] = @unlink($file);
  248. if($data['unl']) {
  249. $sizechange = 0 - $data['size'];
  250. addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_DELETE, $lang['deleted'], '', null, $sizechange);
  251. $data['del'] = io_sweepNS($id, 'mediadir');
  252. }
  253. }
  254. $evt->advise_after();
  255. unset($evt);
  256. if($data['unl'] && $data['del']){
  257. return DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS;
  258. }
  259. return $data['unl'] ? DOKU_MEDIA_DELETED : 0;
  260. }
  261. /**
  262. * Handle file uploads via XMLHttpRequest
  263. *
  264. * @param string $ns target namespace
  265. * @param int $auth current auth check result
  266. * @return false|string false on error, id of the new file on success
  267. */
  268. function media_upload_xhr($ns,$auth){
  269. if(!checkSecurityToken()) return false;
  270. global $INPUT;
  271. $id = $INPUT->get->str('qqfile');
  272. list($ext,$mime) = mimetype($id);
  273. $input = fopen("php://input", "r");
  274. if (!($tmp = io_mktmpdir())) return false;
  275. $path = $tmp.'/'.md5($id);
  276. $target = fopen($path, "w");
  277. $realSize = stream_copy_to_stream($input, $target);
  278. fclose($target);
  279. fclose($input);
  280. if ($INPUT->server->has('CONTENT_LENGTH') && ($realSize != $INPUT->server->int('CONTENT_LENGTH'))) {
  281. unlink($path);
  282. return false;
  283. }
  284. $res = media_save(
  285. array('name' => $path,
  286. 'mime' => $mime,
  287. 'ext' => $ext),
  288. $ns.':'.$id,
  289. ($INPUT->get->str('ow') == 'true'),
  290. $auth,
  291. 'copy'
  292. );
  293. unlink($path);
  294. if ($tmp) io_rmdir($tmp, true);
  295. if (is_array($res)) {
  296. msg($res[0], $res[1]);
  297. return false;
  298. }
  299. return $res;
  300. }
  301. /**
  302. * Handles media file uploads
  303. *
  304. * @author Andreas Gohr <andi@splitbrain.org>
  305. * @author Michael Klier <chi@chimeric.de>
  306. *
  307. * @param string $ns target namespace
  308. * @param int $auth current auth check result
  309. * @param bool|array $file $_FILES member, $_FILES['upload'] if false
  310. * @return false|string false on error, id of the new file on success
  311. */
  312. function media_upload($ns,$auth,$file=false){
  313. if(!checkSecurityToken()) return false;
  314. global $lang;
  315. global $INPUT;
  316. // get file and id
  317. $id = $INPUT->post->str('mediaid');
  318. if (!$file) $file = $_FILES['upload'];
  319. if(empty($id)) $id = $file['name'];
  320. // check for errors (messages are done in lib/exe/mediamanager.php)
  321. if($file['error']) return false;
  322. // check extensions
  323. list($fext,$fmime) = mimetype($file['name']);
  324. list($iext,$imime) = mimetype($id);
  325. if($fext && !$iext){
  326. // no extension specified in id - read original one
  327. $id .= '.'.$fext;
  328. $imime = $fmime;
  329. }elseif($fext && $fext != $iext){
  330. // extension was changed, print warning
  331. msg(sprintf($lang['mediaextchange'],$fext,$iext));
  332. }
  333. $res = media_save(array('name' => $file['tmp_name'],
  334. 'mime' => $imime,
  335. 'ext' => $iext), $ns.':'.$id,
  336. $INPUT->post->bool('ow'), $auth, 'copy_uploaded_file');
  337. if (is_array($res)) {
  338. msg($res[0], $res[1]);
  339. return false;
  340. }
  341. return $res;
  342. }
  343. /**
  344. * An alternative to move_uploaded_file that copies
  345. *
  346. * Using copy, makes sure any setgid bits on the media directory are honored
  347. *
  348. * @see move_uploaded_file()
  349. *
  350. * @param string $from
  351. * @param string $to
  352. * @return bool
  353. */
  354. function copy_uploaded_file($from, $to){
  355. if(!is_uploaded_file($from)) return false;
  356. $ok = copy($from, $to);
  357. @unlink($from);
  358. return $ok;
  359. }
  360. /**
  361. * This generates an action event and delegates to _media_upload_action().
  362. * Action plugins are allowed to pre/postprocess the uploaded file.
  363. * (The triggered event is preventable.)
  364. *
  365. * Event data:
  366. * $data[0] fn_tmp: the temporary file name (read from $_FILES)
  367. * $data[1] fn: the file name of the uploaded file
  368. * $data[2] id: the future directory id of the uploaded file
  369. * $data[3] imime: the mimetype of the uploaded file
  370. * $data[4] overwrite: if an existing file is going to be overwritten
  371. * $data[5] move: name of function that performs move/copy/..
  372. *
  373. * @triggers MEDIA_UPLOAD_FINISH
  374. *
  375. * @param array $file
  376. * @param string $id media id
  377. * @param bool $ow overwrite?
  378. * @param int $auth permission level
  379. * @param string $move name of functions that performs move/copy/..
  380. * @return false|array|string
  381. */
  382. function media_save($file, $id, $ow, $auth, $move) {
  383. if($auth < AUTH_UPLOAD) {
  384. return array("You don't have permissions to upload files.", -1);
  385. }
  386. if (!isset($file['mime']) || !isset($file['ext'])) {
  387. list($ext, $mime) = mimetype($id);
  388. if (!isset($file['mime'])) {
  389. $file['mime'] = $mime;
  390. }
  391. if (!isset($file['ext'])) {
  392. $file['ext'] = $ext;
  393. }
  394. }
  395. global $lang, $conf;
  396. // get filename
  397. $id = cleanID($id);
  398. $fn = mediaFN($id);
  399. // get filetype regexp
  400. $types = array_keys(getMimeTypes());
  401. $types = array_map(
  402. function ($q) {
  403. return preg_quote($q, "/");
  404. },
  405. $types
  406. );
  407. $regex = join('|',$types);
  408. // because a temp file was created already
  409. if(!preg_match('/\.('.$regex.')$/i',$fn)) {
  410. return array($lang['uploadwrong'],-1);
  411. }
  412. //check for overwrite
  413. $overwrite = file_exists($fn);
  414. $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
  415. if($overwrite && (!$ow || $auth < $auth_ow)) {
  416. return array($lang['uploadexist'], 0);
  417. }
  418. // check for valid content
  419. $ok = media_contentcheck($file['name'], $file['mime']);
  420. if($ok == -1){
  421. return array(sprintf($lang['uploadbadcontent'],'.' . $file['ext']),-1);
  422. }elseif($ok == -2){
  423. return array($lang['uploadspam'],-1);
  424. }elseif($ok == -3){
  425. return array($lang['uploadxss'],-1);
  426. }
  427. // prepare event data
  428. $data = array();
  429. $data[0] = $file['name'];
  430. $data[1] = $fn;
  431. $data[2] = $id;
  432. $data[3] = $file['mime'];
  433. $data[4] = $overwrite;
  434. $data[5] = $move;
  435. // trigger event
  436. return Event::createAndTrigger('MEDIA_UPLOAD_FINISH', $data, '_media_upload_action', true);
  437. }
  438. /**
  439. * Callback adapter for media_upload_finish() triggered by MEDIA_UPLOAD_FINISH
  440. *
  441. * @author Michael Klier <chi@chimeric.de>
  442. *
  443. * @param array $data event data
  444. * @return false|array|string
  445. */
  446. function _media_upload_action($data) {
  447. // fixme do further sanity tests of given data?
  448. if(is_array($data) && count($data)===6) {
  449. return media_upload_finish($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]);
  450. } else {
  451. return false; //callback error
  452. }
  453. }
  454. /**
  455. * Saves an uploaded media file
  456. *
  457. * @author Andreas Gohr <andi@splitbrain.org>
  458. * @author Michael Klier <chi@chimeric.de>
  459. * @author Kate Arzamastseva <pshns@ukr.net>
  460. *
  461. * @param string $fn_tmp
  462. * @param string $fn
  463. * @param string $id media id
  464. * @param string $imime mime type
  465. * @param bool $overwrite overwrite existing?
  466. * @param string $move function name
  467. * @return array|string
  468. */
  469. function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'move_uploaded_file') {
  470. global $conf;
  471. global $lang;
  472. global $REV;
  473. $old = @filemtime($fn);
  474. if(!file_exists(mediaFN($id, $old)) && file_exists($fn)) {
  475. // add old revision to the attic if missing
  476. media_saveOldRevision($id);
  477. }
  478. // prepare directory
  479. io_createNamespace($id, 'media');
  480. $filesize_old = file_exists($fn) ? filesize($fn) : 0;
  481. if($move($fn_tmp, $fn)) {
  482. @clearstatcache(true,$fn);
  483. $new = @filemtime($fn);
  484. // Set the correct permission here.
  485. // Always chmod media because they may be saved with different permissions than expected from the php umask.
  486. // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
  487. chmod($fn, $conf['fmode']);
  488. msg($lang['uploadsucc'],1);
  489. media_notify($id,$fn,$imime,$old,$new);
  490. // add a log entry to the media changelog
  491. $filesize_new = filesize($fn);
  492. $sizechange = $filesize_new - $filesize_old;
  493. if($REV) {
  494. addMediaLogEntry(
  495. $new,
  496. $id,
  497. DOKU_CHANGE_TYPE_REVERT,
  498. sprintf($lang['restored'], dformat($REV)),
  499. $REV,
  500. null,
  501. $sizechange
  502. );
  503. } elseif($overwrite) {
  504. addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT, '', '', null, $sizechange);
  505. } else {
  506. addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created'], '', null, $sizechange);
  507. }
  508. return $id;
  509. }else{
  510. return array($lang['uploadfail'],-1);
  511. }
  512. }
  513. /**
  514. * Moves the current version of media file to the media_attic
  515. * directory
  516. *
  517. * @author Kate Arzamastseva <pshns@ukr.net>
  518. *
  519. * @param string $id
  520. * @return int - revision date
  521. */
  522. function media_saveOldRevision($id) {
  523. global $conf, $lang;
  524. $oldf = mediaFN($id);
  525. if (!file_exists($oldf)) return '';
  526. $date = filemtime($oldf);
  527. if (!$conf['mediarevisions']) return $date;
  528. $medialog = new MediaChangeLog($id);
  529. if (!$medialog->getRevisionInfo($date)) {
  530. // there was an external edit,
  531. // there is no log entry for current version of file
  532. $sizechange = filesize($oldf);
  533. if(!file_exists(mediaMetaFN($id, '.changes'))) {
  534. addMediaLogEntry($date, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created'], '', null, $sizechange);
  535. } else {
  536. $oldRev = $medialog->getRevisions(-1, 1); // from changelog
  537. $oldRev = (int) (empty($oldRev) ? 0 : $oldRev[0]);
  538. $filesize_old = filesize(mediaFN($id, $oldRev));
  539. $sizechange = $sizechange - $filesize_old;
  540. addMediaLogEntry($date, $id, DOKU_CHANGE_TYPE_EDIT, '', '', null, $sizechange);
  541. }
  542. }
  543. $newf = mediaFN($id, $date);
  544. io_makeFileDir($newf);
  545. if (copy($oldf, $newf)) {
  546. // Set the correct permission here.
  547. // Always chmod media because they may be saved with different permissions than expected from the php umask.
  548. // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
  549. chmod($newf, $conf['fmode']);
  550. }
  551. return $date;
  552. }
  553. /**
  554. * This function checks if the uploaded content is really what the
  555. * mimetype says it is. We also do spam checking for text types here.
  556. *
  557. * We need to do this stuff because we can not rely on the browser
  558. * to do this check correctly. Yes, IE is broken as usual.
  559. *
  560. * @author Andreas Gohr <andi@splitbrain.org>
  561. * @link http://www.splitbrain.org/blog/2007-02/12-internet_explorer_facilitates_cross_site_scripting
  562. * @fixme check all 26 magic IE filetypes here?
  563. *
  564. * @param string $file path to file
  565. * @param string $mime mimetype
  566. * @return int
  567. */
  568. function media_contentcheck($file,$mime){
  569. global $conf;
  570. if($conf['iexssprotect']){
  571. $fh = @fopen($file, 'rb');
  572. if($fh){
  573. $bytes = fread($fh, 256);
  574. fclose($fh);
  575. if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i',$bytes)){
  576. return -3; //XSS: possibly malicious content
  577. }
  578. }
  579. }
  580. if(substr($mime,0,6) == 'image/'){
  581. $info = @getimagesize($file);
  582. if($mime == 'image/gif' && $info[2] != 1){
  583. return -1; // uploaded content did not match the file extension
  584. }elseif($mime == 'image/jpeg' && $info[2] != 2){
  585. return -1;
  586. }elseif($mime == 'image/png' && $info[2] != 3){
  587. return -1;
  588. }
  589. # fixme maybe check other images types as well
  590. }elseif(substr($mime,0,5) == 'text/'){
  591. global $TEXT;
  592. $TEXT = io_readFile($file);
  593. if(checkwordblock()){
  594. return -2; //blocked by the spam blacklist
  595. }
  596. }
  597. return 0;
  598. }
  599. /**
  600. * Send a notify mail on uploads
  601. *
  602. * @author Andreas Gohr <andi@splitbrain.org>
  603. *
  604. * @param string $id media id
  605. * @param string $file path to file
  606. * @param string $mime mime type
  607. * @param bool|int $old_rev revision timestamp or false
  608. */
  609. function media_notify($id,$file,$mime,$old_rev=false,$current_rev=false){
  610. global $conf;
  611. if(empty($conf['notify'])) return; //notify enabled?
  612. $subscription = new MediaSubscriptionSender();
  613. $subscription->sendMediaDiff($conf['notify'], 'uploadmail', $id, $old_rev, $current_rev);
  614. }
  615. /**
  616. * List all files in a given Media namespace
  617. *
  618. * @param string $ns namespace
  619. * @param null|int $auth permission level
  620. * @param string $jump id
  621. * @param bool $fullscreenview
  622. * @param bool|string $sort sorting order, false skips sorting
  623. */
  624. function media_filelist($ns,$auth=null,$jump='',$fullscreenview=false,$sort=false){
  625. global $conf;
  626. global $lang;
  627. $ns = cleanID($ns);
  628. // check auth our self if not given (needed for ajax calls)
  629. if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
  630. if (!$fullscreenview) echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL;
  631. if($auth < AUTH_READ){
  632. // FIXME: print permission warning here instead?
  633. echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
  634. }else{
  635. if (!$fullscreenview) {
  636. media_uploadform($ns, $auth);
  637. media_searchform($ns);
  638. }
  639. $dir = utf8_encodeFN(str_replace(':','/',$ns));
  640. $data = array();
  641. search($data,$conf['mediadir'],'search_mediafiles',
  642. array('showmsg'=>true,'depth'=>1),$dir,1,$sort);
  643. if(!count($data)){
  644. echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
  645. }else {
  646. if ($fullscreenview) {
  647. echo '<ul class="' . _media_get_list_type() . '">';
  648. }
  649. foreach($data as $item){
  650. if (!$fullscreenview) {
  651. //FIXME old call: media_printfile($item,$auth,$jump);
  652. $display = new DisplayRow($item);
  653. $display->scrollIntoView($jump == $item->getID());
  654. $display->show();
  655. } else {
  656. //FIXME old call: media_printfile_thumbs($item,$auth,$jump);
  657. echo '<li>';
  658. $display = new DisplayTile($item);
  659. $display->scrollIntoView($jump == $item->getID());
  660. $display->show();
  661. echo '</li>';
  662. }
  663. }
  664. if ($fullscreenview) echo '</ul>'.NL;
  665. }
  666. }
  667. }
  668. /**
  669. * Prints tabs for files list actions
  670. *
  671. * @author Kate Arzamastseva <pshns@ukr.net>
  672. * @author Adrian Lang <mail@adrianlang.de>
  673. *
  674. * @param string $selected_tab - opened tab
  675. */
  676. function media_tabs_files($selected_tab = ''){
  677. global $lang;
  678. $tabs = array();
  679. foreach(array('files' => 'mediaselect',
  680. 'upload' => 'media_uploadtab',
  681. 'search' => 'media_searchtab') as $tab => $caption) {
  682. $tabs[$tab] = array('href' => media_managerURL(['tab_files' => $tab], '&'),
  683. 'caption' => $lang[$caption]);
  684. }
  685. html_tabs($tabs, $selected_tab);
  686. }
  687. /**
  688. * Prints tabs for files details actions
  689. *
  690. * @author Kate Arzamastseva <pshns@ukr.net>
  691. * @param string $image filename of the current image
  692. * @param string $selected_tab opened tab
  693. */
  694. function media_tabs_details($image, $selected_tab = '') {
  695. global $lang, $conf;
  696. $tabs = array();
  697. $tabs['view'] = array('href' => media_managerURL(['tab_details' => 'view'], '&'),
  698. 'caption' => $lang['media_viewtab']);
  699. list(, $mime) = mimetype($image);
  700. if ($mime == 'image/jpeg' && file_exists(mediaFN($image))) {
  701. $tabs['edit'] = array('href' => media_managerURL(['tab_details' => 'edit'], '&'),
  702. 'caption' => $lang['media_edittab']);
  703. }
  704. if ($conf['mediarevisions']) {
  705. $tabs['history'] = array('href' => media_managerURL(['tab_details' => 'history'], '&'),
  706. 'caption' => $lang['media_historytab']);
  707. }
  708. html_tabs($tabs, $selected_tab);
  709. }
  710. /**
  711. * Prints options for the tab that displays a list of all files
  712. *
  713. * @author Kate Arzamastseva <pshns@ukr.net>
  714. */
  715. function media_tab_files_options() {
  716. global $lang;
  717. global $INPUT;
  718. global $ID;
  719. $form = new Form([
  720. 'method' => 'get',
  721. 'action' => wl($ID),
  722. 'class' => 'options'
  723. ]);
  724. $form->addTagOpen('div')->addClass('no');
  725. $form->setHiddenField('sectok', null);
  726. $media_manager_params = media_managerURL([], '', false, true);
  727. foreach ($media_manager_params as $pKey => $pVal) {
  728. $form->setHiddenField($pKey, $pVal);
  729. }
  730. if ($INPUT->has('q')) {
  731. $form->setHiddenField('q', $INPUT->str('q'));
  732. }
  733. $form->addHTML('<ul>'.NL);
  734. foreach (array('list' => array('listType', array('thumbs', 'rows')),
  735. 'sort' => array('sortBy', array('name', 'date')))
  736. as $group => $content) {
  737. $checked = "_media_get_{$group}_type";
  738. $checked = $checked();
  739. $form->addHTML('<li class="'. $content[0] .'">');
  740. foreach ($content[1] as $option) {
  741. $attrs = array();
  742. if ($checked == $option) {
  743. $attrs['checked'] = 'checked';
  744. }
  745. $radio = $form->addRadioButton(
  746. $group.'_dwmedia',
  747. $lang['media_'.$group.'_'.$option]
  748. )->val($option)->id($content[0].'__'.$option)->addClass($option);
  749. $radio->attrs($attrs);
  750. }
  751. $form->addHTML('</li>'.NL);
  752. }
  753. $form->addHTML('<li>');
  754. $form->addButton('', $lang['btn_apply'])->attr('type', 'submit');
  755. $form->addHTML('</li>'.NL);
  756. $form->addHTML('</ul>'.NL);
  757. $form->addTagClose('div');
  758. print $form->toHTML();
  759. }
  760. /**
  761. * Returns type of sorting for the list of files in media manager
  762. *
  763. * @author Kate Arzamastseva <pshns@ukr.net>
  764. *
  765. * @return string - sort type
  766. */
  767. function _media_get_sort_type() {
  768. return _media_get_display_param('sort', array('default' => 'name', 'date'));
  769. }
  770. /**
  771. * Returns type of listing for the list of files in media manager
  772. *
  773. * @author Kate Arzamastseva <pshns@ukr.net>
  774. *
  775. * @return string - list type
  776. */
  777. function _media_get_list_type() {
  778. return _media_get_display_param('list', array('default' => 'thumbs', 'rows'));
  779. }
  780. /**
  781. * Get display parameters
  782. *
  783. * @param string $param name of parameter
  784. * @param array $values allowed values, where default value has index key 'default'
  785. * @return string the parameter value
  786. */
  787. function _media_get_display_param($param, $values) {
  788. global $INPUT;
  789. if (in_array($INPUT->str($param), $values)) {
  790. // FIXME: Set cookie
  791. return $INPUT->str($param);
  792. } else {
  793. $val = get_doku_pref($param, $values['default']);
  794. if (!in_array($val, $values)) {
  795. $val = $values['default'];
  796. }
  797. return $val;
  798. }
  799. }
  800. /**
  801. * Prints tab that displays a list of all files
  802. *
  803. * @author Kate Arzamastseva <pshns@ukr.net>
  804. *
  805. * @param string $ns
  806. * @param null|int $auth permission level
  807. * @param string $jump item id
  808. */
  809. function media_tab_files($ns,$auth=null,$jump='') {
  810. global $lang;
  811. if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
  812. if($auth < AUTH_READ){
  813. echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
  814. }else{
  815. media_filelist($ns,$auth,$jump,true,_media_get_sort_type());
  816. }
  817. }
  818. /**
  819. * Prints tab that displays uploading form
  820. *
  821. * @author Kate Arzamastseva <pshns@ukr.net>
  822. *
  823. * @param string $ns
  824. * @param null|int $auth permission level
  825. * @param string $jump item id
  826. */
  827. function media_tab_upload($ns,$auth=null,$jump='') {
  828. global $lang;
  829. if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
  830. echo '<div class="upload">'.NL;
  831. if ($auth >= AUTH_UPLOAD) {
  832. echo '<p>' . $lang['mediaupload'] . '</p>';
  833. }
  834. media_uploadform($ns, $auth, true);
  835. echo '</div>'.NL;
  836. }
  837. /**
  838. * Prints tab that displays search form
  839. *
  840. * @author Kate Arzamastseva <pshns@ukr.net>
  841. *
  842. * @param string $ns
  843. * @param null|int $auth permission level
  844. */
  845. function media_tab_search($ns,$auth=null) {
  846. global $INPUT;
  847. $do = $INPUT->str('mediado');
  848. $query = $INPUT->str('q');
  849. echo '<div class="search">'.NL;
  850. media_searchform($ns, $query, true);
  851. if ($do == 'searchlist' || $query) {
  852. media_searchlist($query,$ns,$auth,true,_media_get_sort_type());
  853. }
  854. echo '</div>'.NL;
  855. }
  856. /**
  857. * Prints tab that displays mediafile details
  858. *
  859. * @author Kate Arzamastseva <pshns@ukr.net>
  860. *
  861. * @param string $image media id
  862. * @param string $ns
  863. * @param null|int $auth permission level
  864. * @param string|int $rev revision timestamp or empty string
  865. */
  866. function media_tab_view($image, $ns, $auth=null, $rev='') {
  867. global $lang;
  868. if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
  869. if ($image && $auth >= AUTH_READ) {
  870. $meta = new JpegMeta(mediaFN($image, $rev));
  871. media_preview($image, $auth, $rev, $meta);
  872. media_preview_buttons($image, $auth, $rev);
  873. media_details($image, $auth, $rev, $meta);
  874. } else {
  875. echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
  876. }
  877. }
  878. /**
  879. * Prints tab that displays form for editing mediafile metadata
  880. *
  881. * @author Kate Arzamastseva <pshns@ukr.net>
  882. *
  883. * @param string $image media id
  884. * @param string $ns
  885. * @param null|int $auth permission level
  886. */
  887. function media_tab_edit($image, $ns, $auth=null) {
  888. if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
  889. if ($image) {
  890. list(, $mime) = mimetype($image);
  891. if ($mime == 'image/jpeg') media_metaform($image,$auth);
  892. }
  893. }
  894. /**
  895. * Prints tab that displays mediafile revisions
  896. *
  897. * @author Kate Arzamastseva <pshns@ukr.net>
  898. *
  899. * @param string $image media id
  900. * @param string $ns
  901. * @param null|int $auth permission level
  902. */
  903. function media_tab_history($image, $ns, $auth=null) {
  904. global $lang;
  905. global $INPUT;
  906. if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
  907. $do = $INPUT->str('mediado');
  908. if ($auth >= AUTH_READ && $image) {
  909. if ($do == 'diff'){
  910. (new dokuwiki\Ui\MediaDiff($image))->show(); //media_diff($image, $ns, $auth);
  911. } else {
  912. $first = $INPUT->int('first',-1);
  913. (new dokuwiki\Ui\MediaRevisions($image))->show($first);
  914. }
  915. } else {
  916. echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
  917. }
  918. }
  919. /**
  920. * Prints mediafile details
  921. *
  922. * @param string $image media id
  923. * @param int $auth permission level
  924. * @param int|string $rev revision timestamp or empty string
  925. * @param JpegMeta|bool $meta
  926. *
  927. * @author Kate Arzamastseva <pshns@ukr.net>
  928. */
  929. function media_preview($image, $auth, $rev = '', $meta = false) {
  930. $size = media_image_preview_size($image, $rev, $meta);
  931. if ($size) {
  932. global $lang;
  933. echo '<div class="image">';
  934. $more = array();
  935. if ($rev) {
  936. $more['rev'] = $rev;
  937. } else {
  938. $t = @filemtime(mediaFN($image));
  939. $more['t'] = $t;
  940. }
  941. $more['w'] = $size[0];
  942. $more['h'] = $size[1];
  943. $src = ml($image, $more);
  944. echo '<a href="'.$src.'" target="_blank" title="'.$lang['mediaview'].'">';
  945. echo '<img src="'.$src.'" alt="" style="max-width: '.$size[0].'px;" />';
  946. echo '</a>';
  947. echo '</div>';
  948. }
  949. }
  950. /**
  951. * Prints mediafile action buttons
  952. *
  953. * @author Kate Arzamastseva <pshns@ukr.net>
  954. *
  955. * @param string $image media id
  956. * @param int $auth permission level
  957. * @param int|string $rev revision timestamp, or empty string
  958. */
  959. function media_preview_buttons($image, $auth, $rev = '') {
  960. global $lang, $conf;
  961. echo '<ul class="actions">';
  962. if ($auth >= AUTH_DELETE && !$rev && file_exists(mediaFN($image))) {
  963. // delete button
  964. $form = new Form([
  965. 'id' => 'mediamanager__btn_delete',
  966. 'action' => media_managerURL(['delete' => $image], '&'),
  967. ]);
  968. $form->addTagOpen('div')->addClass('no');
  969. $form->addButton('', $lang['btn_delete'])->attr('type', 'submit');
  970. $form->addTagClose('div');
  971. echo '<li>';
  972. echo $form->toHTML();
  973. echo '</li>';
  974. }
  975. $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
  976. if ($auth >= $auth_ow && !$rev) {
  977. // upload new version button
  978. $form = new Form([
  979. 'id' => 'mediamanager__btn_update',
  980. 'action' => media_managerURL(['image' => $image, 'mediado' => 'update'], '&'),
  981. ]);
  982. $form->addTagOpen('div')->addClass('no');
  983. $form->addButton('', $lang['media_update'])->attr('type', 'submit');
  984. $form->addTagClose('div');
  985. echo '<li>';
  986. echo $form->toHTML();
  987. echo '</li>';
  988. }
  989. if ($auth >= AUTH_UPLOAD && $rev && $conf['mediarevisions'] && file_exists(mediaFN($image, $rev))) {
  990. // restore button
  991. $form = new Form([
  992. 'id' => 'mediamanager__btn_restore',
  993. 'action'=>media_managerURL(['image' => $image], '&'),
  994. ]);
  995. $form->addTagOpen('div')->addClass('no');
  996. $form->setHiddenField('mediado', 'restore');
  997. $form->setHiddenField('rev', $rev);
  998. $form->addButton('', $lang['media_restore'])->attr('type', 'submit');
  999. $form->addTagClose('div');
  1000. echo '<li>';
  1001. echo $form->toHTML();
  1002. echo '</li>';
  1003. }
  1004. echo '</ul>';
  1005. }
  1006. /**
  1007. * Returns image width and height for mediamanager preview panel
  1008. *
  1009. * @author Kate Arzamastseva <pshns@ukr.net>
  1010. * @param string $image
  1011. * @param int|string $rev
  1012. * @param JpegMeta|bool $meta
  1013. * @param int $size
  1014. * @return array
  1015. */
  1016. function media_image_preview_size($image, $rev, $meta = false, $size = 500) {
  1017. if (!preg_match("/\.(jpe?g|gif|png)$/", $image)
  1018. || !file_exists($filename = mediaFN($image, $rev))
  1019. ) return array();
  1020. $info = getimagesize($filename);
  1021. $w = (int) $info[0];
  1022. $h = (int) $info[1];
  1023. if ($meta && ($w > $size || $h > $size)) {
  1024. $ratio = $meta->getResizeRatio($size, $size);
  1025. $w = floor($w * $ratio);
  1026. $h = floor($h * $ratio);
  1027. }
  1028. return array($w, $h);
  1029. }
  1030. /**
  1031. * Returns the requested EXIF/IPTC tag from the image meta
  1032. *
  1033. * @author Kate Arzamastseva <pshns@ukr.net>
  1034. *
  1035. * @param array $tags array with tags, first existing is returned
  1036. * @param JpegMeta $meta
  1037. * @param string $alt alternative value
  1038. * @return string
  1039. */
  1040. function media_getTag($tags, $meta = false, $alt = '') {
  1041. if (!$meta) return $alt;
  1042. $info = $meta->getField($tags);
  1043. if (!$info) return $alt;
  1044. return $info;
  1045. }
  1046. /**
  1047. * Returns mediafile tags
  1048. *
  1049. * @author Kate Arzamastseva <pshns@ukr.net>
  1050. *
  1051. * @param JpegMeta $meta
  1052. * @return array list of tags of the mediafile
  1053. */
  1054. function media_file_tags($meta) {
  1055. // load the field descriptions
  1056. static $fields = null;
  1057. if (is_null($fields)) {
  1058. $config_files = getConfigFiles('mediameta');
  1059. foreach ($config_files as $config_file) {
  1060. if (file_exists($config_file)) include($config_file);
  1061. }
  1062. }
  1063. $tags = array();
  1064. foreach ($fields as $key => $tag) {
  1065. $t = array();
  1066. if (!empty($tag[0])) $t = array($tag[0]);
  1067. if (isset($tag[3]) && is_array($tag[3])) $t = array_merge($t,$tag[3]);
  1068. $value = media_getTag($t, $meta);
  1069. $tags[] = array('tag' => $tag, 'value' => $value);
  1070. }
  1071. return $tags;
  1072. }
  1073. /**
  1074. * Prints mediafile tags
  1075. *
  1076. * @author Kate Arzamastseva <pshns@ukr.net>
  1077. *
  1078. * @param string $image image id
  1079. * @param int $auth permission level
  1080. * @param string|int $rev revision timestamp, or empty string
  1081. * @param bool|JpegMeta $meta image object, or create one if false
  1082. */
  1083. function media_details($image, $auth, $rev='', $meta=false) {
  1084. global $lang;
  1085. if (!$meta) $meta = new JpegMeta(mediaFN($image, $rev));
  1086. $tags = media_file_tags($meta);
  1087. echo '<dl>'.NL;
  1088. foreach($tags as $tag){
  1089. if ($tag['value']) {
  1090. $value = cleanText($tag['value']);
  1091. echo '<dt>'.$lang[$tag['tag'][1]].'</dt><dd>';
  1092. if ($tag['tag'][2] == 'date') echo dformat($value);
  1093. else echo hsc($value);
  1094. echo '</dd>'.NL;
  1095. }
  1096. }
  1097. echo '</dl>'.NL;
  1098. echo '<dl>'.NL;
  1099. echo '<dt>'.$lang['reference'].':</dt>';
  1100. $media_usage = ft_mediause($image,true);
  1101. if(count($media_usage) > 0){
  1102. foreach($media_usage as $path){
  1103. echo '<dd>'.html_wikilink($path).'</dd>';
  1104. }
  1105. }else{
  1106. echo '<dd>'.$lang['nothingfound'].'</dd>';
  1107. }
  1108. echo '</dl>'.NL;
  1109. }
  1110. /**
  1111. * Shows difference between two revisions of file
  1112. *
  1113. * @author Kate Arzamastseva <pshns@ukr.net>
  1114. *
  1115. * @param string $image image id
  1116. * @param string $ns
  1117. * @param int $auth permission level
  1118. * @param bool $fromajax
  1119. *
  1120. * @deprecated 2020-12-31
  1121. */
  1122. function media_diff($image, $ns, $auth, $fromajax = false) {
  1123. dbg_deprecated('see '. MediaDiff::class .'::show()');
  1124. }
  1125. /**
  1126. * Callback for media file diff
  1127. *
  1128. * @param array $data event data
  1129. *
  1130. * @deprecated 2020-12-31
  1131. */
  1132. function _media_file_diff($data) {
  1133. dbg_deprecated('see '. MediaDiff::class .'::show()');
  1134. }
  1135. /**
  1136. * Shows difference between two revisions of image
  1137. *
  1138. * @author Kate Arzamastseva <pshns@ukr.net>
  1139. *
  1140. * @param string $image
  1141. * @param string|int $l_rev revision timestamp, or empty string
  1142. * @param string|int $r_rev revision timestamp, or empty string
  1143. * @param string $ns
  1144. * @param int $auth permission level
  1145. * @param bool $fromajax
  1146. * @deprecated 2020-12-31
  1147. */
  1148. function media_file_diff($image, $l_rev, $r_rev, $ns, $auth, $fromajax) {
  1149. dbg_deprecated('see '. MediaDiff::class .'::showFileDiff()');
  1150. }
  1151. /**
  1152. * Prints two images side by side
  1153. * and slider
  1154. *
  1155. * @author Kate Arzamastseva <pshns@ukr.net>
  1156. *
  1157. * @param string $image image id
  1158. * @param int $l_rev revision timestamp, or empty string
  1159. * @param int $r_rev revision timestamp, or empty string
  1160. * @param array $l_size array with width and height
  1161. * @param array $r_size array with width and height
  1162. * @param string $type
  1163. * @deprecated 2020-12-31
  1164. */
  1165. function media_image_diff($image, $l_rev, $r_rev, $l_size, $r_size, $type) {
  1166. dbg_deprecated('see '. MediaDiff::class .'::showImageDiff()');
  1167. }
  1168. /**
  1169. * Restores an old revision of a media file
  1170. *
  1171. * @param string $image media id
  1172. * @param int $rev revision timestamp or empty string
  1173. * @param int $auth
  1174. * @return string - file's id
  1175. *
  1176. * @author Kate Arzamastseva <pshns@ukr.net>
  1177. */
  1178. function media_restore($image, $rev, $auth){
  1179. global $conf;
  1180. if ($auth < AUTH_UPLOAD || !$conf['mediarevisions']) return false;
  1181. $removed = (!file_exists(mediaFN($image)) && file_exists(mediaMetaFN($image, '.changes')));
  1182. if (!$image || (!file_exists(mediaFN($image)) && !$removed)) return false;
  1183. if (!$rev || !file_exists(mediaFN($image, $rev))) return false;
  1184. list(,$imime,) = mimetype($image);
  1185. $res = media_upload_finish(mediaFN($image, $rev),
  1186. mediaFN($image),
  1187. $image,
  1188. $imime,
  1189. true,
  1190. 'copy');
  1191. if (is_array($res)) {
  1192. msg($res[0], $res[1]);
  1193. return false;
  1194. }
  1195. return $res;
  1196. }
  1197. /**
  1198. * List all files found by the search request
  1199. *
  1200. * @author Tobias Sarnowski <sarnowski@cosmocode.de>
  1201. * @author Andreas Gohr <gohr@cosmocode.de>
  1202. * @author Kate Arzamastseva <pshns@ukr.net>
  1203. * @triggers MEDIA_SEARCH
  1204. *
  1205. * @param string $query
  1206. * @param string $ns
  1207. * @param null|int $auth
  1208. * @param bool $fullscreen
  1209. * @param string $sort
  1210. */
  1211. function media_searchlist($query,$ns,$auth=null,$fullscreen=false,$sort='natural'){
  1212. global $conf;
  1213. global $lang;
  1214. $ns = cleanID($ns);
  1215. $evdata = array(
  1216. 'ns' => $ns,
  1217. 'data' => array(),
  1218. 'query' => $query
  1219. );
  1220. if (!blank($query)) {
  1221. $evt = new Event('MEDIA_SEARCH', $evdata);
  1222. if ($evt->advise_before()) {
  1223. $dir = utf8_encodeFN(str_replace(':','/',$evdata['ns']));
  1224. $quoted = preg_quote($evdata['query'],'/');
  1225. //apply globbing
  1226. $quoted = str_replace(array('\*', '\?'), array('.*', '.'), $quoted, $count);
  1227. //if we use globbing file name must match entirely but may be preceded by arbitrary namespace
  1228. if ($count > 0) $quoted = '^([^:]*:)*'.$quoted.'$';
  1229. $pattern = '/'.$quoted.'/i';
  1230. search($evdata['data'],
  1231. $conf['mediadir'],
  1232. 'search_mediafiles',
  1233. array('showmsg'=>false,'pattern'=>$pattern),
  1234. $dir,
  1235. 1,
  1236. $sort);
  1237. }
  1238. $evt->advise_after();
  1239. unset($evt);
  1240. }
  1241. if (!$fullscreen) {
  1242. echo '<h1 id="media__ns">'.sprintf($lang['searchmedia_in'],hsc($ns).':*').'</h1>'.NL;
  1243. media_searchform($ns,$query);
  1244. }
  1245. if(!count($evdata['data'])){
  1246. echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
  1247. }else {
  1248. if ($fullscreen) {
  1249. echo '<ul class="' . _media_get_list_type() . '">';
  1250. }
  1251. foreach($evdata['data'] as $item){
  1252. if (!$fullscreen) {
  1253. // FIXME old call: media_printfile($item,$item['perm'],'',true);
  1254. $display = new DisplayRow($item);
  1255. $display->relativeDisplay($ns);
  1256. $display->show();
  1257. } else {
  1258. // FIXME old call: media_printfile_thumbs($item,$item['perm'],false,true);
  1259. $display = new DisplayTile($item);
  1260. $display->relativeDisplay($ns);
  1261. echo '<li>';
  1262. $display->show();
  1263. echo '</li>';
  1264. }
  1265. }
  1266. if ($fullscreen) echo '</ul>'.NL;
  1267. }
  1268. }
  1269. /**
  1270. * Display a media icon
  1271. *
  1272. * @param string $filename media id
  1273. * @param string $size the size subfolder, if not specified 16x16 is used
  1274. * @return string html
  1275. */
  1276. function media_printicon($filename, $size=''){
  1277. list($ext) = mimetype(mediaFN($filename),false);
  1278. if (file_exists(DOKU_INC.'lib/images/fileicons/'.$size.'/'.$ext.'.png')) {
  1279. $icon = DOKU_BASE.'lib/images/fileicons/'.$size.'/'.$ext.'.png';
  1280. } else {
  1281. $icon = DOKU_BASE.'lib/images/fileicons/'.$size.'/file.png';
  1282. }
  1283. return '<img src="'.$icon.'" alt="'.$filename.'" class="icon" />';
  1284. }
  1285. /**
  1286. * Build link based on the current, adding/rewriting parameters
  1287. *
  1288. * @author Kate Arzamastseva <pshns@ukr.net>
  1289. *
  1290. * @param array|bool $params
  1291. * @param string $amp separator
  1292. * @param bool $abs absolute url?
  1293. * @param bool $params_array return the parmeters array?
  1294. * @return string|array - link or link parameters
  1295. */
  1296. function media_managerURL($params = false, $amp = '&amp;', $abs = false, $params_array = false) {
  1297. global $ID;
  1298. global $INPUT;
  1299. $gets = array('do' => 'media');
  1300. $media_manager_params = array('tab_files', 'tab_details', 'image', 'ns', 'list', 'sort');
  1301. foreach ($media_manager_params as $x) {
  1302. if ($INPUT->has($x)) $gets[$x] = $INPUT->str($x);
  1303. }
  1304. if ($params) {
  1305. $gets = $params + $gets;
  1306. }
  1307. unset($gets['id']);
  1308. if (isset($gets['delete'])) {
  1309. unset($gets['image']);
  1310. unset($gets['tab_details']);
  1311. }
  1312. if ($params_array) return $gets;
  1313. return wl($ID,$gets,$abs,$amp);
  1314. }
  1315. /**
  1316. * Print the media upload form if permissions are correct
  1317. *
  1318. * @author Andreas Gohr <andi@splitbrain.org>
  1319. * @author Kate Arzamastseva <pshns@ukr.net>
  1320. *
  1321. * @param string $ns
  1322. * @param int $auth permission level
  1323. * @param bool $fullscreen
  1324. */
  1325. function media_uploadform($ns, $auth, $fullscreen = false) {
  1326. global $lang;
  1327. global $conf;
  1328. global $INPUT;
  1329. if ($auth < AUTH_UPLOAD) {
  1330. echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL;
  1331. return;
  1332. }
  1333. $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
  1334. $update = false;
  1335. $id = '';
  1336. if ($auth >= $auth_ow && $fullscreen && $INPUT->str('mediado') == 'update') {
  1337. $update = true;
  1338. $id = cleanID($INPUT->str('image'));
  1339. }
  1340. // The default HTML upload form
  1341. $form = new Form([
  1342. 'id' => 'dw__upload',
  1343. 'enctype' => 'multipart/form-data',
  1344. 'action' => ($fullscreen)
  1345. ? media_managerURL(['tab_files' => 'files', 'tab_details' => 'view'], '&')
  1346. : DOKU_BASE.'lib/exe/mediamanager.php',
  1347. ]);
  1348. $form->addTagOpen('div')->addClass('no');
  1349. $form->setHiddenField('ns', hsc($ns)); // FIXME hsc required?
  1350. $form->addTagOpen('p');
  1351. $form->addTextInput('upload', $lang['txt_upload'])->id('upload__file')
  1352. ->attrs(['type' => 'file']);
  1353. $form->addTagClose('p');
  1354. $form->addTagOpen('p');
  1355. $form->addTextInput('mediaid', $lang['txt_filename'])->id('upload__name')
  1356. ->val(noNS($id));
  1357. $form->addButton('', $lang['btn_upload'])->attr('type', 'submit');
  1358. $form->addTagClose('p');
  1359. if ($auth >= $auth_ow){
  1360. $form->addTagOpen('p');
  1361. $attrs = array();
  1362. if ($update) $attrs['checked'] = 'checked';
  1363. $form->addCheckbox('ow', $lang['txt_overwrt'])->id('dw__ow')->val('1')
  1364. ->addClass('check')->attrs($attrs);
  1365. $form->addTagClose('p');
  1366. }
  1367. $form->addTagClose('div');
  1368. if (!$fullscreen) {
  1369. echo '<div class="upload">'. $lang['mediaupload'] .'</div>'.DOKU_LF;
  1370. } else {
  1371. echo DOKU_LF;
  1372. }
  1373. echo '<div id="mediamanager__uploader">'.DOKU_LF;
  1374. echo $form->toHTML('Upload');
  1375. echo '</div>'.DOKU_LF;
  1376. echo '<p class="maxsize">';
  1377. printf($lang['maxuploadsize'], filesize_h(media_getuploadsize()));
  1378. echo ' <a class="allowedmime" href="#">'. $lang['allowedmime'] .'</a>';
  1379. echo ' <span>'. implode(', ', array_keys(getMimeTypes())) .'</span>';
  1380. echo '</p>'.DOKU_LF;
  1381. }
  1382. /**
  1383. * Returns the size uploaded files may have
  1384. *
  1385. * This uses a conservative approach using the lowest number found
  1386. * in any of the limiting ini settings
  1387. *
  1388. * @returns int size in bytes
  1389. */
  1390. function media_getuploadsize(){
  1391. $okay = 0;
  1392. $post = (int) php_to_byte(@ini_get('post_max_size'));
  1393. $suho = (int) php_to_byte(@ini_get('suhosin.post.max_value_length'));
  1394. $upld = (int) php_to_byte(@ini_get('upload_max_filesize'));
  1395. if($post && ($post < $okay || $okay == 0)) $okay = $post;
  1396. if($suho && ($suho < $okay || $okay == 0)) $okay = $suho;
  1397. if($upld && ($upld < $okay || $okay == 0)) $okay = $upld;
  1398. return $okay;
  1399. }
  1400. /**
  1401. * Print the search field form
  1402. *
  1403. * @author Tobias Sarnowski <sarnowski@cosmocode.de>
  1404. * @author Kate Arzamastseva <pshns@ukr.net>
  1405. *
  1406. * @param string $ns
  1407. * @param string $query
  1408. * @param bool $fullscreen
  1409. */
  1410. function media_searchform($ns, $query = '', $fullscreen = false) {
  1411. global $lang;
  1412. // The default HTML search form
  1413. $form = new Form([
  1414. 'id' => 'dw__mediasearch',
  1415. 'action' => ($fullscreen)
  1416. ? media_managerURL([], '&')
  1417. : DOKU_BASE.'lib/exe/mediamanager.php',
  1418. ]);
  1419. $form->addTagOpen('div')->addClass('no');
  1420. $form->setHiddenField('ns', $ns);
  1421. $form->setHiddenField($fullscreen ? 'mediado' : 'do', 'searchlist');
  1422. $form->addTagOpen('p');
  1423. $form->addTextInput('q', $lang['searchmedia'])
  1424. ->attr('title', sprintf($lang['searchmedia_in'], hsc($ns) .':*'))
  1425. ->val($query);
  1426. $form->addHTML(' ');
  1427. $form->addButton('', $lang['btn_search'])->attr('type', 'submit');
  1428. $form->addTagClose('p');
  1429. $form->addTagClose('div');
  1430. print $form->toHTML('SearchMedia');
  1431. }
  1432. /**
  1433. * Build a tree outline of available media namespaces
  1434. *
  1435. * @author Andreas Gohr <andi@splitbrain.org>
  1436. *
  1437. * @param string $ns
  1438. */
  1439. function media_nstree($ns){
  1440. global $conf;
  1441. global $lang;
  1442. // currently selected namespace
  1443. $ns = cleanID($ns);
  1444. if(empty($ns)){
  1445. global $ID;
  1446. $ns = (string)getNS($ID);
  1447. }
  1448. $ns_dir = utf8_encodeFN(str_replace(':','/',$ns));
  1449. $data = array();
  1450. search($data,$conf['mediadir'],'search_index',array('ns' => $ns_dir, 'nofiles' => true));
  1451. // wrap a list with the root level around the other namespaces
  1452. array_unshift($data, array('level' => 0, 'id' => '', 'open' =>'true',
  1453. 'label' => '['.$lang['mediaroot'].']'));
  1454. // insert the current ns into the hierarchy if it isn't already part of it
  1455. $ns_parts = explode(':', $ns);
  1456. $tmp_ns = '';
  1457. $pos = 0;
  1458. foreach ($ns_parts as $level => $part) {
  1459. if ($tmp_ns) $tmp_ns .= ':'.$part;
  1460. else $tmp_ns = $part;
  1461. // find the namespace parts or insert them
  1462. while ($data[$pos]['id'] != $tmp_ns) {
  1463. if (
  1464. $pos >= count($data) ||
  1465. ($data[$pos]['level'] <= $level+1 && Sort::strcmp($data[$pos]['id'], $tmp_ns) > 0)
  1466. ) {
  1467. array_splice($data, $pos, 0, array(array('level' => $level+1, 'id' => $tmp_ns, 'open' => 'true')));
  1468. break;
  1469. }
  1470. ++$pos;
  1471. }
  1472. }
  1473. echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
  1474. }
  1475. /**
  1476. * Userfunction for html_buildlist
  1477. *
  1478. * Prints a media namespace tree item
  1479. *
  1480. * @author Andreas Gohr <andi@splitbrain.org>
  1481. *
  1482. * @param array $item
  1483. * @return string html
  1484. */
  1485. function media_nstree_item($item){
  1486. global $INPUT;
  1487. $pos = strrpos($item['id'], ':');
  1488. $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
  1489. if(empty($item['label'])) $item['label'] = $label;
  1490. $ret = '';
  1491. if (!($INPUT->str('do') == 'media'))
  1492. $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
  1493. else $ret .= '<a href="'.media_managerURL(['ns' => idfilter($item['id'], false), 'tab_files' => 'files'])
  1494. .'" class="idx_dir">';
  1495. $ret .= $item['label'];
  1496. $ret .= '</a>';
  1497. return $ret;
  1498. }
  1499. /**
  1500. * Userfunction for html_buildlist
  1501. *
  1502. * Prints a media namespace tree item opener
  1503. *
  1504. * @author Andreas Gohr <andi@splitbrain.org>
  1505. *
  1506. * @param array $item
  1507. * @return string html
  1508. */
  1509. function media_nstree_li($item){
  1510. $class='media level'.$item['level'];
  1511. if($item['open']){
  1512. $class .= ' open';
  1513. $img = DOKU_BASE.'lib/images/minus.gif';
  1514. $alt = '−';
  1515. }else{
  1516. $class .= ' closed';
  1517. $img = DOKU_BASE.'lib/images/plus.gif';
  1518. $alt = '+';
  1519. }
  1520. // TODO: only deliver an image if it actually has a subtree...
  1521. return '<li class="'.$class.'">'.
  1522. '<img src="'.$img.'" alt="'.$alt.'" />';
  1523. }
  1524. /**
  1525. * Resizes or crop the given image to the given size
  1526. *
  1527. * @author Andreas Gohr <andi@splitbrain.org>
  1528. *
  1529. * @param string $file filename, path to file
  1530. * @param string $ext extension
  1531. * @param int $w desired width
  1532. * @param int $h desired height
  1533. * @param bool $crop should a center crop be used?
  1534. * @return string path to resized or original size if failed
  1535. */
  1536. function media_mod_image($file, $ext, $w, $h=0, $crop=false)
  1537. {
  1538. global $conf;
  1539. if(!$h) $h = 0;
  1540. // we wont scale up to infinity
  1541. if($w > 2000 || $h > 2000) return $file;
  1542. $operation = $crop ? 'crop' : 'resize';
  1543. $options = [
  1544. 'quality' => $conf['jpg_quality'],
  1545. 'imconvert' => $conf['im_convert'],
  1546. ];
  1547. $cache = new \dokuwiki\Cache\CacheImageMod($file, $w, $h, $ext, $crop);
  1548. if(!$cache->useCache()) {
  1549. try {
  1550. Slika::run($file, $options)
  1551. ->autorotate()
  1552. ->$operation($w, $h)
  1553. ->save($cache->cache, $ext);
  1554. if($conf['fperm']) @chmod($cache->cache, $conf['fperm']);
  1555. } catch (\splitbrain\slika\Exception $e) {
  1556. Logger::debug($e->getMessage());
  1557. return $file;
  1558. }
  1559. }
  1560. return $cache->cache;
  1561. }
  1562. /**
  1563. * Resizes the given image to the given size
  1564. *
  1565. * @author Andreas Gohr <andi@splitbrain.org>
  1566. *
  1567. * @param string $file filename, path to file
  1568. * @param string $ext extension
  1569. * @param int $w desired width
  1570. * @param int $h desired height
  1571. * @return string path to resized or original size if failed
  1572. */
  1573. function media_resize_image($file, $ext, $w, $h = 0)
  1574. {
  1575. return media_mod_image($file, $ext, $w, $h, false);
  1576. }
  1577. /**
  1578. * Center crops the given image to the wanted size
  1579. *
  1580. * @author Andreas Gohr <andi@splitbrain.org>
  1581. *
  1582. * @param string $file filename, path to file
  1583. * @param string $ext extension
  1584. * @param int $w desired width
  1585. * @param int $h desired height
  1586. * @return string path to resized or original size if failed
  1587. */
  1588. function media_crop_image($file, $ext, $w, $h = 0)
  1589. {
  1590. return media_mod_image($file, $ext, $w, $h, true);
  1591. }
  1592. /**
  1593. * Calculate a token to be used to verify fetch requests for resized or
  1594. * cropped images have been internally generated - and prevent external
  1595. * DDOS attacks via fetch
  1596. *
  1597. * @author Christopher Smith <chris@jalakai.co.uk>
  1598. *
  1599. * @param string $id id of the image
  1600. * @param int $w resize/crop width
  1601. * @param int $h resize/crop height
  1602. * @return string token or empty string if no token required
  1603. */
  1604. function media_get_token($id,$w,$h){
  1605. // token is only required for modified images
  1606. if ($w || $h || media_isexternal($id)) {
  1607. $token = $id;
  1608. if ($w) $token .= '.'.$w;
  1609. if ($h) $token .= '.'.$h;
  1610. return substr(\dokuwiki\PassHash::hmac('md5', $token, auth_cookiesalt()),0,6);
  1611. }
  1612. return '';
  1613. }
  1614. /**
  1615. * Download a remote file and return local filename
  1616. *
  1617. * returns false if download fails. Uses cached file if available and
  1618. * wanted
  1619. *
  1620. * @author Andreas Gohr <andi@splitbrain.org>
  1621. * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
  1622. *
  1623. * @param string $url
  1624. * @param string $ext extension
  1625. * @param int $cache cachetime in seconds
  1626. * @return false|string path to cached file
  1627. */
  1628. function media_get_from_URL($url,$ext,$cache){
  1629. global $conf;
  1630. // if no cache or fetchsize just redirect
  1631. if ($cache==0) return false;
  1632. if (!$conf['fetchsize']) return false;
  1633. $local = getCacheName(strtolower($url),".media.$ext");
  1634. $mtime = @filemtime($local); // 0 if not exists
  1635. //decide if download needed:
  1636. if(($mtime == 0) || // cache does not exist
  1637. ($cache != -1 && $mtime < time() - $cache) // 'recache' and cache has expired
  1638. ) {
  1639. if(media_image_download($url, $local)) {
  1640. return $local;
  1641. } else {
  1642. return false;
  1643. }
  1644. }
  1645. //if cache exists use it else
  1646. if($mtime) return $local;
  1647. //else return false
  1648. return false;
  1649. }
  1650. /**
  1651. * Download image files
  1652. *
  1653. * @author Andreas Gohr <andi@splitbrain.org>
  1654. *
  1655. * @param string $url
  1656. * @param string $file path to file in which to put the downloaded content
  1657. * @return bool
  1658. */
  1659. function media_image_download($url,$file){
  1660. global $conf;
  1661. $http = new DokuHTTPClient();
  1662. $http->keep_alive = false; // we do single ops here, no need for keep-alive
  1663. $http->max_bodysize = $conf['fetchsize'];
  1664. $http->timeout = 25; //max. 25 sec
  1665. $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
  1666. $data = $http->get($url);
  1667. if(!$data) return false;
  1668. $fileexists = file_exists($file);
  1669. $fp = @fopen($file,"w");
  1670. if(!$fp) return false;
  1671. fwrite($fp,$data);
  1672. fclose($fp);
  1673. if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
  1674. // check if it is really an image
  1675. $info = @getimagesize($file);
  1676. if(!$info){
  1677. @unlink($file);
  1678. return false;
  1679. }
  1680. return true;
  1681. }
  1682. /**
  1683. * resize images using external ImageMagick convert program
  1684. *
  1685. * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
  1686. * @author Andreas Gohr <andi@splitbrain.org>
  1687. *
  1688. * @param string $ext extension
  1689. * @param string $from filename path to file
  1690. * @param int $from_w original width
  1691. * @param int $from_h original height
  1692. * @param string $to path to resized file
  1693. * @param int $to_w desired width
  1694. * @param int $to_h desired height
  1695. * @return bool
  1696. */
  1697. function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
  1698. global $conf;
  1699. // check if convert is configured
  1700. if(!$conf['im_convert']) return false;
  1701. // prepare command
  1702. $cmd = $conf['im_convert'];
  1703. $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
  1704. if ($ext == 'jpg' || $ext == 'jpeg') {
  1705. $cmd .= ' -quality '.$conf['jpg_quality'];
  1706. }
  1707. $cmd .= " $from $to";
  1708. @exec($cmd,$out,$retval);
  1709. if ($retval == 0) return true;
  1710. return false;
  1711. }
  1712. /**
  1713. * crop images using external ImageMagick convert program
  1714. *
  1715. * @author Andreas Gohr <andi@splitbrain.org>
  1716. *
  1717. * @param string $ext extension
  1718. * @param string $from filename path to file
  1719. * @param int $from_w original width
  1720. * @param int $from_h original height
  1721. * @param string $to path to resized file
  1722. * @param int $to_w desired width
  1723. * @param int $to_h desired height
  1724. * @param int $ofs_x offset of crop centre
  1725. * @param int $ofs_y offset of crop centre
  1726. * @return bool
  1727. * @deprecated 2020-09-01
  1728. */
  1729. function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
  1730. global $conf;
  1731. dbg_deprecated('splitbrain\\Slika');
  1732. // check if convert is configured
  1733. if(!$conf['im_convert']) return false;
  1734. // prepare command
  1735. $cmd = $conf['im_convert'];
  1736. $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
  1737. if ($ext == 'jpg' || $ext == 'jpeg') {
  1738. $cmd .= ' -quality '.$conf['jpg_quality'];
  1739. }
  1740. $cmd .= " $from $to";
  1741. @exec($cmd,$out,$retval);
  1742. if ($retval == 0) return true;
  1743. return false;
  1744. }
  1745. /**
  1746. * resize or crop images using PHP's libGD support
  1747. *
  1748. * @author Andreas Gohr <andi@splitbrain.org>
  1749. * @author Sebastian Wienecke <s_wienecke@web.de>
  1750. *
  1751. * @param string $ext extension
  1752. * @param string $from filename path to file
  1753. * @param int $from_w original width
  1754. * @param int $from_h original height
  1755. * @param string $to path to resized file
  1756. * @param int $to_w desired width
  1757. * @param int $to_h desired height
  1758. * @param int $ofs_x offset of crop centre
  1759. * @param int $ofs_y offset of crop centre
  1760. * @return bool
  1761. * @deprecated 2020-09-01
  1762. */
  1763. function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
  1764. global $conf;
  1765. dbg_deprecated('splitbrain\\Slika');
  1766. if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
  1767. // check available memory
  1768. if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
  1769. return false;
  1770. }
  1771. // create an image of the given filetype
  1772. $image = false;
  1773. if ($ext == 'jpg' || $ext == 'jpeg'){
  1774. if(!function_exists("imagecreatefromjpeg")) return false;
  1775. $image = @imagecreatefromjpeg($from);
  1776. }elseif($ext == 'png') {
  1777. if(!function_exists("imagecreatefrompng")) return false;
  1778. $image = @imagecreatefrompng($from);
  1779. }elseif($ext == 'gif') {
  1780. if(!function_exists("imagecreatefromgif")) return false;
  1781. $image = @imagecreatefromgif($from);
  1782. }
  1783. if(!$image) return false;
  1784. $newimg = false;
  1785. if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
  1786. $newimg = @imagecreatetruecolor ($to_w, $to_h);
  1787. }
  1788. if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
  1789. if(!$newimg){
  1790. imagedestroy($image);
  1791. return false;
  1792. }
  1793. //keep png alpha channel if possible
  1794. if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
  1795. imagealphablending($newimg, false);
  1796. imagesavealpha($newimg,true);
  1797. }
  1798. //keep gif transparent color if possible
  1799. if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
  1800. if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
  1801. $transcolorindex = @imagecolortransparent($image);
  1802. if($transcolorindex >= 0 ) { //transparent color exists
  1803. $transcolor = @imagecolorsforindex($image, $transcolorindex);
  1804. $transcolorindex = @imagecolorallocate(
  1805. $newimg,
  1806. $transcolor['red'],
  1807. $transcolor['green'],
  1808. $transcolor['blue']
  1809. );
  1810. @imagefill($newimg, 0, 0, $transcolorindex);
  1811. @imagecolortransparent($newimg, $transcolorindex);
  1812. }else{ //filling with white
  1813. $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
  1814. @imagefill($newimg, 0, 0, $whitecolorindex);
  1815. }
  1816. }else{ //filling with white
  1817. $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
  1818. @imagefill($newimg, 0, 0, $whitecolorindex);
  1819. }
  1820. }
  1821. //try resampling first
  1822. if(function_exists("imagecopyresampled")){
  1823. if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
  1824. imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
  1825. }
  1826. }else{
  1827. imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
  1828. }
  1829. $okay = false;
  1830. if ($ext == 'jpg' || $ext == 'jpeg'){
  1831. if(!function_exists('imagejpeg')){
  1832. $okay = false;
  1833. }else{
  1834. $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
  1835. }
  1836. }elseif($ext == 'png') {
  1837. if(!function_exists('imagepng')){
  1838. $okay = false;
  1839. }else{
  1840. $okay = imagepng($newimg, $to);
  1841. }
  1842. }elseif($ext == 'gif') {
  1843. if(!function_exists('imagegif')){
  1844. $okay = false;
  1845. }else{
  1846. $okay = imagegif($newimg, $to);
  1847. }
  1848. }
  1849. // destroy GD image resources
  1850. imagedestroy($image);
  1851. imagedestroy($newimg);
  1852. return $okay;
  1853. }
  1854. /**
  1855. * Return other media files with the same base name
  1856. * but different extensions.
  1857. *
  1858. * @param string $src - ID of media file
  1859. * @param string[] $exts - alternative extensions to find other files for
  1860. * @return array - array(mime type => file ID)
  1861. *
  1862. * @author Anika Henke <anika@selfthinker.org>
  1863. */
  1864. function media_alternativefiles($src, $exts){
  1865. $files = array();
  1866. list($srcExt, /* $srcMime */) = mimetype($src);
  1867. $filebase = substr($src, 0, -1 * (strlen($srcExt)+1));
  1868. foreach($exts as $ext) {
  1869. $fileid = $filebase.'.'.$ext;
  1870. $file = mediaFN($fileid);
  1871. if(file_exists($file)) {
  1872. list(/* $fileExt */, $fileMime) = mimetype($file);
  1873. $files[$fileMime] = $fileid;
  1874. }
  1875. }
  1876. return $files;
  1877. }
  1878. /**
  1879. * Check if video/audio is supported to be embedded.
  1880. *
  1881. * @param string $mime - mimetype of media file
  1882. * @param string $type - type of media files to check ('video', 'audio', or null for all)
  1883. * @return boolean
  1884. *
  1885. * @author Anika Henke <anika@selfthinker.org>
  1886. */
  1887. function media_supportedav($mime, $type=NULL){
  1888. $supportedAudio = array(
  1889. 'ogg' => 'audio/ogg',
  1890. 'mp3' => 'audio/mpeg',
  1891. 'wav' => 'audio/wav',
  1892. );
  1893. $supportedVideo = array(
  1894. 'webm' => 'video/webm',
  1895. 'ogv' => 'video/ogg',
  1896. 'mp4' => 'video/mp4',
  1897. );
  1898. if ($type == 'audio') {
  1899. $supportedAv = $supportedAudio;
  1900. } elseif ($type == 'video') {
  1901. $supportedAv = $supportedVideo;
  1902. } else {
  1903. $supportedAv = array_merge($supportedAudio, $supportedVideo);
  1904. }
  1905. return in_array($mime, $supportedAv);
  1906. }
  1907. /**
  1908. * Return track media files with the same base name
  1909. * but extensions that indicate kind and lang.
  1910. * ie for foo.webm search foo.sub.lang.vtt, foo.cap.lang.vtt...
  1911. *
  1912. * @param string $src - ID of media file
  1913. * @return array - array(mediaID => array( kind, srclang ))
  1914. *
  1915. * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
  1916. */
  1917. function media_trackfiles($src){
  1918. $kinds=array(
  1919. 'sub' => 'subtitles',
  1920. 'cap' => 'captions',
  1921. 'des' => 'descriptions',
  1922. 'cha' => 'chapters',
  1923. 'met' => 'metadata'
  1924. );
  1925. $files = array();
  1926. $re='/\\.(sub|cap|des|cha|met)\\.([^.]+)\\.vtt$/';
  1927. $baseid=pathinfo($src, PATHINFO_FILENAME);
  1928. $pattern=mediaFN($baseid).'.*.*.vtt';
  1929. $list=glob($pattern);
  1930. foreach($list as $track) {
  1931. if(preg_match($re, $track, $matches)){
  1932. $files[$baseid.'.'.$matches[1].'.'.$matches[2].'.vtt']=array(
  1933. $kinds[$matches[1]],
  1934. $matches[2],
  1935. );
  1936. }
  1937. }
  1938. return $files;
  1939. }
  1940. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */