Subversion Repositories oidplus

Rev

Rev 1266 | Rev 1279 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
  6.  *
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *     http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  */
  19.  
  20. namespace ViaThinkSoft\OIDplus;
  21.  
  22. // phpcs:disable PSR1.Files.SideEffects
  23. \defined('INSIDE_OIDPLUS') or die;
  24. // phpcs:enable PSR1.Files.SideEffects
  25.  
  26. class OIDplusPagePublicAttachments extends OIDplusPagePluginPublic
  27.         implements INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_2, /* modifyContent */
  28.                    INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3, /* beforeObject*, afterObject* */
  29.                    INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_4, /* whois*Attributes */
  30.                    INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_8  /* getNotifications */
  31. {
  32.  
  33.         /**
  34.          * @param string $dir
  35.          * @return void
  36.          * @throws OIDplusException
  37.          */
  38.         private static function checkUploadDir(string $dir) {
  39.                 if (!is_dir($dir)) {
  40.                         throw new OIDplusException(_L('The attachment directory "%1" is not existing.', $dir));
  41.                 }
  42.  
  43.                 $realdir = realpath($dir);
  44.                 if ($realdir === false) {
  45.                         throw new OIDplusException(_L('The attachment directory "%1" cannot be resolved (realpath).', $dir));
  46.                 }
  47.  
  48.                 // Check for critical directories
  49.                 if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
  50.                         if (self::isCriticalLinuxDirectory($realdir)) {
  51.                                 throw new OIDplusException(_L('The attachment directory must not be inside a critical system directory!'));
  52.                         }
  53.                 } else {
  54.                         if (self::isCriticalWindowsDirectory($realdir)) {
  55.                                 throw new OIDplusException(_L('The attachment directory must not be inside a critical system directory!'));
  56.                         }
  57.                 }
  58.         }
  59.  
  60.         /**
  61.          * @param string $dir
  62.          * @return bool
  63.          */
  64.         private static function isCriticalWindowsDirectory(string $dir): bool {
  65.                 $dir = rtrim(str_replace('/', '\\', $dir),'\\').'\\';
  66.                 $windir = isset($_SERVER['SystemRoot']) ? rtrim($_SERVER['SystemRoot'],'\\').'\\' : 'C:\\Windows\\';
  67.                 if (stripos($dir,$windir) === 0) return true;
  68.                 return false;
  69.         }
  70.  
  71.         /**
  72.          * @param string $dir
  73.          * @return bool
  74.          */
  75.         private static function isCriticalLinuxDirectory(string $dir): bool {
  76.                 if ($dir == '/') return true;
  77.                 $dir = rtrim($dir,'/').'/';
  78.                 if (strpos($dir,'/bin/') === 0) return true;
  79.                 if (strpos($dir,'/boot/') === 0) return true;
  80.                 if (strpos($dir,'/dev/') === 0) return true;
  81.                 if (strpos($dir,'/etc/') === 0) return true;
  82.                 if (strpos($dir,'/lib') === 0) return true;
  83.                 if (strpos($dir,'/opt/') === 0) return true;
  84.                 if (strpos($dir,'/proc/') === 0) return true;
  85.                 if (strpos($dir,'/root/') === 0) return true;
  86.                 if (strpos($dir,'/run/') === 0) return true;
  87.                 if (strpos($dir,'/sbin/') === 0) return true;
  88.                 if (strpos($dir,'/sys/') === 0) return true;
  89.                 if (strpos($dir,'/tmp/') === 0) return true;
  90.                 if (strpos($dir,'/usr/bin/') === 0) return true;
  91.                 if (strpos($dir,'/usr/include/') === 0) return true;
  92.                 if (strpos($dir,'/usr/lib') === 0) return true;
  93.                 if (strpos($dir,'/usr/sbin/') === 0) return true;
  94.                 if (strpos($dir,'/usr/src/') === 0) return true;
  95.                 if (strpos($dir,'/var/cache/') === 0) return true;
  96.                 if (strpos($dir,'/var/lib') === 0) return true;
  97.                 if (strpos($dir,'/var/lock/') === 0) return true;
  98.                 if (strpos($dir,'/var/log/') === 0) return true;
  99.                 if (strpos($dir,'/var/mail/') === 0) return true;
  100.                 if (strpos($dir,'/var/opt/') === 0) return true;
  101.                 if (strpos($dir,'/var/run/') === 0) return true;
  102.                 if (strpos($dir,'/var/spool/') === 0) return true;
  103.                 if (strpos($dir,'/var/tmp/') === 0) return true;
  104.                 return false;
  105.         }
  106.  
  107.         /**
  108.          * @return string
  109.          * @throws OIDplusException
  110.          */
  111.         protected static function getUploadBaseDir(): string {
  112.                 // Get base path
  113.                 $cfg = OIDplus::config()->getValue('attachment_upload_dir', '');
  114.                 $cfg = trim($cfg);
  115.                 if ($cfg === '') {
  116.                         $basepath = OIDplus::localpath() . 'userdata' . DIRECTORY_SEPARATOR . 'attachments';
  117.                 } else {
  118.                         $basepath = $cfg;
  119.                 }
  120.                 return $basepath;
  121.         }
  122.  
  123.         /**
  124.          * @param string|null $id
  125.          * @return string
  126.          * @throws OIDplusException
  127.          */
  128.         public static function getUploadDir(string $id=null): string {
  129.                 $basepath = self::getUploadBaseDir();
  130.  
  131.                 try {
  132.                         self::checkUploadDir($basepath);
  133.                 } catch (\Exception $e) {
  134.                         $error = _L('This functionality is not available due to a misconfiguration');
  135.                         if (OIDplus::authUtils()->isAdminLoggedIn()) {
  136.                                 $htmlmsg = $e instanceof OIDplusException ? $e->getHtmlMessage() : htmlentities($e->getMessage());
  137.                                 $error .= ': '.$htmlmsg;
  138.                         } else {
  139.                                 $error .= '. '._L('Please notify the system administrator. After they log-in, they can see the reason at this place.');
  140.                         }
  141.                         throw new OIDplusHtmlException($error);
  142.                 }
  143.  
  144.                 // Get object-specific path
  145.                 if (!is_null($id)) {
  146.                         $obj = OIDplusObject::parse($id);
  147.                         if (!$obj) throw new OIDplusException(_L('Invalid object "%1"',$id));
  148.  
  149.                         $path_v1 = $basepath . DIRECTORY_SEPARATOR . $obj->getLegacyDirectoryName();
  150.                         $path_v1_bug = $basepath . $obj->getLegacyDirectoryName();
  151.                         $path_v2 = $basepath . DIRECTORY_SEPARATOR . $obj->getDirectoryName();
  152.  
  153.                         if (is_dir($path_v1)) return $path_v1; // backwards compatibility
  154.                         if (is_dir($path_v1_bug)) return $path_v1_bug; // backwards compatibility
  155.                         return $path_v2;
  156.                 } else {
  157.                         return $basepath;
  158.                 }
  159.         }
  160.  
  161.         /**
  162.          * @return mixed|null
  163.          * @throws OIDplusException
  164.          */
  165.         private function raMayDelete() {
  166.                 return OIDplus::config()->getValue('attachments_allow_ra_delete', 0);
  167.         }
  168.  
  169.         /**
  170.          * @return mixed|null
  171.          * @throws OIDplusException
  172.          */
  173.         private function raMayUpload() {
  174.                 return OIDplus::config()->getValue('attachments_allow_ra_upload', 0);
  175.         }
  176.  
  177.         /**
  178.          * @param string $actionID
  179.          * @param array $params
  180.          * @return array
  181.          * @throws OIDplusException
  182.          */
  183.         public function action(string $actionID, array $params): array {
  184.  
  185.                 if ($actionID == 'deleteAttachment') {
  186.                         _CheckParamExists($params, 'id');
  187.                         $id = $params['id'];
  188.                         $obj = OIDplusObject::parse($id);
  189.                         if (!$obj) throw new OIDplusException(_L('Invalid object "%1"',$id));
  190.                         if (!$obj->userHasWriteRights()) throw new OIDplusException(_L('Authentication error. Please log in as admin, or as the RA of "%1" to upload an attachment.',$id), null, 401);
  191.  
  192.                         if (!OIDplus::authUtils()->isAdminLoggedIn() && !$this->raMayDelete()) {
  193.                                 throw new OIDplusException(_L('The administrator has disabled deleting attachments by RAs.'));
  194.                         }
  195.  
  196.                         _CheckParamExists($params, 'filename');
  197.                         $req_filename = $params['filename'];
  198.                         if (strpos($req_filename, '/') !== false) throw new OIDplusException(_L('Illegal file name'));
  199.                         if (strpos($req_filename, '\\') !== false) throw new OIDplusException(_L('Illegal file name'));
  200.                         if (strpos($req_filename, '..') !== false) throw new OIDplusException(_L('Illegal file name'));
  201.                         if (strpos($req_filename, chr(0)) !== false) throw new OIDplusException(_L('Illegal file name'));
  202.  
  203.                         $uploaddir = self::getUploadDir($id);
  204.                         $uploadfile = $uploaddir . DIRECTORY_SEPARATOR . basename($req_filename);
  205.  
  206.                         if (!file_exists($uploadfile)) throw new OIDplusException(_L('File does not exist'));
  207.                         @unlink($uploadfile);
  208.                         if (file_exists($uploadfile)) {
  209.                                 OIDplus::logger()->log("V2:[ERR]OID(%1)+[ERR]A", "Attachment file '%2' could not be deleted from object '%1' (problem with permissions?)", $id, basename($uploadfile));
  210.                                 $msg = _L('Attachment file "%1" could not be deleted from object "%2" (problem with permissions?)',basename($uploadfile),$id);
  211.                                 if (OIDplus::authUtils()->isAdminLoggedIn()) {
  212.                                         throw new OIDplusException($msg);
  213.                                 } else {
  214.                                         throw new OIDplusException($msg.'. '._L('Please contact the system administrator.'));
  215.                                 }
  216.                         } else {
  217.                                 // If it was the last file, delete the empty directory
  218.                                 $ary = @glob($uploaddir . DIRECTORY_SEPARATOR . '*');
  219.                                 if (is_array($ary) && (count($ary) == 0)) @rmdir($uploaddir);
  220.                         }
  221.  
  222.                         OIDplus::logger()->log("V2:[OK]OID(%1)+[OK/INFO]OIDRA(%1)+[OK/INFO]A", "Deleted attachment '%2' from object '%1'", $id, basename($uploadfile));
  223.  
  224.                         return array("status" => 0);
  225.  
  226.                 } else if ($actionID == 'uploadAttachment') {
  227.                         _CheckParamExists($params, 'id');
  228.                         $id = $params['id'];
  229.                         $obj = OIDplusObject::parse($id);
  230.                         if (!$obj) throw new OIDplusException(_L('Invalid object "%1"',$id));
  231.                         if (!$obj->userHasWriteRights()) throw new OIDplusException(_L('Authentication error. Please log in as admin, or as the RA of "%1" to upload an attachment.',$id), null, 401);
  232.  
  233.                         if (!OIDplus::authUtils()->isAdminLoggedIn() && !$this->raMayUpload()) {
  234.                                 throw new OIDplusException(_L('The administrator has disabled uploading attachments by RAs.'));
  235.                         }
  236.  
  237.                         if (!isset($_FILES['userfile'])) {
  238.                                 throw new OIDplusException(_L('Please choose a file.'));
  239.                         }
  240.  
  241.                         if (!OIDplus::authUtils()->isAdminLoggedIn()) {
  242.                                 $fname = basename($_FILES['userfile']['name']);
  243.  
  244.                                 // 1. If something is on the blacklist, we always block it, even if it is on the whitelist, too
  245.                                 $banned = explode(',', OIDplus::config()->getValue('attachments_block_extensions', ''));
  246.                                 foreach ($banned as $ext) {
  247.                                         $ext = trim($ext);
  248.                                         if ($ext == '') continue;
  249.                                         if (strtolower(substr($fname, -strlen($ext)-1)) == strtolower('.'.$ext)) {
  250.                                                 throw new OIDplusException(_L('The file extension "%1" is banned by the administrator (it can be uploaded by the administrator though)',$ext));
  251.                                         }
  252.                                 }
  253.  
  254.                                 // 2. Something on the whitelist is always OK
  255.                                 $allowed = explode(',', OIDplus::config()->getValue('attachments_allow_extensions', ''));
  256.                                 $is_whitelisted = false;
  257.                                 foreach ($allowed as $ext) {
  258.                                         $ext = trim($ext);
  259.                                         if ($ext == '') continue;
  260.                                         if (strtolower(substr($fname, -strlen($ext)-1)) == strtolower('.'.$ext)) {
  261.                                                 $is_whitelisted = true;
  262.                                                 break;
  263.                                         }
  264.                                 }
  265.  
  266.                                 // 3. For everything that is neither whitelisted, nor blacklisted, the admin can decide if these grey zone is allowed or blocked
  267.                                 if (!$is_whitelisted) {
  268.                                         if (!OIDplus::config()->getValue('attachments_allow_grey_extensions', '1')) {
  269.                                                 $tmp = explode('.', $fname);
  270.                                                 $ext = array_pop($tmp);
  271.                                                 throw new OIDplusException(_L('The file extension "%1" is not on the whitelist (it can be uploaded by the administrator though)',$ext));
  272.                                         }
  273.                                 }
  274.                         }
  275.  
  276.                         $req_filename = $_FILES['userfile']['name'];
  277.                         if (strpos($req_filename, '/') !== false) throw new OIDplusException(_L('Illegal file name'));
  278.                         if (strpos($req_filename, '\\') !== false) throw new OIDplusException(_L('Illegal file name'));
  279.                         if (strpos($req_filename, '..') !== false) throw new OIDplusException(_L('Illegal file name'));
  280.                         if (strpos($req_filename, chr(0)) !== false) throw new OIDplusException(_L('Illegal file name'));
  281.  
  282.                         $uploaddir = self::getUploadDir($id);
  283.                         $uploadfile = $uploaddir . DIRECTORY_SEPARATOR . basename($req_filename);
  284.  
  285.                         if (!is_dir($uploaddir)) {
  286.                                 @mkdir($uploaddir, 0777, true);
  287.                                 if (!is_dir($uploaddir)) {
  288.                                         OIDplus::logger()->log("V2:[ERR]OID(%1)+[ERR]A", "Upload attachment '%2' to object '%1' failed: Cannot create directory '%3' (problem with permissions?)", $id, basename($uploadfile), basename($uploaddir));
  289.                                         $msg = _L('Upload attachment "%1" to object "%2" failed',basename($uploadfile),$id).': '._L('Cannot create directory "%1" (problem with permissions?)',basename($uploaddir));
  290.                                         if (OIDplus::authUtils()->isAdminLoggedIn()) {
  291.                                                 throw new OIDplusException($msg);
  292.                                         } else {
  293.                                                 throw new OIDplusException($msg.'. '._L('Please contact the system administrator.'));
  294.                                         }
  295.                                 }
  296.                         }
  297.  
  298.                         if (!@move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
  299.                                 OIDplus::logger()->log("V2:[ERR]OID(%1)+[ERR]A", "Upload attachment '%2' to object '%1' failed: Cannot move uploaded file into directory (problem with permissions?)", $id, basename($uploadfile));
  300.                                 $msg = _L('Upload attachment "%1" to object "%2" failed',basename($uploadfile),$id).': '._L('Cannot move uploaded file into directory (problem with permissions?)');
  301.                                 if (OIDplus::authUtils()->isAdminLoggedIn()) {
  302.                                         throw new OIDplusException($msg);
  303.                                 } else {
  304.                                         throw new OIDplusException($msg.'. '._L('Please contact the system administrator.'));
  305.                                 }
  306.                         }
  307.  
  308.                         OIDplus::logger()->log("V2:[OK]OID(%1)+[OK/INFO]OIDRA(%1)+[OK/INFO]A", "Uploaded attachment '%2' to object '%1'", $id, basename($uploadfile));
  309.  
  310.                         return array("status" => 0);
  311.                 } else {
  312.                         return parent::action($actionID, $params);
  313.                 }
  314.         }
  315.  
  316.         /**
  317.          * @param bool $html
  318.          * @return void
  319.          * @throws OIDplusException
  320.          */
  321.         public function init(bool $html=true) {
  322.                 OIDplus::config()->prepareConfigKey('attachments_block_extensions', 'Block file name extensions being used in file attachments (comma separated)', 'exe,scr,pif,bat,com,vbs,cmd', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  323.                         // TODO: check if a blacklist entry is also on the whitelist (which is not allowed)
  324.                 });
  325.                 OIDplus::config()->prepareConfigKey('attachments_allow_extensions', 'Allow (whitelist) file name extensions being used in file attachments (comma separated)', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  326.                         // TODO: check if a whitelist entry is also on the blacklist (which is not allowed)
  327.                 });
  328.                 OIDplus::config()->prepareConfigKey('attachments_allow_grey_extensions', 'Should file-extensions which are neither be on the whitelist, nor be at the blacklist, be allowed? (1=Yes, 0=No)', '1', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  329.                         if (!is_numeric($value) || ($value < 0) || ($value > 1)) {
  330.                                 throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
  331.                         }
  332.                 });
  333.                 OIDplus::config()->prepareConfigKey('attachments_allow_ra_delete', 'Allow that RAs delete file attachments? (0=no, 1=yes)', '0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  334.                         if (!is_numeric($value) || ($value < 0) || ($value > 1)) {
  335.                                 throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
  336.                         }
  337.                 });
  338.                 OIDplus::config()->prepareConfigKey('attachments_allow_ra_upload', 'Allow that RAs upload file attachments? (0=no, 1=yes)', '0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  339.                         if (!is_numeric($value) || ($value < 0) || ($value > 1)) {
  340.                                 throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
  341.                         }
  342.                 });
  343.                 OIDplus::config()->prepareConfigKey('attachment_upload_dir', 'Alternative directory for attachments. If this setting is empty, then the userdata directory is used.', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  344.                         if (trim($value) !== '') {
  345.                                 self::checkUploadDir($value);
  346.                         }
  347.                 });
  348.         }
  349.  
  350.         /**
  351.          * @param string $id
  352.          * @param array $out
  353.          * @param bool $handled
  354.          * @return void
  355.          */
  356.         public function gui(string $id, array &$out, bool &$handled) {
  357.                 // Nothing
  358.         }
  359.  
  360.         /**
  361.          * @param array $out
  362.          * @return void
  363.          */
  364.         public function publicSitemap(array &$out) {
  365.                 // Nothing
  366.         }
  367.  
  368.         /**
  369.          * @param array $json
  370.          * @param string|null $ra_email
  371.          * @param bool $nonjs
  372.          * @param string $req_goto
  373.          * @return bool
  374.          */
  375.         public function tree(array &$json, string $ra_email=null, bool $nonjs=false, string $req_goto=''): bool {
  376.                 return false;
  377.         }
  378.  
  379.         /**
  380.          * Convert amount of bytes to human-friendly name
  381.          *
  382.          * @param int $bytes
  383.          * @param int $decimals
  384.          * @return string
  385.          * @throws OIDplusConfigInitializationException
  386.          * @throws OIDplusException
  387.          */
  388.         private static function convert_filesize(int $bytes, int $decimals = 2): string {
  389.                 $size = array(_L('Bytes'),_L('KiB'),_L('MiB'),_L('GiB'),_L('TiB'),_L('PiB'),_L('EiB'),_L('ZiB'),_L('YiB'));
  390.                 $factor = floor((strlen("$bytes") - 1) / 3);
  391.                 return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . ' ' . @$size[$factor];
  392.         }
  393.  
  394.         /**
  395.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_2
  396.          *
  397.          * @param string $id
  398.          * @param string $title
  399.          * @param string $icon
  400.          * @param string $text
  401.          * @return void
  402.          * @throws OIDplusConfigInitializationException
  403.          * @throws OIDplusException
  404.          */
  405.         public function modifyContent(string $id, string &$title, string &$icon, string &$text) {
  406.                 $output = '';
  407.                 $doshow = false;
  408.  
  409.                 try {
  410.                         $upload_dir = self::getUploadDir($id);
  411.                         $files = @glob($upload_dir . DIRECTORY_SEPARATOR . '*');
  412.                         $found_files = false;
  413.  
  414.                         $obj = OIDplusObject::parse($id);
  415.                         if (!$obj) throw new OIDplusException(_L('Invalid object "%1"',$id));
  416.                         $can_upload = OIDplus::authUtils()->isAdminLoggedIn() || ($this->raMayUpload() && $obj->userHasWriteRights());
  417.                         $can_delete = OIDplus::authUtils()->isAdminLoggedIn() || ($this->raMayDelete() && $obj->userHasWriteRights());
  418.  
  419.                         if (OIDplus::authUtils()->isAdminLoggedIn()) {
  420.                                 $output .= '<p>'._L('Admin info: The directory is %1','<b>'.htmlentities($upload_dir).'</b>').'</p>';
  421.                                 $doshow = true;
  422.                         }
  423.  
  424.                         $output .= '<div id="fileattachments_table" class="table-responsive">';
  425.                         $output .= '<table class="table table-bordered table-striped">';
  426.                         $output .= '<thead>';
  427.                         $output .= '<tr>';
  428.                         $output .= '<th>'._L('Filename').'</th>';
  429.                         $output .= '<th>'._L('Size').'</th>';
  430.                         $output .= '<th>'._L('File type').'</th>';
  431.                         $output .= '<th>'._L('Download').'</th>';
  432.                         if ($can_delete) $output .= '<th>'._L('Delete').'</th>';
  433.                         $output .= '</tr>';
  434.                         $output .= '</thead>';
  435.                         $output .= '<tbody>';
  436.                         if ($files) foreach ($files as $file) {
  437.                                 if (is_dir($file)) continue;
  438.  
  439.                                 $output .= '<tr>';
  440.                                 $output .= '<td>'.htmlentities(basename($file)).'</td>';
  441.                                 $output .= '<td>'.htmlentities(self::convert_filesize(filesize($file), 0)).'</td>';
  442.                                 $lookup_files = array(
  443.                                         OIDplus::localpath().'userdata/attachments/filetypes$'.OIDplus::getCurrentLang().'.conf',
  444.                                         OIDplus::localpath().'userdata/attachments/filetypes.conf',
  445.                                         OIDplus::localpath().'vendor/danielmarschall/fileformats/filetypes$'.OIDplus::getCurrentLang().'.local', // not recommended
  446.                                         OIDplus::localpath().'vendor/danielmarschall/fileformats/filetypes.local', // not recommended
  447.                                         OIDplus::localpath().'vendor/danielmarschall/fileformats/filetypes$'.OIDplus::getCurrentLang().'.conf',
  448.                                         OIDplus::localpath().'vendor/danielmarschall/fileformats/filetypes.conf'
  449.                                 );
  450.                                 $output .= '<td>'.htmlentities(\VtsFileTypeDetect::getDescription($file, $lookup_files)).'</td>';
  451.  
  452.                                 $output .= '     <td><button type="button" name="download_'.md5($file).'" id="download_'.md5($file).'" class="btn btn-success btn-xs download" onclick="OIDplusPagePublicAttachments.downloadAttachment('.js_escape(OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE)).', current_node,'.js_escape(basename($file)).')">'._L('Download').'</button></td>';
  453.                                 if ($can_delete) {
  454.                                         $output .= '     <td><button type="button" name="delete_'.md5($file).'" id="delete_'.md5($file).'" class="btn btn-danger btn-xs delete" onclick="OIDplusPagePublicAttachments.deleteAttachment(current_node,'.js_escape(basename($file)).')">'._L('Delete').'</button></td>';
  455.                                 }
  456.  
  457.                                 $output .= '</tr>';
  458.                                 $doshow = true;
  459.                                 $found_files = true;
  460.                         }
  461.                         $output .= '</tbody>';
  462.  
  463.                         if (!$found_files) {
  464.                                 $output .= '<tfoor>';
  465.                                 $output .= '<tr><td colspan="' . ($can_delete ? 5 : 4) . '"><i>' . _L('No attachments') . '</i></td></tr>';
  466.                                 $output .= '</tfoot>';
  467.                         }
  468.  
  469.                         $output .= '</table></div>';
  470.  
  471.                         if ($can_upload) {
  472.                                 $output .= '<form action="javascript:void(0);" onsubmit="return OIDplusPagePublicAttachments.uploadAttachmentOnSubmit(this);" enctype="multipart/form-data" id="uploadAttachmentForm">';
  473.                                 $output .= '<input type="hidden" name="id" value="'.htmlentities($id).'">';
  474.                                 $output .= '<div>'._L('Add a file attachment').':<input type="file" name="userfile" value="" id="fileAttachment">';
  475.                                 $output .= '<br><input type="submit" value="'._L('Upload').'"></div>';
  476.                                 $output .= '</form>';
  477.                                 $doshow = true;
  478.                         }
  479.                 } catch (\Exception $e) {
  480.                         $doshow = true;
  481.                         $htmlmsg = $e instanceof OIDplusException ? $e->getHtmlMessage() : htmlentities($e->getMessage());
  482.                         if (strtolower(substr($htmlmsg, 0, 3)) === '<p ') {
  483.                                 $output = $htmlmsg;
  484.                         } else {
  485.                                 $output = '<p>'.$htmlmsg.'</p>';
  486.                         }
  487.                 }
  488.  
  489.                 $output = '<h2>'._L('File attachments').'</h2>' .
  490.                           '<div class="container box">' .
  491.                           $output .
  492.                           '</div>';
  493.                 if ($doshow) $text .= $output;
  494.         }
  495.  
  496.         /**
  497.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
  498.          * @param string $id
  499.          * @return void
  500.          */
  501.         public function beforeObjectDelete(string $id) {}
  502.  
  503.         /**
  504.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
  505.          * @param string $id
  506.          * @return void
  507.          * @throws OIDplusException
  508.          */
  509.         public function afterObjectDelete(string $id) {
  510.                 // Delete the attachment folder including all files in it (note: Subfolders are not possible)
  511.                 $uploaddir = self::getUploadDir($id);
  512.                 if ($uploaddir != '') {
  513.                         $ary = @glob($uploaddir . DIRECTORY_SEPARATOR . '*');
  514.                         if ($ary) foreach ($ary as $a) @unlink($a);
  515.                         @rmdir($uploaddir);
  516.                         if (is_dir($uploaddir)) {
  517.                                 OIDplus::logger()->log("V2:[WARN]OID(%1)+[WARN]A", "Attachment directory '%2' could not be deleted during the deletion of the OID", $id, $uploaddir);
  518.                         }
  519.                 }
  520.         }
  521.  
  522.         /**
  523.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
  524.          * @param string $id
  525.          * @param array $params
  526.          * @return void
  527.          */
  528.         public function beforeObjectUpdateSuperior(string $id, array &$params) {}
  529.  
  530.         /**
  531.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
  532.          * @param string $id
  533.          * @param array $params
  534.          * @return void
  535.          */
  536.         public function afterObjectUpdateSuperior(string $id, array &$params) {}
  537.  
  538.         /**
  539.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
  540.          * @param string $id
  541.          * @param array $params
  542.          * @return void
  543.          */
  544.         public function beforeObjectUpdateSelf(string $id, array &$params) {}
  545.  
  546.         /**
  547.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
  548.          * @param string $id
  549.          * @param array $params
  550.          * @return void
  551.          */
  552.         public function afterObjectUpdateSelf(string $id, array &$params) {}
  553.  
  554.         /**
  555.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
  556.          * @param string $id
  557.          * @param array $params
  558.          * @return void
  559.          */
  560.         public function beforeObjectInsert(string $id, array &$params) {}
  561.  
  562.         /**
  563.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
  564.          * @param string $id
  565.          * @param array $params
  566.          * @return void
  567.          */
  568.         public function afterObjectInsert(string $id, array &$params) {}
  569.  
  570.         /**
  571.          * @param string $request
  572.          * @return array|false
  573.          */
  574.         public function tree_search(string $request) {
  575.                 return false;
  576.         }
  577.  
  578.         /**
  579.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_4
  580.          * @param string $id
  581.          * @param array $out
  582.          * @return void
  583.          * @throws OIDplusException
  584.          */
  585.         public function whoisObjectAttributes(string $id, array &$out) {
  586.                 $xmlns = 'oidplus-attachment-plugin';
  587.                 $xmlschema = 'urn:oid:1.3.6.1.4.1.37476.2.5.2.4.1.95.1';
  588.                 $xmlschemauri = OIDplus::webpath(__DIR__.'/attachments.xsd',OIDplus::PATH_ABSOLUTE);
  589.  
  590.                 $files = @glob(self::getUploadDir($id) . DIRECTORY_SEPARATOR . '*');
  591.                 if ($files) foreach ($files as $file) {
  592.                         $url = OIDplus::webpath(__DIR__,OIDplus::PATH_ABSOLUTE).'download.php?id='.urlencode($id).'&filename='.urlencode(basename($file));
  593.  
  594.                         $out[] = array(
  595.                                 'xmlns' => $xmlns,
  596.                                 'xmlschema' => $xmlschema,
  597.                                 'xmlschemauri' => $xmlschemauri,
  598.                                 'name' => 'attachment-name',
  599.                                 'value' => basename($file)
  600.                         );
  601.  
  602.                         $out[] = array(
  603.                                 'xmlns' => $xmlns,
  604.                                 'xmlschema' => $xmlschema,
  605.                                 'xmlschemauri' => $xmlschemauri,
  606.                                 'name' => 'attachment-url',
  607.                                 'value' => $url
  608.                         );
  609.                 }
  610.  
  611.         }
  612.  
  613.         /**
  614.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_4
  615.          * @param string $email
  616.          * @param array $out
  617.          * @return void
  618.          */
  619.         public function whoisRaAttributes(string $email, array &$out) {}
  620.  
  621.         /**
  622.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_8
  623.          * @param string|null $user
  624.          * @return array  returns array of array($severity, $htmlMessage)
  625.          */
  626.         public function getNotifications(string $user=null): array {
  627.                 $notifications = array();
  628.                 if ((!$user || ($user == 'admin')) && OIDplus::authUtils()->isAdminLoggedIn()) {
  629.                         $error = '';
  630.                         try {
  631.                                 $basepath = self::getUploadBaseDir();
  632.                                 if (!is_dir($basepath)) {
  633.                                         throw new OIDplusException(_L('Directory %1 does not exist', $basepath));
  634.                                 } else {
  635.                                         self::checkUploadDir($basepath);
  636.                                         if (!isFileOrPathWritable($basepath)) {
  637.                                                 throw new OIDplusException(_L('Directory %1 is not writeable. Please check the permissions!', $basepath));
  638.                                         }
  639.                                 }
  640.                         } catch (\Exception $e) {
  641.                                 $error = _L('The file attachments feature is not available due to a misconfiguration');
  642.                                 $htmlmsg = $e instanceof OIDplusException ? $e->getHtmlMessage() : htmlentities($e->getMessage());
  643.                                 $error .= ': ' . $htmlmsg;
  644.                         }
  645.                         if ($error) {
  646.                                 $notifications[] = new OIDplusNotification('WARN', $error);
  647.                         }
  648.                 }
  649.                 return $notifications;
  650.         }
  651. }
  652.