bash_sync_perms.php 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512
  1. <?php
  2. /**
  3. * by plabudda 2013-10-09:
  4. *
  5. * 1. install:
  6. * - create *.plist file:
  7. * # php /Library/Server/Web/Data/Sites/Default/SE/se-dev-pl/bash_sync_perms.php biuro.biall-net.pl addToLaunchctl
  8. * # php /Library/Server/Web/Data/Sites/Default/SE/bash_sync_perms.php biuro.medical-opakowania.pl addToLaunchctl
  9. * - load by launchctl:
  10. * # launchctl load /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  11. *
  12. * 2. uninstall:
  13. * - unload from launchctl:
  14. * # launchctl unload /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  15. *
  16. * 3. debug:
  17. * - debug by www:
  18. * /SE/se-dev-pl/bash_sync_perms.php?DBG=1
  19. * - more verbose debug:
  20. * /SE/se-dev-pl/bash_sync_perms.php?DBG=6
  21. * - task:
  22. * /SE/se-dev-pl/bash_sync_perms.php?task=task
  23. * /SE/se-dev-pl/bash_sync_perms.php?task=newFiles
  24. * /SE/se-dev-pl/bash_sync_perms.php?task=testParse
  25. * /SE/se-dev-pl/bash_sync_perms.php?task=task&PROJ_ID={projID} -- force update project
  26. *
  27. *
  28. * 4. Sync users: `ADMIN_USERS`.`A_STATUS` - OFF - manual sync from users table (groups from CRM_LISTA_ZASOBOW)
  29. * 'WAITING' - Kandydaci
  30. * 'NORMAL' - Aktywni pracownicy
  31. * 'DELETED' - Wyłączone konta
  32. * 'OFF_SOFT' - ?
  33. * 'OFF_HARD' - ?
  34. *
  35. * @2014-01 recomended by A.Binder migration to separate dirs of koresp scripts:
  36. * robienie katalogow dla korespondencji przy migracji na nowy typ pism
  37. #read PASSWORD
  38. #for a in `echo "select concat(ID,';---;',K_OD_KOGO,K_ZAWARTOS) from IN7_DZIENNIK_KORESP" |mysql -p$PASSWORD -uroot -Damssystem -h127.0.0.1 | sed 's/[^a-zA-Z0-9;-]/_/g' |sed 's/;---;/\./g' ` ;
  39. #do
  40. #echo mkdir $a
  41. #mkdir $a
  42. #done
  43. *do wywolania w katalogach IN/OUT:
  44. # cd IN
  45. # for a in `ls |awk -F'.' '{ print $1 }' ` ; do mv $a.* ../$a.*; done
  46. *
  47. *
  48. *
  49. * DONE: koresp format: PISMA/ID/...
  50. * DONE: projekty -> koresp hardlink PROJEKTY/ID..../_PISMA/{HL:pismo.pdf}
  51. * TODO: PROJEKTY/ID..../_PISMA/ permy tylko read/listing
  52. * TODO: hardlink druki: mkdir DRUKI/ID.{DESC}/_PROJEKT/{proj_folder}/{HL:pliki z proj bez podkatalogów}
  53. * TODO: DRUKI/ID.{DESC}/_PROJEKT/{proj_folder} permy tylko read/listing
  54. * -- TODO: DRUKI/ID.{DESC}/ - permy z bazy danych A_ADM_COMPANY, A_CLASSIFIED
  55. *
  56. *
  57. * DONE: Trigger po update/insert Koresp po aktualizacji permów plików projektu
  58. *
  59. * 5. Sync custom tables
  60. * TEST 2014-10-27: # php /Users/plabudda/rsync-dev/SE/bash_sync_perms.php biuro.biall-net.pl SyncPermsCustomTables
  61. * 5.1 Table list in CRM_CONFIG(key=_SYNC_TABLE_FILE_PERMS__TablesList)
  62. * table must be defined in .cnf--folders-{domain}.ini.php as section [{tblName}_COLUMN]
  63. * table must have fields: ID, L_APPOITMENT_USER, A_ADM_COMPANY, A_CLASSIFIED @see generateTasksNewRecords
  64. */
  65. ini_set('max_execution_time', 300);
  66. ini_set('memory_limit', '512M');
  67. define('DS', DIRECTORY_SEPARATOR);
  68. define('APP_PATH_ROOT', dirname(__FILE__));
  69. define('APP_PATH_WWW', dirname(__FILE__));
  70. define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');
  71. // set ini to log errors into error log file
  72. ini_set('display_startup_errors', '0');
  73. ini_set('log_errors', '1');
  74. ini_set('error_log', '/var/log/apache2/error_log');// TODO: php.ini ?
  75. date_default_timezone_set('Europe/Warsaw');// PHP 5 >= 5.1.0 required by date functions
  76. require_once APP_PATH_ROOT . DS . 'se-lib' . DS . 'Lib.php';
  77. Lib::loadClass('V');
  78. Lib::loadClass('Config');
  79. Lib::loadClass('DB');
  80. Lib::loadClass('User');
  81. Lib::loadClass('FoldersConfig');
  82. Lib::loadClass('FileUploader');
  83. if (isset($_SERVER["argv"][1])) {
  84. $_SERVER['SERVER_NAME'] = $_SERVER["argv"][1];
  85. }
  86. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'info') {
  87. $info = array();
  88. $info['max_execution_time'] = ini_get('max_execution_time');
  89. $info['memory_limit'] = ini_get('memory_limit');
  90. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  91. ini_set('max_execution_time', 300);
  92. ini_set('memory_limit', '512M');
  93. $info = array();
  94. $info['max_execution_time'] = ini_get('max_execution_time');
  95. $info['memory_limit'] = ini_get('memory_limit');
  96. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  97. // $requirePermsExt = SyncPerms::getRequiredPermsExtByRecord((object)[
  98. // 'L_APPOITMENT_USER' => "plabudda",
  99. // 'A_ADM_COMPANY' => "",
  100. // 'A_CLASSIFIED' => "",
  101. // 'PARENT_L_APPOITMENT_USER' => "a.binder",
  102. // ]);
  103. // DBG::nicePrint($requirePermsExt, '$requirePermsExt - public for workgroup');
  104. // $requirePermsExt = SyncPerms::getRequiredPermsExtByRecord((object)[
  105. // 'L_APPOITMENT_USER' => "plabudda",
  106. // 'A_ADM_COMPANY' => "2948-programista",
  107. // 'A_CLASSIFIED' => "2948-programista",
  108. // 'PARENT_L_APPOITMENT_USER' => "a.binder",
  109. // ]);
  110. // DBG::nicePrint($requirePermsExt, '$requirePermsExt - only 2948-programista read,write');
  111. // $requirePermsExt = SyncPerms::getRequiredPermsExtByRecord((object)[
  112. // 'L_APPOITMENT_USER' => "plabudda",
  113. // 'A_ADM_COMPANY' => "",
  114. // 'A_CLASSIFIED' => "2948-programista",
  115. // 'PARENT_L_APPOITMENT_USER' => "a.binder",
  116. // ]);
  117. // DBG::nicePrint($requirePermsExt, '$requirePermsExt - 2948-programista read');
  118. // $requirePermsExt = SyncPerms::getRequiredPermsExtByRecord((object)[
  119. // 'L_APPOITMENT_USER' => "plabudda",
  120. // 'A_ADM_COMPANY' => "2948-programista",
  121. // 'A_CLASSIFIED' => "",
  122. // 'PARENT_L_APPOITMENT_USER' => "a.binder",
  123. // ]);
  124. // DBG::nicePrint($requirePermsExt, '$requirePermsExt - 2948-programista write');
  125. //
  126. // $vFile = (object)[
  127. // 'path' => 'test-file-1.txt',
  128. // 'isDir' => false,
  129. // 'permsExt' => [],
  130. // ];
  131. // $permReadDir = "list,search,readattr,readextattr,readsecurity,file_inherit,directory_inherit";
  132. // $permWriteDir = "add_file,add_subdirectory,delete_child,writeattr,writeextattr,writesecurity,chown";
  133. // $permReadFile = "read,execute,readattr,readextattr,readsecurity";
  134. // $permWriteFile = "write,append,writeattr,writeextattr,writesecurity,chown";
  135. //
  136. // $recordPath = "/Library/Server/Web/Data/Sites/Default/PLIKI/TEST_PERMS/90";
  137. // $filePath = "{$recordPath}/{$vFile->path}";
  138. //
  139. // $cmdList = SyncPerms::fixFilePerms($vFile, $requirePermsExt, $recordPath);
  140. // DBG::nicePrint($cmdList, '$cmdList - 2948-programista write');
  141. //
  142. // V::exec("ls -le '{$filePath}'", $out, $ret);
  143. // DBG::nicePrint($out, "\$out - ret({$ret})");
  144. //
  145. // V::exec("echo \"" . implode("\n", [
  146. // "user:_www allow read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown",
  147. // "group:27_BIALL-NET allow read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown",
  148. // ]) . "\" | chmod -E '{$filePath}'", $out, $ret);
  149. // DBG::nicePrint($out, "\$out - ret({$ret})");
  150. //
  151. // V::exec("ls -le '{$filePath}'", $out, $ret);
  152. // DBG::nicePrint($out, "\$out - test 1, ret({$ret})");
  153. //
  154. // $aclPermsOut = implode("\n", [
  155. // "user:_www allow read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown",
  156. // "group:27_BIALL-NET allow read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown",
  157. // ]);
  158. // $aclPermsOut = implode("\n", [
  159. // "user:_www allow read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown",
  160. // "group:27_BIALL-NET allow read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown",
  161. // "user:plabudda allow read,write",
  162. // ]);
  163. // V::exec("cd '{$recordPath}'; find . -type f | while read -r file; do echo \"fix file perms: \$file\"; echo \"{$aclPermsOut}\" | chmod -E \"\${file}\"; done", $out, $ret);
  164. // DBG::nicePrint($out, "\$out - ret({$ret})");
  165. //
  166. // V::exec("ls -le '{$filePath}'", $out, $ret);
  167. // DBG::nicePrint($out, "\$out - test 2, ret({$ret})");
  168. //
  169. // $testPermsFile = "{$recordPath}/perms-90.txt";
  170. // DBG::nicePrint(explode("\n", file_get_contents($testPermsFile)), "testPermsFile - before add line");
  171. // $lineToAdd = "user:plabudda allow read,write";
  172. // V::exec("cat '{$testPermsFile}' | grep '{$lineToAdd}' || echo \"{$lineToAdd}\" >> '{$testPermsFile}'", $out, $ret);
  173. // DBG::nicePrint($out, "\$out - add line, ret({$ret})");
  174. // DBG::nicePrint(explode("\n", file_get_contents($testPermsFile)), "testPermsFile - after add line");
  175. //
  176. // { // TODO: add to instalator / install check / ?Status
  177. // $lineToAdd = "_www ALL = NOPASWD: '" . APP_PATH_ROOT . "/SE/index-cli.php'";
  178. // $destFile = "/etc/sudoers";
  179. // V::exec("cat '{$destFile}' | grep '{$lineToAdd}' || echo \"{$lineToAdd}\" >> '{$destFile}'", $out, $ret);
  180. // // TODO: check if sudo index-cli.php can exec("sudo ...")
  181. // }
  182. }
  183. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'users') {
  184. SyncPerms::run(null, null, 'users', null);
  185. }
  186. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'usersAll') {
  187. SyncPerms::run(null, null, 'usersAll', null);
  188. }
  189. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'task') {
  190. SyncPerms::run(null, null, 'nextTask', null);
  191. }
  192. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'newFiles') {
  193. SyncPerms::run(null, null, 'newFiles', null);
  194. }
  195. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'testParse') {
  196. $cmd = " ls -Rlea . ";
  197. exec("cd '/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1657.Rekrutacja_z_dnia_2012-06_25_na_stanowisko_Przedstawiciel_Handlowy/1/'; {$cmd} ", $filesWithPerms);
  198. //$line = "-rwxrwx---+ 1 _www workgroup 212367 Feb 25 2013 {file_name}";
  199. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';
  200. $filesWithPermsTree = array();
  201. $lastName = '';
  202. $folderParent = '';
  203. foreach ($filesWithPerms as $line) {
  204. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  205. $fileParts = array();
  206. $filePartsArr = explode(' ', $line);
  207. $lastInd = 0;
  208. foreach ($filePartsArr as $vPart) {
  209. if ($lastInd > 7) {// file name
  210. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  211. $lastInd++;
  212. }
  213. else if (!empty($vPart) || $vPart === '0') {
  214. $fileParts[] = $vPart;
  215. $lastInd++;
  216. }
  217. }
  218. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  219. $lastName = '..';
  220. continue;
  221. }
  222. $file = new stdClass();
  223. if (!isset($fileParts[8])) {
  224. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  225. //continue;
  226. } else {
  227. // fix file name from bad chars
  228. // [8] => CV_Kowalski Mariusz`.pdf
  229. // "-$Model Bialnet .xlsm" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  230. // [11-Oct-2013 21:00:28 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2013-02-26_harmonogram_EDORADCA_Aktualny/-$harmonogram 01.2013.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  231. // [11-Oct-2013 21:00:27 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2012-04-19_oferta_gpon_sprint_po_poprawkach/-$Wycena GPON 2012 Biall-Net_spr v1.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  232. // [11-Oct-2013 20:56:25 UTC] PHP Notice: Error-cmd: chmod +a "user:prejsi allow write,append,writeattr,writeextattr,writesecurity,chown,read,execute,readattr,readextattr,readsecurity" "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1695.Projekt_glowny_dzialu_rozwoju_biznesu_oraz_dystrybucji_informacji/HANDLOWY/HANDLOWY_2012/OTOMIN/-$Otomin.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1517
  233. //$fileParts[8] = str_replace('\\', '\\\\', $fileParts[8]);
  234. //$fileParts[8] = str_replace(array('`', '$'), array('\`', '\$'), $fileParts[8]);
  235. }
  236. echo'<pre style="max-height:230px;overflow:auto;border:1px solid red;text-align:left;">line/$fileParts/$filePartsArr (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($line, $fileParts, $filePartsArr));echo'</pre>';
  237. $file->name = end($fileParts);
  238. $file->path = array();
  239. if ($folderParent) $file->path[] = $folderParent;
  240. $file->path[] = end($fileParts);
  241. $file->path = implode('/', $file->path);
  242. //$file->owner = $fileParts[2];
  243. //$file->group = $fileParts[3];
  244. //$file->perms = $fileParts[0];
  245. $file->isDir = (substr($line, 0, 1) == 'd');
  246. $file->permsExt = array();
  247. $filesWithPermsTree[$file->name] = $file;
  248. $lastName = $file;
  249. }
  250. else if (substr($line, 0, 1) == ' ') {// extended perm line
  251. if ($lastName == '..') {
  252. continue;
  253. }
  254. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  255. }
  256. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  257. $folderParent = substr($line, 2, -1);
  258. }
  259. else if (substr($line, 0, 5) == 'total') {
  260. continue;
  261. }
  262. else if (empty($line)) {
  263. $folderParent = '';
  264. continue;
  265. }
  266. }
  267. echo'<pre style="max-height:400px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';
  268. }
  269. else if (empty($_SERVER["argv"]) && V::get('DBG', '', $_GET, 'int') > 0) {
  270. SyncPerms::run(null, null);
  271. }
  272. else {
  273. die("\n The second argument should be server domain - e.g. biuro.kike.pl \n");
  274. }
  275. if (!empty($_SERVER["argv"][0]) && !empty($_SERVER["argv"][1])) {
  276. $arg2 = (!empty($_SERVER["argv"][2]))? $_SERVER["argv"][2] : null;
  277. $arg3 = (!empty($_SERVER["argv"][3]))? $_SERVER["argv"][3] : null;
  278. SyncPerms::run($_SERVER["argv"][0], $_SERVER["argv"][1], $arg2, $arg3);
  279. }
  280. class SyncPerms {
  281. public static function run($script_name, $domain, $arg2 = null, $arg3 = null) {
  282. if ($arg2 == 'addToLaunchctl') self::task__addToLaunchctl($domain);
  283. else if ($arg2 == 'newFiles') self::task__newFiles();
  284. else if ($arg2 == 'nextTask') self::task__nextTask();
  285. else if ($arg2 == 'testErrorLog') self::task__testErrorLog();
  286. else if ($arg2 == 'users') self::usersAction();
  287. else if ($arg2 == 'usersAll') self::usersAllAction();
  288. else if ($arg2 == 'SyncPermsCustomTables') self::task__SyncPermsCustomTables();
  289. else if ($arg2 == 'sendNotify') self::sendNotify();
  290. else self::task__default();
  291. }
  292. public static function task__addToLaunchctl($domain) {
  293. $plistFile = "/Library/LaunchDaemons/pl.biallnet.sync_perms.{$domain}.php.plist";
  294. system("echo \"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
  295. <!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
  296. <plist version=\"1.0\">
  297. <dict>
  298. <key>Disabled</key>
  299. <false/>
  300. <key>Label</key>
  301. <string>pl.biallnet.sync_perms.{$domain}.php</string>
  302. <key>UserName</key>
  303. <string>root</string>
  304. <key>ProgramArguments</key>
  305. <array>
  306. <string>php</string>
  307. <string>{$_SERVER["argv"][0]}</string>
  308. <string>{$_SERVER["argv"][1]}</string>
  309. </array>
  310. <key>StartInterval</key>
  311. <integer>60</integer>
  312. </dict>
  313. </plist>
  314. \" > {$plistFile}");
  315. echo "Run as root: launchctl load {$plistFile} \n";
  316. }
  317. public static function task__newFiles() {
  318. $time = new stdClass();
  319. $time->start = time();
  320. self::newFilesAction();
  321. $time->end = time();
  322. // TODO: print operation time if DBG
  323. }
  324. public static function task__nextTask() {
  325. $time = new stdClass();
  326. $time->start = time();
  327. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">nextTask</pre>';}
  328. self::installTable();
  329. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">installTable DONE</pre>';}
  330. self::generateTasksNewRecords();
  331. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksNewRecords DONE</pre>';}
  332. self::generateTasksUpdated();
  333. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksUpdated DONE</pre>';}
  334. $limit = V::get('_limit', 1, $_GET, 'int');
  335. for ($i = 0; $i < $limit; $i++) {
  336. $time->cur = time();
  337. if ($time->cur - $time->start > 60 * 5) {
  338. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">Force-break time('.($time->cur - $time->start).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';echo'</pre>';}
  339. break;
  340. }
  341. $task = self::nextTaskAction();
  342. if (!$task) break;
  343. }
  344. }
  345. public static function task__testErrorLog() {
  346. echo "display_errors: " . ini_get("display_errors") . "\n";
  347. echo "display_startup_errors: " . ini_get("display_startup_errors") . "\n";
  348. echo "log_errors: " . ini_get("log_errors") . "\n";
  349. echo "error_reporting: " . ini_get("error_reporting") . "\n";
  350. echo "error_log: " . ini_get("error_log") . "\n";
  351. trigger_error("Notice: Test Error Log", E_USER_NOTICE);
  352. }
  353. public static function task__SyncPermsCustomTables() {
  354. $DBG_TIME = true;
  355. $dbgTime = new stdClass();
  356. $dbgTime->startTime = microtime(true);
  357. $dbgTime->lastTime = $dbgTime->startTime;
  358. $customSync = new SyncPermsCustomTables();
  359. // TODO: $customSync->run();
  360. $customSync->fetchConfig();
  361. if ($DBG_TIME) {
  362. $dbgTime->curTime = microtime(true);
  363. trigger_error("DBG:time after-fetchConfig (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  364. $dbgTime->lastTime = $dbgTime->curTime;
  365. }
  366. $customSync->installTable();
  367. if ($DBG_TIME) {
  368. $dbgTime->curTime = microtime(true);
  369. trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  370. $dbgTime->lastTime = $dbgTime->curTime;
  371. }
  372. $rowId = (int)$arg3;
  373. if ($rowId > 0) {
  374. $customSync->executeTask('DEALS_TABLE', $rowId);// TODO: DEALS_TABLE ?
  375. }
  376. else {
  377. $customSync->generateTasksNewRecords();
  378. if ($DBG_TIME) {
  379. $dbgTime->curTime = microtime(true);
  380. trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  381. $dbgTime->lastTime = $dbgTime->curTime;
  382. }
  383. $customSync->generateTasksUpdated();
  384. if ($DBG_TIME) {
  385. $dbgTime->curTime = microtime(true);
  386. trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  387. $dbgTime->lastTime = $dbgTime->curTime;
  388. }
  389. $customSync->newFilesAction();
  390. if ($DBG_TIME) {
  391. $dbgTime->curTime = microtime(true);
  392. trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  393. $dbgTime->lastTime = $dbgTime->curTime;
  394. }
  395. $limit = 1000;
  396. for ($i = 0; $i < $limit; $i++) {
  397. $loopTasksFired = 0;
  398. foreach ($customSync->_tbls as $tblName => $tblConf) {
  399. $task = $customSync->nextTaskAction($tblName);
  400. if ($DBG_TIME) {
  401. $dbgTime->curTime = microtime(true);
  402. trigger_error("DBG:time after-nextTaskAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  403. $dbgTime->lastTime = $dbgTime->curTime;
  404. }
  405. if (!$task) {
  406. // TODO: rm $tblName from config to prevent searching for task in next loops
  407. unset($customSync->_tbls[$tblName]);
  408. continue;
  409. }
  410. $loopTasksFired++;
  411. }
  412. if (!$loopTasksFired) {
  413. if ($DBG_TIME) {
  414. $dbgTime->curTime = microtime(true);
  415. trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  416. $dbgTime->lastTime = $dbgTime->curTime;
  417. }
  418. break;
  419. }
  420. $i += $loopTasksFired;
  421. }
  422. }
  423. $dbgTime->endTime = microtime(true);
  424. trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
  425. }
  426. public static function task__default() {
  427. $DBG_TIME = false;
  428. $DBG_MEMORY = false;
  429. $dbgTime = new stdClass();
  430. $dbgTime->start = time();
  431. $dbgTime->startTime = microtime(true);
  432. $dbgTime->lastTime = $dbgTime->startTime;
  433. self::installTable();
  434. if ($DBG_TIME) {
  435. $dbgTime->curTime = microtime(true);
  436. trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  437. $dbgTime->lastTime = $dbgTime->curTime;
  438. }
  439. self::generateTasksNewRecords();
  440. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksNewRecords " . memory_get_usage(true) . ".", E_USER_NOTICE);
  441. if ($DBG_TIME) {
  442. $dbgTime->curTime = microtime(true);
  443. trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  444. $dbgTime->lastTime = $dbgTime->curTime;
  445. }
  446. self::generateTasksUpdated();
  447. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksUpdated " . memory_get_usage(true) . ".", E_USER_NOTICE);
  448. if ($DBG_TIME) {
  449. $dbgTime->curTime = microtime(true);
  450. trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  451. $dbgTime->lastTime = $dbgTime->curTime;
  452. }
  453. $dbgTime->cur = time();
  454. if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
  455. trigger_error("Error: time end after-init " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
  456. return;
  457. }
  458. self::newFilesAction();
  459. if($DBG_MEMORY)trigger_error("DBG:mem usage after-newFilesAction " . memory_get_usage(true) . ".", E_USER_NOTICE);
  460. if ($DBG_TIME) {
  461. $dbgTime->curTime = microtime(true);
  462. trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  463. $dbgTime->lastTime = $dbgTime->curTime;
  464. }
  465. $limit = 100;
  466. for ($i = 0; $i < $limit; $i++) {
  467. $dbgTime->cur = time();
  468. if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
  469. trigger_error("Error: time end after-nextTaskAction(loop:{$i}) " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
  470. return;
  471. }
  472. $task = self::nextTaskAction();
  473. if($DBG_MEMORY)trigger_error("DBG:mem usage after-nextTaskAction (loop:{$i}) " . memory_get_usage(true) . ".", E_USER_NOTICE);
  474. if ($DBG_TIME) {
  475. $dbgTime->curTime = microtime(true);
  476. trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  477. $dbgTime->lastTime = $dbgTime->curTime;
  478. }
  479. if (!$task) {
  480. $dbgTime->cur = time();
  481. break;
  482. }
  483. }
  484. $customSync = new SyncPermsCustomTables();
  485. $customSync->run();
  486. $dbgTime->cur = time();
  487. $dbgTime->endTime = microtime(true);
  488. trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
  489. if ($DBG_TIME) {
  490. $dbgTime->curTime = microtime(true);
  491. trigger_error("DBG:time sync end OK (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  492. $dbgTime->lastTime = $dbgTime->curTime;
  493. }
  494. self::sendNotify();
  495. Lib::loadClass('Router');
  496. echo "DBG: UrlAction_WmsGenerate->doGenerate() START...\n";
  497. Router::getRoute('UrlAction_WmsGenerate')->doGenerate();
  498. echo "DBG: UrlAction_WmsGenerate->doGenerate() END\n";
  499. echo "DBG: UrlAction_BiAuditGenerate->doGenerate() START...\n";
  500. //Router::getRoute('UrlAction_BiAuditGenerate')->doGenerate(); //musze przetestowac raport!
  501. echo "DBG: UrlAction_BiAuditGenerate->doGenerate() END\n";
  502. }
  503. public static function sendNotify() {
  504. Lib::loadClass('Router');
  505. $cronTaskName = 'sendNotify';
  506. $keyToken = 'bach_sync_perms';
  507. $token = Router::getRoute('Cron')->generateCliAuthToken($keyToken, $cronTaskName, 300 * 10);
  508. echo "DBG: token = '{$token}'" . "\n";
  509. $string = Router::getRoute('Cron')->executeCurlTastByToken($cronTaskName, $keyToken, $token);
  510. echo "DBG: string -----------------------\n{$string}\nEOF string---------------------------------\n";
  511. }
  512. public static function installTable() {
  513. $sql = "
  514. CREATE TABLE IF NOT EXISTS `_SYNC_FILE_PERMS` (
  515. `ID` int(11) NOT NULL AUTO_INCREMENT,
  516. `ID_PROJECT` int(11) NOT NULL,
  517. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  518. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  519. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  520. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  521. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  522. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  523. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  524. PRIMARY KEY (`ID`),
  525. UNIQUE KEY `ID_PROJECT` (`ID_PROJECT`)
  526. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  527. ";
  528. DB::getPDO()->execSql($sql);
  529. try {
  530. $sql = " DROP TRIGGER IF EXISTS `KORESP_change_ID_PROJECT`; ";
  531. DB::getPDO()->execSql($sql);
  532. } catch (Exception $e) {
  533. // TODO: SKIP - BUG after upgrade mysql - @see https://dev.mysql.com/doc/refman/5.5/en/upgrading-from-previous-series.html
  534. }
  535. try {
  536. $sql = "
  537. CREATE DEFINER=`root`@`localhost` TRIGGER `KORESP_change_ID_PROJECT` AFTER UPDATE ON `IN7_DZIENNIK_KORESP`
  538. FOR EACH ROW BEGIN
  539. IF (NEW.`ID_PROJECT` != OLD.`ID_PROJECT` and NEW.`ID_PROJECT` > 0) or OLD.`M_DIST_FILES`!=NEW.`M_DIST_FILES` THEN
  540. update `_SYNC_FILE_PERMS` as s set
  541. s.`A_SYNCHRONIZED`=0
  542. where
  543. s.`ID_PROJECT`=NEW.`ID_PROJECT`
  544. or s.`ID_PROJECT`=OLD.`ID_PROJECT`;
  545. END IF;
  546. END
  547. ";
  548. DB::getPDO()->execSql($sql);
  549. } catch (Exception $e) {
  550. echo "DB ERR L." . __LINE__ . ": " . $e->getMessage() . "\n";
  551. trigger_error("DB ERR L." . __LINE__ . ": " . $e->getMessage(), E_USER_WARNING);
  552. }
  553. try {
  554. $sql = " DROP TRIGGER IF EXISTS `KORESP_add_ID_PROJECT`; ";
  555. DB::getPDO()->execSql($sql);
  556. } catch (Exception $e) {
  557. // TODO: SKIP - BUG after upgrade mysql - @see https://dev.mysql.com/doc/refman/5.5/en/upgrading-from-previous-series.html
  558. }
  559. try {
  560. $sql = "
  561. CREATE DEFINER=`root`@`localhost` TRIGGER `KORESP_add_ID_PROJECT` AFTER INSERT ON `IN7_DZIENNIK_KORESP`
  562. FOR EACH ROW BEGIN
  563. IF NEW.`ID_PROJECT` > 0 THEN
  564. update `_SYNC_FILE_PERMS` as s set
  565. s.`A_SYNCHRONIZED`=0
  566. where
  567. s.`ID_PROJECT`=NEW.`ID_PROJECT`;
  568. END IF;
  569. END
  570. ";
  571. DB::getPDO()->execSql($sql);
  572. } catch (Exception $e) {
  573. echo "DB ERR L." . __LINE__ . ": " . $e->getMessage() . "\n";
  574. trigger_error("DB ERR L." . __LINE__ . ": " . $e->getMessage(), E_USER_WARNING);
  575. }
  576. }
  577. public static function newFilesAction() {
  578. $task = self::getTaskNewFiles();
  579. $taskResult = self::fixLastModifiedFiles($task);
  580. self::saveTask(-1);
  581. }
  582. public static function nextTaskAction() {
  583. $task = self::getTask();
  584. if (!$task) return false;
  585. self::executeTask($task);
  586. /*
  587. if (isset($task->A_SYNC_RESULT->total)
  588. && isset($task->A_SYNC_RESULT->lastDone)
  589. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  590. ) {
  591. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  592. } else {
  593. self::saveTask($task->ID_PROJECT);
  594. }
  595. */
  596. self::saveTask($task->ID_PROJECT);
  597. return $task;
  598. }
  599. public static function generateTasksUpdated() {
  600. $sqlTest = "
  601. select p.ID, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, s. *
  602. from `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  603. where
  604. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  605. and (
  606. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  607. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  608. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  609. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  610. )
  611. ";
  612. $sql = "update `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  613. set
  614. s.`L_APPOITMENT_USER`=p.`L_APPOITMENT_USER`
  615. , s.`A_ADM_COMPANY`=p.`A_ADM_COMPANY`
  616. , s.`A_CLASSIFIED`=p.`A_CLASSIFIED`
  617. , s.`PARENT_L_APPOITMENT_USER`=pp.`L_APPOITMENT_USER`
  618. , s.`A_SYNCHRONIZED`=0
  619. where
  620. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  621. and (
  622. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  623. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  624. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  625. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  626. )
  627. ";
  628. try {
  629. DB::getPDO()->execSql($sql);
  630. } catch (Exception $e) {
  631. echo "DB ERR L." . __LINE__ . ": " . $e->getMessage() . "\n";
  632. trigger_error("DB ERR L." . __LINE__ . ": " . $e->getMessage(), E_USER_WARNING);
  633. }
  634. }
  635. public static function generateTasksNewRecords() {
  636. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  637. values (-1, '', '', '', '');
  638. ";
  639. try {
  640. DB::getPDO()->execSql($sql);
  641. } catch (Exception $e) {
  642. echo "DB ERR L." . __LINE__ . ": " . $e->getMessage() . "\n";
  643. trigger_error("DB ERR L." . __LINE__ . ": " . $e->getMessage(), E_USER_WARNING);
  644. }
  645. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  646. select p.`ID`, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, pp.`L_APPOITMENT_USER`
  647. from `IN7_MK_BAZA_DYSTRYBUCJI` as p
  648. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on (pp.`ID`=p.`P_ID`)
  649. where p.`A_STATUS`!='DELETED'
  650. ";
  651. try {
  652. DB::getPDO()->execSql($sql);
  653. } catch (Exception $e) {
  654. echo "DB ERR L." . __LINE__ . ": " . $e->getMessage() . "\n";
  655. trigger_error("DB ERR L." . __LINE__ . ": " . $e->getMessage(), E_USER_WARNING);
  656. }
  657. }
  658. /**
  659. * Znajdź najstarszy aktualizowany projekt.
  660. */
  661. public static function getTask() {
  662. $sqlWhereProjID = " s.`A_SYNCHRONIZED`=0 ";
  663. if (($projID = V::get('PROJ_ID', '', $_GET, 'int')) > 0) {
  664. $sqlWhereProjID = " s.`ID_PROJECT`='{$projID}' ";
  665. }
  666. $sql = "
  667. select s.*
  668. , p.`L_APPOITMENT_USER` as p__L_APPOITMENT_USER
  669. , p.`A_ADM_COMPANY` as p__A_ADM_COMPANY
  670. , p.`A_CLASSIFIED` as p__A_CLASSIFIED
  671. , pp.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  672. , p.`M_DIST_DESC` as p__M_DIST_DESC
  673. , p.`M_DISTRIBUTOR` as p__M_DISTRIBUTOR
  674. , p.`CRM_LISTA_ZASOBOW_ID` as p__CRM_LISTA_ZASOBOW_ID
  675. from `_SYNC_FILE_PERMS` as s
  676. left join `IN7_MK_BAZA_DYSTRYBUCJI` as p on(p.`ID`=s.`ID_PROJECT`)
  677. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on(pp.`ID`=p.`P_ID`)
  678. where {$sqlWhereProjID}
  679. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  680. limit 1
  681. ";
  682. try {
  683. $task = DB::getPDO()->fetchFirst($sql);
  684. if ($task) {
  685. $task['A_SYNC_RESULT'] = (!$task['A_SYNC_RESULT'])? new stdClass() : json_decode($task['A_SYNC_RESULT']);
  686. return (object)$task;
  687. }
  688. } catch (Exception $e) {
  689. echo "DB ERR L." . __LINE__ . ": " . $e->getMessage() . "\n";
  690. trigger_error("DB ERR L." . __LINE__ . ": " . $e->getMessage(), E_USER_WARNING);
  691. }
  692. return null;
  693. }
  694. public static function getTaskNewerUsers() {
  695. $sql = "
  696. select s.*
  697. from `_SYNC_FILE_PERMS` as s
  698. where s.`ID_PROJECT`=-2
  699. ";
  700. try {
  701. $task = DB::getPDO()->fetchFirst($sql);
  702. if ($task) {
  703. return (object)$task;
  704. }
  705. } catch (Exception $e) {
  706. echo "DB ERR L." . __LINE__ . ": " . $e->getMessage() . "\n";
  707. trigger_error("DB ERR L." . __LINE__ . ": " . $e->getMessage(), E_USER_WARNING);
  708. }
  709. return (object)[
  710. 'ID_PROJECT' => -2,
  711. 'A_SYNC_RESULT' => new stdClass(),
  712. 'A_LAST_SYNC' => '', // date("Y-m-d H:i", mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"))),
  713. ];
  714. }
  715. public static function getTaskNewFiles() {
  716. $sql = "
  717. select s.*
  718. from `_SYNC_FILE_PERMS` as s
  719. where s.`ID_PROJECT`=-1
  720. ";
  721. try {
  722. $task = DB::getPDO()->fetchFirst($sql);
  723. if ($task) {
  724. return (object)$task;
  725. }
  726. } catch (Exception $e) {
  727. echo "DB ERR L." . __LINE__ . ": " . $e->getMessage() . "\n";
  728. trigger_error("DB ERR L." . __LINE__ . ": " . $e->getMessage(), E_USER_WARNING);
  729. }
  730. return (object)[
  731. 'ID_PROJECT' => -1,
  732. 'A_SYNC_RESULT' => new stdClass(),
  733. 'A_LAST_SYNC' => date("Y-m-d H:i", mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"))),
  734. ];
  735. }
  736. public static function saveTask($idProject, $taskDone = 1, $result = null) {
  737. $sqlResult = ($result)
  738. ? " , s.`A_SYNC_RESULT` = " . DB::getPDO()->quote( json_encode($result) )
  739. : '';
  740. $sql = "
  741. update `_SYNC_FILE_PERMS` as s
  742. set
  743. s.`A_LAST_SYNC` = NOW()
  744. , s.`A_SYNCHRONIZED` = {$taskDone}
  745. {$sqlResult}
  746. where s.`ID_PROJECT` = {$idProject}
  747. ";
  748. DB::getPDO()->execSql($sql);
  749. }
  750. public static function executeTask(&$task) {
  751. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
  752. $confTblName = 'IN7_MK_BAZA_DYSTRYBUCJI_COLUMN';
  753. $PROJ_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  754. $project = new stdClass();
  755. $project->ID = $task->ID_PROJECT;
  756. $project->L_APPOITMENT_USER = $task->p__L_APPOITMENT_USER;
  757. $project->A_ADM_COMPANY = $task->p__A_ADM_COMPANY;
  758. $project->A_CLASSIFIED = $task->p__A_CLASSIFIED;
  759. $project->PARENT_L_APPOITMENT_USER = $task->p__PARENT_L_APPOITMENT_USER;
  760. $project->M_DIST_DESC = $task->p__M_DIST_DESC;
  761. $project->M_DISTRIBUTOR = $task->p__M_DISTRIBUTOR;
  762. $project->CRM_LISTA_ZASOBOW_ID = $task->p__CRM_LISTA_ZASOBOW_ID;
  763. $folderConf = FoldersConfig::getAll($confTblName);
  764. $uploader = new FileUploader($confTblName, $project);
  765. $errMsg = '';
  766. if (!$uploader->setConfig($folderConf, $errMsg)) {
  767. trigger_error("Error: folders config!", E_USER_NOTICE);
  768. die("Error: folders config!");
  769. }
  770. $uploader->findFolder();
  771. $mainFolder = $uploader->getDestFolder();
  772. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
  773. if (!$mainFolder) {
  774. $mainFolder = $uploader->generateFolderName();
  775. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  776. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
  777. mkdir($mainFolderPath, 0770, true);
  778. @chmod($mainFolderPath, 0770);
  779. if (!file_exists($mainFolderPath)) {
  780. trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
  781. return false;
  782. }
  783. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  784. $file = new stdClass();
  785. $file->name = '.';
  786. $file->path = '.';
  787. //$file->owner = '';
  788. //$file->group = '';
  789. //$file->perms = '';
  790. $file->isDir = true;
  791. $file->permsExt = array();
  792. $cmdList = self::fixFilePerms($file, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $project);
  793. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  794. }
  795. else {
  796. $cmdList = self::fixProject($project, $mainFolder, $PROJ_mount_point, $task);
  797. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProject (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  798. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  799. $folderPismaPath = "{$mainFolderPath}/_PISMA";
  800. // if folder _PISMA not exists then create
  801. $cmdList[] = "if [ ! -d '{$folderPismaPath}' ] ; then mkdir '{$folderPismaPath}'; chmod 0770 '{$folderPismaPath}'; fi;";
  802. $cmdKorepList = self::fixProjectKoresp($project, $folderPismaPath);
  803. if (!empty($cmdKorepList)) {
  804. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProjectKoresp (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdKorepList);echo'</pre>';}
  805. foreach ($cmdKorepList as $vCmd) {
  806. $cmdList[] = $vCmd;
  807. }
  808. }
  809. }
  810. if (!empty($cmdList)) {
  811. foreach ($cmdList as $vCmd) {
  812. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  813. exec($vCmd, $out, $outValue);
  814. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  815. if ($outValue != 0) {
  816. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  817. }
  818. }
  819. }
  820. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
  821. }
  822. public static function getActiveLoginList() {
  823. static $activeLoginList;
  824. if (!is_array($activeLoginList)) {
  825. $activeLoginList = DB::getPDO()->fetchValuesList("
  826. select u.`ADM_ACCOUNT`
  827. from `ADMIN_USERS` as u
  828. where u.`A_STATUS` = 'NORMAL'
  829. ");
  830. }
  831. return $activeLoginList;
  832. }
  833. public static function isActiveUser($login) {
  834. $activeLoginList = self::getActiveLoginList();
  835. return in_array($login, $activeLoginList);
  836. }
  837. public static function getRequiredPermsExtByRecord($project) {
  838. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  839. $requirePermsExt = array();
  840. if (!$project->L_APPOITMENT_USER && !$project->A_ADM_COMPANY) {// no owner, no write group
  841. // TODO: group PODMIOT
  842. $requirePermsExt["group:workgroup"] = array('write', 'read');
  843. }
  844. else {
  845. if ($project->L_APPOITMENT_USER) {
  846. if (self::isActiveUser($project->L_APPOITMENT_USER)) {
  847. $requirePermsExt["user:{$project->L_APPOITMENT_USER}"] = array('write', 'read');
  848. } else {
  849. // TODO: trigger error $project->L_APPOITMENT_USER is not active user!
  850. }
  851. }
  852. if (!empty($project->A_ADM_COMPANY) && $project->A_ADM_COMPANY == $project->A_CLASSIFIED) {
  853. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('read', 'write');
  854. }
  855. else if (empty($project->A_ADM_COMPANY) && empty($project->A_CLASSIFIED)) {
  856. $requirePermsExt["group:workgroup"] = array('write', 'read');
  857. }
  858. else {
  859. if ($project->A_ADM_COMPANY) {
  860. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('write');
  861. }
  862. if ($project->A_CLASSIFIED) {
  863. $requirePermsExt["group:{$project->A_CLASSIFIED}"] = array('read');
  864. }
  865. }
  866. }
  867. // add parent owner
  868. if (!empty($project->PARENT_L_APPOITMENT_USER) && $project->PARENT_L_APPOITMENT_USER != $project->L_APPOITMENT_USER) {
  869. if (self::isActiveUser($project->PARENT_L_APPOITMENT_USER)) {
  870. $requirePermsExt["user:{$project->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  871. } else {
  872. // TODO: trigger error $project->PARENT_L_APPOITMENT_USER is not active user!
  873. }
  874. }
  875. // add user:_www perms read, write
  876. $requirePermsExt["user:_www"] = array('write', 'read');
  877. return $requirePermsExt;
  878. }
  879. /**
  880. * Used for files added/modified by samba/afp.
  881. *
  882. * @return TODO: object to store in task->A_SYNC_RESULT
  883. */
  884. public static function fixLastModifiedFiles($task) {
  885. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
  886. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  887. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  888. $foundProjectFiles = array();
  889. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
  890. //exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  891. exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;", $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  892. if (!empty($filesWithPerms)) {
  893. $filesWithPermsTree = array();
  894. $lastName = '';
  895. foreach ($filesWithPerms as $line) {
  896. if (substr($line, 0, 1) == '-') {// file name
  897. $fileParts = array();
  898. $filePartsArr = explode(' ', $line);
  899. $lastInd = 0;
  900. foreach ($filePartsArr as $vPart) {
  901. if ($lastInd > 7) {// file name
  902. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  903. $lastInd++;
  904. }
  905. else if (!empty($vPart) || $vPart === '0') {
  906. $fileParts[] = $vPart;
  907. $lastInd++;
  908. }
  909. }
  910. $file = new stdClass();
  911. if (!isset($fileParts[8])) {
  912. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  913. //continue;
  914. }
  915. $file->name = end($fileParts);
  916. $file->path = end($fileParts);
  917. //$file->owner = $fileParts[2];
  918. //$file->group = $fileParts[3];
  919. //$file->perms = $fileParts[0];
  920. $file->isDir = (substr($line, 0, 1) == 'd');
  921. $file->permsExt = array();
  922. $filesWithPermsTree[$file->name] = $file;
  923. $lastName = $file->name;
  924. }
  925. else if (substr($line, 0, 1) == ' ') {// extended perm line
  926. if ($lastName == '..') {
  927. continue;
  928. }
  929. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  930. }
  931. else {// parse error
  932. $lastName = '..';
  933. }
  934. }
  935. foreach ($filesWithPermsTree as $vFile) {
  936. $vFile->path = ltrim($vFile->path, './');
  937. $vFile->path = explode('/', $vFile->path);
  938. $vFile->projectFolder = array_shift($vFile->path);
  939. $vFile->path = implode('/', $vFile->path);
  940. $projId = explode('.', $vFile->projectFolder);
  941. $projId = reset($projId);
  942. if (is_numeric($projId) && $projId > 0) {
  943. $foundProjectFiles[$projId][] = $vFile;
  944. }
  945. }
  946. }
  947. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  948. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectFiles);echo'</pre>';}
  949. if (!empty($foundProjectFiles)) {
  950. $sql = "
  951. select p.`ID`
  952. , p.`L_APPOITMENT_USER`
  953. , p.`A_ADM_COMPANY`
  954. , p.`A_CLASSIFIED`
  955. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  956. from IN7_MK_BAZA_DYSTRYBUCJI as p
  957. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  958. where p.`ID` in (" . implode(',', array_keys($foundProjectFiles)) . ")
  959. ";
  960. $rows = DB::getPDO()->fetchAll($sql);
  961. foreach ($rows as $row) {
  962. $r = (object)$row;
  963. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  964. foreach ($foundProjectFiles[$r->ID] as $vFile) {
  965. $cmdList = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$vFile->projectFolder}", $r);
  966. if (!empty($cmdList)) {
  967. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  968. foreach ($cmdList as $vCmd) {
  969. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  970. exec($vCmd, $out, $outValue);
  971. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  972. if ($outValue != 0) {
  973. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  974. }
  975. }
  976. } else {
  977. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
  978. }
  979. }
  980. }
  981. }
  982. }
  983. public static function fixProjectKoresp($project, $folderPismaPath) {
  984. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  985. $PISMA_mount_point = rtrim($PISMA_mount_point, '/');
  986. // $PISMA_mount_point / {TYP_KORESP} / {ID} . *
  987. $sql = "
  988. select k.`ID`
  989. , k.`K_TYP_KORESP`
  990. from `IN7_DZIENNIK_KORESP` as k
  991. where k.`ID_PROJECT`={$project->ID}
  992. order by k.`ID` DESC
  993. limit 100
  994. ";
  995. $pismaList = array_map(function ($row) {
  996. return $row['K_TYP_KORESP']; // TODO: K_TYP_KORESP not used
  997. }, DB::getPDO()->fetchAllByKey($sql, 'ID'));
  998. // $PISMA_mount_point / {TYP_KORESP} / {ID} . *
  999. if (empty($pismaList)) {
  1000. return false;
  1001. }
  1002. $lsCmd = array();
  1003. $lsCmd[] = "0.*/";// if only one folder then it doesnt show folder name, only files
  1004. foreach ($pismaList as $kID => $vTyp) {
  1005. $lsCmd[] = "{$kID}.*/";
  1006. }
  1007. if (empty($lsCmd)) {
  1008. return false;
  1009. }
  1010. $lsCmd = 'ls -le ' . implode($lsCmd, ' ') . ' 2>>/dev/null ';
  1011. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Koreps lsCmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lsCmd);echo'</pre>';}
  1012. exec("cd {$PISMA_mount_point}; {$lsCmd} ", $filesWithPerms);
  1013. $filesWithPermsTree = array();
  1014. if (!empty($filesWithPerms)) {
  1015. $lastName = '';
  1016. $folderParent = '';
  1017. foreach ($filesWithPerms as $line) {
  1018. if (substr($line, 0, 1) == '-') {// file name
  1019. $fileParts = array();
  1020. $filePartsArr = explode(' ', $line);
  1021. $lastInd = 0;
  1022. foreach ($filePartsArr as $vPart) {
  1023. if ($lastInd > 7) {// file name
  1024. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1025. $lastInd++;
  1026. }
  1027. else if (!empty($vPart) || $vPart === '0') {
  1028. $fileParts[] = $vPart;
  1029. $lastInd++;
  1030. }
  1031. }
  1032. $file = new stdClass();
  1033. if (!isset($fileParts[8])) {
  1034. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  1035. //continue;
  1036. }
  1037. $file->name = end($fileParts);
  1038. $file->path = array();
  1039. if ($folderParent) $file->path[] = $folderParent;
  1040. $file->path[] = end($fileParts);
  1041. $file->path = implode('/', $file->path);
  1042. //$file->owner = $fileParts[2];
  1043. //$file->group = $fileParts[3];
  1044. //$file->perms = $fileParts[0];
  1045. $file->isDir = (substr($line, 0, 1) == 'd');
  1046. $file->permsExt = array();
  1047. $filesWithPermsTree[$file->name] = $file;
  1048. $lastName = $file->name;
  1049. }
  1050. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1051. if ($lastName == '..') {
  1052. continue;
  1053. }
  1054. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1055. }
  1056. else if (substr($line, -1) == ':') {// folder
  1057. $folderParent = trim(substr($line, 0, -1), '/');
  1058. }
  1059. else if (substr($line, 0, 5) == 'total') {
  1060. continue;
  1061. }
  1062. else if (empty($line)) {
  1063. $folderParent = '';
  1064. continue;
  1065. }
  1066. else {// parse error
  1067. $lastName = '..';
  1068. }
  1069. }
  1070. }
  1071. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  1072. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPermsTree);echo'</pre>';}
  1073. $cmdList = array();
  1074. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  1075. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  1076. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PISMA_mount_point}", $project);
  1077. if (!empty($cmdFile)) {
  1078. foreach ($cmdFile as $vCmd) {
  1079. $cmdList[] = $vCmd;
  1080. }
  1081. }
  1082. // if folder _PISMA not exists then create
  1083. $fname = explode('/', $vFile->path);
  1084. $fname = end($fname);
  1085. $cmdList []= "if [ ! -f '{$folderPismaPath}/{$fname}' ] ; then ln '{$PISMA_mount_point}/{$vFile->path}' '{$folderPismaPath}'/; fi; ";
  1086. }
  1087. return $cmdList;
  1088. }
  1089. /*
  1090. * Not used.
  1091. */
  1092. public static function preloadFixProject(&$task, $mainFolder, $PROJ_mount_point) {
  1093. if ($task->ID_PROJECT == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1094. if (isset($task->A_SYNC_RESULT->total)) {
  1095. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && find . -type f | wc -l ", $filesTotal);
  1096. if (!empty($filesTotal)) {
  1097. $filesTotal = reset($filesTotal);
  1098. $filesTotal = intval(trim($filesTotal));
  1099. $task->A_SYNC_RESULT->total = $filesTotal;
  1100. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  1101. }
  1102. }
  1103. }
  1104. }
  1105. public static function fixProject($r, $mainFolder, $PROJ_mount_point, &$task) {
  1106. $time = time();
  1107. if ($r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1108. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: pomin - za dużo plików ('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
  1109. //return false;
  1110. }
  1111. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">r('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
  1112. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  1113. $filesWithPerms = array();
  1114. $cmd = " ls -Rlea . ";
  1115. if (false) {//$r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1116. if (isset($task->A_SYNC_RESULT->total)) {
  1117. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">A_SYNC_RESULT (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("A_SYNC_RESULT[total]={$task->A_SYNC_RESULT->total}");echo'</pre>';}
  1118. if ($task->A_SYNC_RESULT->total > 1000) {
  1119. $lastDone = V::get('lastDone', 0, $task->A_SYNC_RESULT, 'int');
  1120. if ($lastDone > 0) {
  1121. $task->A_SYNC_RESULT->lastDone = $lastDone + 1000;
  1122. $cmd = " find . -type f | head -" . ($lastDone + 1000) . " | tail -1000 | xargs ls -le ";
  1123. } else {
  1124. $task->A_SYNC_RESULT->lastDone = 1000;
  1125. $cmd = " find . -type f | head -1000 | xargs ls -le ";
  1126. }
  1127. }
  1128. }
  1129. }
  1130. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ");echo'</pre>';}
  1131. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ", $filesWithPerms);
  1132. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';}
  1133. $filesWithPermsTree = array();
  1134. $lastName = '';
  1135. $folderParent = '';
  1136. foreach ($filesWithPerms as $line) {
  1137. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  1138. $fileParts = array();
  1139. $filePartsArr = explode(' ', $line);
  1140. $lastInd = 0;
  1141. foreach ($filePartsArr as $vPart) {
  1142. if ($lastInd > 7) {// file name
  1143. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1144. $lastInd++;
  1145. }
  1146. else if (!empty($vPart) || $vPart === '0') {
  1147. $fileParts[] = $vPart;
  1148. $lastInd++;
  1149. }
  1150. }
  1151. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  1152. $lastName = '..';
  1153. continue;
  1154. }
  1155. $file = new stdClass();
  1156. if (!isset($fileParts[8])) {
  1157. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  1158. //continue;
  1159. }
  1160. $file->name = end($fileParts);
  1161. $file->path = array();
  1162. if ($folderParent) $file->path[] = $folderParent;
  1163. $file->path[] = end($fileParts);
  1164. $file->path = implode('/', $file->path);
  1165. //$file->owner = $fileParts[2];
  1166. //$file->group = $fileParts[3];
  1167. //$file->perms = $fileParts[0];
  1168. $file->isDir = (substr($line, 0, 1) == 'd');
  1169. $file->permsExt = array();
  1170. $filesWithPermsTree[$file->name] = $file;
  1171. $lastName = $file;
  1172. }
  1173. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1174. if ($lastName == '..') {
  1175. continue;
  1176. }
  1177. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1178. }
  1179. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  1180. $folderParent = substr($line, 2, -1);
  1181. }
  1182. else if (substr($line, 0, 5) == 'total') {
  1183. continue;
  1184. }
  1185. else if (empty($line)) {
  1186. $folderParent = '';
  1187. continue;
  1188. }
  1189. }
  1190. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
  1191. // check perms
  1192. /*
  1193. files:
  1194. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  1195. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  1196. R read, execute, readattr, readextattr, readsecurity
  1197. dir:
  1198. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  1199. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  1200. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  1201. */
  1202. $cmdList = array();
  1203. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  1204. if (false) {
  1205. // TODO: $kFileName == '_PISMA' - readonly
  1206. // TODO: $vFile->path => _PISMA/...
  1207. }
  1208. else {
  1209. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $r);
  1210. if (!empty($cmdFile)) {
  1211. foreach ($cmdFile as $vCmd) {
  1212. $cmdList[] = $vCmd;
  1213. }
  1214. }
  1215. }
  1216. }
  1217. return $cmdList;
  1218. }
  1219. public static function fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1220. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1221. $cmdList = array();
  1222. $vReqPermsExt = array();
  1223. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1224. $vReqPermsExt[$kPermObj] = array();
  1225. foreach ($vPerms as $vPerm) {
  1226. if ($vFile->isDir) {
  1227. if ($vPerm == 'read') {
  1228. $vReqPermsExt[$kPermObj]['list'] = 0;
  1229. $vReqPermsExt[$kPermObj]['search'] = 0;
  1230. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1231. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1232. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1233. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1234. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1235. }
  1236. else if ($vPerm == 'write') {
  1237. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1238. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1239. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1240. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1241. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1242. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1243. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1244. }
  1245. }
  1246. else {
  1247. if ($vPerm == 'read') {
  1248. $vReqPermsExt[$kPermObj]['read'] = 0;
  1249. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1250. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1251. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1252. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1253. }
  1254. else if ($vPerm == 'write') {
  1255. $vReqPermsExt[$kPermObj]['write'] = 0;
  1256. $vReqPermsExt[$kPermObj]['append'] = 0;
  1257. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1258. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1259. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1260. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1261. }
  1262. }
  1263. }
  1264. }
  1265. $permsToRemove = array();
  1266. foreach ($vFile->permsExt as $vPermExtLine) {
  1267. $vPermExtArr = explode(' ', $vPermExtLine);
  1268. $vPermExt = new stdClass();
  1269. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1270. $vPermExt->permObj = $vPermExtArr[1];
  1271. $vPermExt->perms = '';
  1272. if (count($vPermExtArr) == 4) {
  1273. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1274. }
  1275. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1276. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1277. }
  1278. else {
  1279. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1280. continue;
  1281. }
  1282. $permFound = false;
  1283. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1284. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1285. foreach ($vPerms as $kPerm => $vPermChecked) {
  1286. if (in_array($kPerm, $vPermExt->perms)) {
  1287. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1288. $permFound = true;
  1289. }
  1290. }
  1291. }
  1292. }
  1293. if (!$permFound) {
  1294. $permsToRemove[] = $vPermExt->nr;
  1295. }
  1296. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
  1297. }
  1298. if (!empty($permsToRemove)) {
  1299. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1300. $permsToRemove = array_reverse($permsToRemove);
  1301. foreach ($permsToRemove as $vPermInd) {
  1302. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1303. }
  1304. }
  1305. $permsToAdd = array();
  1306. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1307. foreach ($vPerms as $kPerm => $vPermChecked) {
  1308. if (!$vPermChecked) {
  1309. $permsToAdd[$kPermObj][$kPerm] = 1;
  1310. }
  1311. }
  1312. }
  1313. if (!empty($permsToAdd)) {
  1314. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1315. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1316. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1317. }
  1318. }
  1319. return $cmdList;
  1320. }
  1321. /**
  1322. * @returns array - last modified project ids.
  1323. */
  1324. public static function fixLastModifiedByFiles() {// TODO: RMME
  1325. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByFiles");echo'</pre>';}
  1326. /*
  1327. * $ man find:
  1328. -newer file
  1329. True if the current file has a more recent last modification time than file.
  1330. -newerXY file
  1331. True if the current file has a more recent last access time (X=a), inode creation time (X=B), change time (X=c),
  1332. or modification time (X=m) than the last access time (Y=a), inode creation time (Y=B), change time (Y=c), or mod-
  1333. ification time (Y=m) of file. In addition, if Y=t, then file is instead interpreted as a direct date specifica-
  1334. tion of the form understood by cvs(1). Note that -newermm is equivalent to -newer.
  1335. *
  1336. * $ man chmod:
  1337. -i Removes the 'inherited' bit from all entries in the named file(s) ACLs.
  1338. *
  1339. * chmod -a "admin allow write" file1 # remove line
  1340. * chmod -a# 1 file1 # remove line at position 1
  1341. *
  1342. * chmod +a nie zmienia modify date: find . -newermt '2013-10-07 ...'
  1343. */
  1344. // find /Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY -newermt '2013-10-07 16:20'
  1345. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  1346. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  1347. $foundProjectIds = array();
  1348. $lastRunDate = self::getLastRunDate();
  1349. exec("cd {$PROJ_mount_point}; find . -newermt '{$lastRunDate}' ", $foundPaths);
  1350. if (!empty($foundPaths)) {
  1351. foreach ($foundPaths as $path) {
  1352. $path = ltrim($path, './');
  1353. $folder = explode('/', $path);
  1354. $folder = reset($folder);
  1355. $projId = explode('.', $folder);
  1356. $projId = reset($projId);
  1357. if (is_numeric($projId)) {
  1358. $foundProjectIds[$projId] = $folder;
  1359. }
  1360. }
  1361. }
  1362. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundPaths (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundPaths);echo'</pre>';}
  1363. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectIds (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectIds);echo'</pre>';}
  1364. if (!empty($foundProjectIds)) {
  1365. $sql = "
  1366. select p.`ID`
  1367. , p.`L_APPOITMENT_USER`
  1368. , p.`A_ADM_COMPANY`
  1369. , p.`A_CLASSIFIED`
  1370. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1371. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1372. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1373. where p.`ID` in (" . implode(',', array_keys($foundProjectIds)) . ")
  1374. ";
  1375. $rows = DB::getPDO()->fetchAll($sql);
  1376. foreach ($rows as $row) {
  1377. $r = (object)$row;
  1378. $mainFolder = $foundProjectIds[$r->ID];
  1379. $cmdList = self::fixProject($r, $mainFolder, $PROJ_mount_point);
  1380. if (!empty($cmdList)) {
  1381. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1382. } else {
  1383. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1384. }
  1385. }
  1386. }
  1387. return array_keys($foundProjectIds);
  1388. }
  1389. public static function fixLastModifiedByDB($fixedProjIds) {// TODO: RMME
  1390. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByDB (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByDB");echo'</pre>';}
  1391. $sqlWhereAdd = '';
  1392. if (!empty($fixedProjIds)) {
  1393. $sqlWhereAdd = " and p.`ID` not in (" . implode(',', $fixedProjIds) . ") ";
  1394. }
  1395. $lastRunDate = self::getLastRunDate();
  1396. $sql = "
  1397. select p.`ID`
  1398. , p.`L_APPOITMENT_USER`
  1399. , p.`A_ADM_COMPANY`
  1400. , p.`A_CLASSIFIED`
  1401. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1402. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1403. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1404. where
  1405. ( p.`A_RECORD_UPDATE_DATE`>'{$lastRunDate}'
  1406. or p.`A_RECORD_CREATE_DATE`>'{$lastRunDate}'
  1407. )
  1408. {$sqlWhereAdd}
  1409. ";
  1410. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  1411. $projectList = array_map(function ($row) {
  1412. return (object)$row;
  1413. }, DB::getPDO()->fetchAllByKey($sql, 'ID'));
  1414. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">projectList (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($projectList);echo'</pre>';}
  1415. }
  1416. public static function getLastRunDate() {// TODO: RMME
  1417. if (($argFromDate = V::get('_fromDate', '', $_GET)) != '') {
  1418. // Format: 2013-10-07 23:46
  1419. if (strlen($argFromDate) == 16
  1420. && substr($argFromDate, 4, 1) == '-'
  1421. && substr($argFromDate, 7, 1) == '-'
  1422. && substr($argFromDate, 10, 1) == '-'
  1423. && substr($argFromDate, 13, 1) == ':'
  1424. && is_numeric(str_replace(array('-', ':'), '', $argFromDate))
  1425. ) {
  1426. $lastRunDate = mktime(substr($argFromDate, 11, 2), substr($argFromDate, 14, 2), 0, substr($argFromDate, 5, 2), substr($argFromDate, 8, 2), substr($argFromDate, 0, 4));
  1427. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1428. }
  1429. }
  1430. if (!$lastRunDate) {
  1431. $lastRunDate = mktime(date("H") - 1, date("i"), date("s"), date("n"), date("j"), date("Y"));
  1432. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1433. }
  1434. //$lastRunDate = '2013-09-01 01:00';
  1435. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lastRunDate);echo'</pre>';
  1436. return $lastRunDate;
  1437. }
  1438. public static function usersAction() {
  1439. $task = self::getTaskNewerUsers();
  1440. $users = self::getUsersNewerThen($task->A_LAST_SYNC);
  1441. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$users (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1442. self::saveTask(-2);
  1443. }
  1444. public static function usersAllAction() {
  1445. /*
  1446. * DBU - DB User LDU - LDAP User
  1447. * DBG - DB Group LDG - LDAP Group
  1448. *
  1449. * DBU - ADMIN_USERS
  1450. * DBG - CRM_LISTA_ZASOBOW where TYPE in('STANOWISKO','PODMIOT','DZIAL')// TODO: GRUPA_PROJEKTOWA - ldap nested group?
  1451. *
  1452. * 1. fetch DB Users
  1453. * ? only active users (A_STATUS == 'NORMAL')
  1454. * 2. fetch LDAP Users
  1455. *
  1456. * DBU.ADM_ACCOUNT == LDU.uid
  1457. * DBG.A_LDAP_GID == LDG.gidNumber
  1458. *
  1459. * TODO: $group createLdapGroup()
  1460. *
  1461. */
  1462. Lib::loadClass('UsersHelper');
  1463. $users = self::getUsersAll();
  1464. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">users count('.count($users).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1465. $allLdapUsers = UsersHelper::getLDAPUsersAll();
  1466. $ldapUsers = array();
  1467. foreach ($allLdapUsers as $vLdapUser) {
  1468. $ldapUsers[$vLdapUser->uid] = $vLdapUser;
  1469. }
  1470. unset($allLdapUsers);
  1471. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">ldapUsers count('.count($ldapUsers).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ldapUsers);echo'</pre>';
  1472. foreach ($users as $kLogin => $vUser) {
  1473. if ($vUser->A_STATUS == 'NORMAL') {
  1474. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1475. echo '<div>'.$vUser->ADM_ACCOUNT.': OK? account exists in LDAP</div>';
  1476. }
  1477. else {
  1478. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: create account in LDAP</div>';
  1479. }
  1480. }
  1481. else if ($vUser->A_STATUS == 'DELETED') {
  1482. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1483. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: disable account</div>';
  1484. }
  1485. else {
  1486. //echo '<div>'.$vUser->ADM_ACCOUNT.': WARNING: account not exists in LDAP</div>';
  1487. }
  1488. }
  1489. }
  1490. }
  1491. public static function getUsersNewerThen($datetime) {
  1492. $sqlWhereAdd = "";
  1493. if ($datetime) {
  1494. $sqlWhereAdd = " and ( u.`A_RECORD_CREATE_DATE`>'{$datetime}' or u.`A_RECORD_UPDATE_DATE`>'{$datetime}' )";
  1495. } else {
  1496. // TODO: error datetime not set
  1497. }
  1498. $sql = "
  1499. select u.ID
  1500. , u.`ADM_ACCOUNT`
  1501. , u.`ADM_NAME`
  1502. , u.`A_STATUS`
  1503. from `ADMIN_USERS` as u
  1504. where
  1505. u.`A_STATUS` in('NORMAL', 'DELETED')
  1506. ";
  1507. return array_map(function ($row) {
  1508. return (object)$row;
  1509. }, DB::getPDO()->fetchAllByKey($sql, 'ADM_ACCOUNT'));
  1510. }
  1511. public static function getUsersAll() {
  1512. $sql = "
  1513. select u.ID
  1514. , u.`ADM_ACCOUNT`
  1515. , u.`ADM_NAME`
  1516. , u.`A_STATUS`
  1517. from `ADMIN_USERS` as u
  1518. where
  1519. u.`A_STATUS` in('NORMAL', 'DELETED')
  1520. ";
  1521. return array_map(function ($row) {
  1522. return (object)$row;
  1523. }, DB::getPDO()->fetchAllByKey($sql, 'ADM_ACCOUNT'));
  1524. }
  1525. }
  1526. class SyncPermsCustomTables {
  1527. public $_tbls;
  1528. private $_db;
  1529. private $_syncTblName = '_SYNC_TABLE_FILE_PERMS';
  1530. private $_activeLoginList;
  1531. public function run() {
  1532. if (!$this->fetchConfig()) return;
  1533. $this->installTable();
  1534. $this->generateTasksNewRecords();
  1535. $this->generateTasksUpdated();
  1536. $this->newFilesAction();
  1537. $limit = 100;
  1538. for ($i = 0; $i < $limit; $i++) {
  1539. $loopTasksFired = 0;
  1540. foreach ($this->_tbls as $tblName => $tblConf) {
  1541. $task = $this->nextTaskAction($tblName);
  1542. if (!$task) {
  1543. // TODO: rm $tblName from config to prevent searching for task in next loops
  1544. unset($this->_tbls[$tblName]);
  1545. continue;
  1546. }
  1547. $loopTasksFired++;
  1548. }
  1549. if (!$loopTasksFired) break;
  1550. $i += $loopTasksFired;
  1551. }
  1552. }
  1553. public function fetchConfig() {
  1554. $sql = "
  1555. select c.`CONF_VAL` as tbl_names
  1556. from `CRM_CONFIG` as c
  1557. where c.`CONF_KEY`='_SYNC_TABLE_FILE_PERMS__TablesList'
  1558. ";
  1559. $tblNames = DB::getPDO()->fetchValue($sql);
  1560. $tbls = (!empty($tblNames)) ? explode("\n", $tblNames) : [];
  1561. $configTbls = array();
  1562. Lib::loadClass('FoldersConfig');
  1563. if (!empty($tbls)) {
  1564. $folderConfAll = FoldersConfig::getRawData();
  1565. foreach ($tbls as $tblName) {
  1566. $tblName = trim($tblName);
  1567. if (empty($tblName)) continue;
  1568. $confTblName = "{$tblName}_COLUMN";
  1569. if (FoldersConfig::hasConfig($confTblName)) {
  1570. $configTbls[$tblName] = FoldersConfig::getAll($confTblName);
  1571. }
  1572. }
  1573. }
  1574. //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', array_keys($configTbls)) . "]\n";
  1575. if (!empty($configTbls)) {
  1576. $this->_tbls = $configTbls;
  1577. }
  1578. return $this->_tbls;
  1579. }
  1580. public function installTable() {
  1581. if (!$this->_tbls) return;
  1582. $sql = "
  1583. CREATE TABLE IF NOT EXISTS `{$this->_syncTblName}` (
  1584. `ID` int(11) NOT NULL AUTO_INCREMENT,
  1585. `TBL_NAME` varchar(64),
  1586. `TBL_ID` int(11) NOT NULL,
  1587. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  1588. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  1589. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  1590. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  1591. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  1592. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  1593. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  1594. `A_POMIN_SYNC` tinyint(1) NOT NULL DEFAULT '0',
  1595. PRIMARY KEY (`ID`),
  1596. UNIQUE KEY `TBL` (`TBL_NAME`, `TBL_ID`)
  1597. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  1598. ";
  1599. try {
  1600. DB::getPDO()->execSql($sql);
  1601. } catch (Exception $e) {
  1602. echo "DB ERR L." . __LINE__ . ": " . $e->getMessage() . "\n";
  1603. trigger_error("DB ERR L." . __LINE__ . ": " . $e->getMessage(), E_USER_WARNING);
  1604. }
  1605. }
  1606. public function generateTasksNewRecords() {
  1607. if (!$this->_tbls) return;
  1608. $sqlValues = array();
  1609. foreach ($this->_tbls as $tblName => $tblConf) {
  1610. $sqlValues[] = "('{$tblName}', -1, '', '', '', '')";
  1611. }
  1612. $sqlValues = implode(',', $sqlValues);
  1613. $sql = "
  1614. insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  1615. values {$sqlValues};
  1616. ";
  1617. try {
  1618. DB::getPDO()->execSql($sql);
  1619. } catch (Exception $e) {
  1620. echo "DB ERR L." . __LINE__ . ": " . $e->getMessage() . "\n";
  1621. trigger_error("DB ERR L." . __LINE__ . ": " . $e->getMessage(), E_USER_WARNING);
  1622. }
  1623. foreach ($this->_tbls as $tblName => $tblConf) {
  1624. $sql = "
  1625. insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  1626. select '{$tblName}' as TBL_NAME
  1627. , t.`ID`, t.`L_APPOITMENT_USER`, t.`A_ADM_COMPANY`, t.`A_CLASSIFIED`
  1628. , '' as PARENT_L_APPOITMENT_USER -- pp.`L_APPOITMENT_USER`
  1629. from `{$tblName}` as t
  1630. where t.`A_STATUS`!='DELETED'
  1631. ";
  1632. try {
  1633. DB::getPDO()->execSql($sql);
  1634. } catch (Exception $e) {
  1635. echo "DB ERR L." . __LINE__ . ": " . $e->getMessage() . "\n";
  1636. trigger_error("DB ERR L." . __LINE__ . ": " . $e->getMessage(), E_USER_WARNING);
  1637. }
  1638. }
  1639. }
  1640. public function generateTasksUpdated() {
  1641. if (!$this->_tbls) return;
  1642. foreach ($this->_tbls as $tblName => $tblConf) {
  1643. $sql = "update `{$this->_syncTblName}` as s
  1644. , `{$tblName}` as t
  1645. -- , `IN7_MK_BAZA_DYSTRYBUCJI` as pt
  1646. set
  1647. s.`L_APPOITMENT_USER`=t.`L_APPOITMENT_USER`
  1648. , s.`A_ADM_COMPANY`=t.`A_ADM_COMPANY`
  1649. , s.`A_CLASSIFIED`=t.`A_CLASSIFIED`
  1650. , s.`PARENT_L_APPOITMENT_USER`='' -- pt.`L_APPOITMENT_USER`
  1651. , s.`A_SYNCHRONIZED`=0
  1652. where
  1653. s.`TBL_ID`=t.`ID`
  1654. and s.`TBL_NAME`='{$tblName}'
  1655. -- and pt.`ID`=t.`P_ID`
  1656. and (
  1657. s.`L_APPOITMENT_USER`!=t.`L_APPOITMENT_USER`
  1658. or s.`A_ADM_COMPANY`!=t.`A_ADM_COMPANY`
  1659. or s.`A_CLASSIFIED`!=t.`A_CLASSIFIED`
  1660. -- or s.`PARENT_L_APPOITMENT_USER`!=pt.`L_APPOITMENT_USER`
  1661. )
  1662. ";
  1663. try {
  1664. DB::getPDO()->execSql($sql);
  1665. } catch (Exception $e) {
  1666. echo "DB ERR L." . __LINE__ . ": " . $e->getMessage() . "\n";
  1667. trigger_error("DB ERR L." . __LINE__ . ": " . $e->getMessage(), E_USER_WARNING);
  1668. }
  1669. }
  1670. }
  1671. public function newFilesAction() {
  1672. if (!$this->_tbls) return;
  1673. foreach ($this->_tbls as $tblName => $tblConf) {
  1674. $task = $this->_getTaskNewFiles($tblName);
  1675. $taskResult = $this->_fixLastModifiedFiles($task);
  1676. $this->_saveTask($tblName, -1);
  1677. }
  1678. }
  1679. private function _getTaskNewFiles($tblName) {
  1680. $task = null;
  1681. $sql = "
  1682. select s.*
  1683. from `{$this->_syncTblName}` as s
  1684. where s.`TBL_ID`=-1 and s.`TBL_NAME`='{$tblName}'
  1685. ";
  1686. $task = DB::getPDO()->fetchFirst($sql);
  1687. return ($task)
  1688. ? (object)$task
  1689. : (object)[
  1690. 'TBL_NAME' => $tblName,
  1691. 'TBL_ID' => -1,
  1692. 'A_SYNC_RESULT' => new stdClass(),
  1693. 'A_LAST_SYNC' => date("Y-m-d H:i", mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"))),
  1694. ];
  1695. }
  1696. private function _fixLastModifiedFiles($task) {
  1697. $tblName = $task->TBL_NAME;
  1698. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
  1699. $confTblName = "{$task->TBL_NAME}_COLUMN";
  1700. $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  1701. $record = null;
  1702. $folderConf = FoldersConfig::getAll($confTblName);
  1703. $uploader = new FileUploader($confTblName, $record);
  1704. if (!$uploader->setConfig($folderConf, $errMsg)) {
  1705. trigger_error("Error: folders config!", E_USER_NOTICE);
  1706. die("Error: folders config!");
  1707. }
  1708. $hasRecordOwnFolder = $uploader->hasRecordOwnFolder();
  1709. $foundTblFiles = array();
  1710. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
  1711. //exec("cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  1712. $filesWithPerms = array();
  1713. $cmd = "cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;";
  1714. exec($cmd, $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  1715. if (!empty($filesWithPerms)) {
  1716. $filesWithPermsTree = array();
  1717. $lastName = '';
  1718. foreach ($filesWithPerms as $line) {
  1719. if (substr($line, 0, 1) == '-') {// file name
  1720. $fileParts = array();
  1721. $filePartsArr = explode(' ', $line);
  1722. $lastInd = 0;
  1723. foreach ($filePartsArr as $vPart) {
  1724. if ($lastInd > 7) {// file name
  1725. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1726. $lastInd++;
  1727. }
  1728. else if (!empty($vPart) || $vPart === '0') {
  1729. $fileParts[] = $vPart;
  1730. $lastInd++;
  1731. }
  1732. }
  1733. $file = new stdClass();
  1734. if (!isset($fileParts[8])) {
  1735. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  1736. //continue;
  1737. }
  1738. $file->name = end($fileParts);
  1739. $file->path = end($fileParts);
  1740. //$file->owner = $fileParts[2];
  1741. //$file->group = $fileParts[3];
  1742. //$file->perms = $fileParts[0];
  1743. $file->isDir = (substr($line, 0, 1) == 'd');
  1744. $file->permsExt = array();
  1745. $filesWithPermsTree[$file->name] = $file;
  1746. $lastName = $file->name;
  1747. }
  1748. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1749. if ($lastName == '..') {
  1750. continue;
  1751. }
  1752. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1753. }
  1754. else {// parse error
  1755. $lastName = '..';
  1756. }
  1757. }
  1758. foreach ($filesWithPermsTree as $vFile) {
  1759. $vFile->path = ltrim($vFile->path, './');
  1760. $vFile->path = explode('/', $vFile->path);
  1761. $vFile->recordFolder = array_shift($vFile->path);// $vFile->projectFolder -> recordFolder
  1762. $vFile->path = implode('/', $vFile->path);
  1763. // TODO: _getTableIdFromFolderName($task->TBL_NAME, $vFile->recordFolder);
  1764. $tblId = 0;
  1765. if ($hasRecordOwnFolder) {
  1766. $tblId = explode('.', $vFile->recordFolder);
  1767. $tblId = reset($tblId);
  1768. }
  1769. else {
  1770. $tblId = explode('.', $vFile->path);
  1771. $tblId = reset($tblId);
  1772. }
  1773. if (is_numeric($tblId) && $tblId > 0) {
  1774. $foundTblFiles[$tblId][] = $vFile;
  1775. }
  1776. }
  1777. }
  1778. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$TBL_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  1779. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundTblFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$TBL_mount_point}\n";print_r($foundTblFiles);echo'</pre>';}
  1780. if (!empty($foundTblFiles)) {
  1781. $rowsIds = array_keys($foundTblFiles);
  1782. $sql = "
  1783. select t.`ID`
  1784. , t.`L_APPOITMENT_USER`
  1785. , t.`A_ADM_COMPANY`
  1786. , t.`A_CLASSIFIED`
  1787. -- , pt.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1788. from `{$task->TBL_NAME}` as t
  1789. -- left join `{$task->TBL_NAME}` as pt on (pt.ID=t.P_ID)
  1790. where t.`ID` in (" . implode(',', $rowsIds) . ")
  1791. ";
  1792. $rows = DB::getPDO()->fetchAll($sql);
  1793. foreach ($rows as $row) {
  1794. $r = (object)$row;
  1795. $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
  1796. foreach ($foundTblFiles[$r->ID] as $vFile) {
  1797. $cmdList = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$vFile->recordFolder}", $r);
  1798. if (!empty($cmdList)) {
  1799. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1800. foreach ($cmdList as $vCmd) {
  1801. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$r->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  1802. exec($vCmd, $out, $outValue);
  1803. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$r->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  1804. if ($outValue != 0) {
  1805. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  1806. }
  1807. }
  1808. } else {
  1809. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
  1810. }
  1811. }
  1812. }
  1813. }
  1814. }
  1815. public function _getRequiredPermsExtByRecord($record) {
  1816. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  1817. $requirePermsExt = array();
  1818. if (!$record->L_APPOITMENT_USER && !$record->A_ADM_COMPANY) {// no owner, no write group
  1819. // TODO: group PODMIOT
  1820. $requirePermsExt["group:workgroup"] = array('write', 'read');
  1821. }
  1822. else {
  1823. if ($record->L_APPOITMENT_USER) {
  1824. if ($this->_isActiveUser($record->L_APPOITMENT_USER)) {
  1825. $requirePermsExt["user:{$record->L_APPOITMENT_USER}"] = array('write', 'read');
  1826. } else {
  1827. // TODO: trigger error $record->L_APPOITMENT_USER is not active user!
  1828. }
  1829. }
  1830. if (!empty($record->A_ADM_COMPANY) && $record->A_ADM_COMPANY == $record->A_CLASSIFIED) {
  1831. $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('read', 'write');
  1832. }
  1833. else if (empty($record->A_ADM_COMPANY) && empty($record->A_CLASSIFIED)) {
  1834. $requirePermsExt["group:workgroup"] = array('write', 'read');
  1835. }
  1836. else {
  1837. if ($record->A_ADM_COMPANY) {
  1838. $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('write');
  1839. }
  1840. if ($record->A_CLASSIFIED) {
  1841. $requirePermsExt["group:{$record->A_CLASSIFIED}"] = array('read');
  1842. }
  1843. }
  1844. }
  1845. // add parent owner
  1846. if (!empty($record->PARENT_L_APPOITMENT_USER) && $record->PARENT_L_APPOITMENT_USER != $record->L_APPOITMENT_USER) {
  1847. if ($this->_isActiveUser($record->PARENT_L_APPOITMENT_USER)) {
  1848. $requirePermsExt["user:{$record->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  1849. } else {
  1850. // TODO: trigger error $record->PARENT_L_APPOITMENT_USER is not active user!
  1851. }
  1852. }
  1853. // add user:_www perms read, write
  1854. $requirePermsExt["user:_www"] = array('write', 'read');
  1855. return $requirePermsExt;
  1856. }
  1857. private function _fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1858. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1859. $cmdList = array();
  1860. $vReqPermsExt = array();
  1861. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1862. $vReqPermsExt[$kPermObj] = array();
  1863. foreach ($vPerms as $vPerm) {
  1864. if ($vFile->isDir) {
  1865. if ($vPerm == 'read') {
  1866. $vReqPermsExt[$kPermObj]['list'] = 0;
  1867. $vReqPermsExt[$kPermObj]['search'] = 0;
  1868. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1869. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1870. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1871. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1872. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1873. }
  1874. else if ($vPerm == 'write') {
  1875. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1876. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1877. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1878. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1879. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1880. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1881. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1882. }
  1883. }
  1884. else {
  1885. if ($vPerm == 'read') {
  1886. $vReqPermsExt[$kPermObj]['read'] = 0;
  1887. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1888. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1889. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1890. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1891. }
  1892. else if ($vPerm == 'write') {
  1893. $vReqPermsExt[$kPermObj]['write'] = 0;
  1894. $vReqPermsExt[$kPermObj]['append'] = 0;
  1895. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1896. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1897. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1898. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1899. }
  1900. }
  1901. }
  1902. }
  1903. $permsToRemove = array();
  1904. foreach ($vFile->permsExt as $vPermExtLine) {
  1905. $vPermExtArr = explode(' ', $vPermExtLine);
  1906. $vPermExt = new stdClass();
  1907. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1908. $vPermExt->permObj = $vPermExtArr[1];
  1909. $vPermExt->perms = '';
  1910. if (count($vPermExtArr) == 4) {
  1911. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1912. }
  1913. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1914. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1915. }
  1916. else {
  1917. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1918. continue;
  1919. }
  1920. $permFound = false;
  1921. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1922. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1923. foreach ($vPerms as $kPerm => $vPermChecked) {
  1924. if (in_array($kPerm, $vPermExt->perms)) {
  1925. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1926. $permFound = true;
  1927. }
  1928. }
  1929. }
  1930. }
  1931. if (!$permFound) {
  1932. $permsToRemove[] = $vPermExt->nr;
  1933. }
  1934. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
  1935. }
  1936. if (!empty($permsToRemove)) {
  1937. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1938. $permsToRemove = array_reverse($permsToRemove);
  1939. foreach ($permsToRemove as $vPermInd) {
  1940. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1941. }
  1942. }
  1943. $permsToAdd = array();
  1944. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1945. foreach ($vPerms as $kPerm => $vPermChecked) {
  1946. if (!$vPermChecked) {
  1947. $permsToAdd[$kPermObj][$kPerm] = 1;
  1948. }
  1949. }
  1950. }
  1951. if (!empty($permsToAdd)) {
  1952. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1953. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1954. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1955. }
  1956. }
  1957. return $cmdList;
  1958. }
  1959. private function _isActiveUser($usrLogin) {
  1960. $activeLoginList = $this->_fetchActiveLoginList();
  1961. return in_array($usrLogin, $activeLoginList);
  1962. }
  1963. public function _fetchActiveLoginList() {
  1964. if (!is_array($this->_activeLoginList)) {
  1965. $this->_activeLoginList = array();
  1966. $sql = "
  1967. select u.`ADM_ACCOUNT`
  1968. from `ADMIN_USERS` as u
  1969. where u.`A_STATUS` = 'NORMAL'
  1970. ";
  1971. $this->_activeLoginList = DB::getPDO()->fetchValuesList($sql);
  1972. }
  1973. return $this->_activeLoginList;
  1974. }
  1975. private function _saveTask($tblName, $tblId, $taskDone = 1, $result = null) {
  1976. $sqlResult = ($result)
  1977. ? " , s.`A_SYNC_RESULT` = " . DB::getPDO()->quote( json_encode($result) )
  1978. : '';
  1979. $sql = "
  1980. update `{$this->_syncTblName}` as s
  1981. set
  1982. s.`A_LAST_SYNC`=NOW()
  1983. , s.`A_SYNCHRONIZED`={$taskDone}
  1984. {$sqlResult}
  1985. where s.`TBL_ID`={$tblId} and s.`TBL_NAME`='{$tblName}'
  1986. ";
  1987. DB::getPDO()->execSql($sql);
  1988. }
  1989. public function executeTask($tblName, $tblId) {
  1990. if (!$this->_tbls) return;
  1991. $task = $this->_getTask($tblName, $tblId);
  1992. if (!$task) return;
  1993. $this->_executeTask($task);
  1994. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1995. return $task;
  1996. }
  1997. public function nextTaskAction($tblName) {
  1998. if (!$this->_tbls) return;
  1999. $task = $this->_getTask($tblName);
  2000. if (!$task) return;
  2001. $this->_executeTask($task);
  2002. /*
  2003. if (isset($task->A_SYNC_RESULT->total)
  2004. && isset($task->A_SYNC_RESULT->lastDone)
  2005. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  2006. ) {
  2007. $this->_saveTask($task->TBL_NAME, $task->TBL_ID, 0, $task->A_SYNC_RESULT);
  2008. } else {
  2009. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  2010. }
  2011. */
  2012. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  2013. return $task;
  2014. }
  2015. private function _getTask($tblName, $tblId = null) {
  2016. $task = null;
  2017. $recordFieldList = $this->_getRecordFieldList($tblName);
  2018. $recordFieldList[] = 'L_APPOITMENT_USER';
  2019. $recordFieldList[] = 'A_ADM_COMPANY';
  2020. $recordFieldList[] = 'A_CLASSIFIED';
  2021. $sqlRecordFields = array();
  2022. foreach ($recordFieldList as $fldName) {
  2023. $sqlRecordFields[] = "t.`{$fldName}` as t__{$fldName}";
  2024. }
  2025. $sqlRecordFields = implode(',', $sqlRecordFields);
  2026. $sqlTblId = "and s.`TBL_ID`!=-1";
  2027. if ($tblId > 0) $sqlTblId = "and s.`TBL_ID`='{$tblId}'";
  2028. $sql = "
  2029. select s.*
  2030. , {$sqlRecordFields}
  2031. -- , pt.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  2032. from `{$this->_syncTblName}` as s
  2033. left join `{$tblName}` as t on(t.`ID`=s.`TBL_ID`)
  2034. -- left join `{$tblName}` as pt on(pt.`ID`=t.`P_ID`)
  2035. where
  2036. s.`TBL_NAME`='{$tblName}'
  2037. {$sqlTblId}
  2038. and s.`A_SYNCHRONIZED`=0
  2039. and s.`A_POMIN_SYNC`=0
  2040. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  2041. limit 1
  2042. ";
  2043. $row = DB::getPDO()->fetchFirst($sql);
  2044. if ($row) {
  2045. $r = (object)$row;
  2046. $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
  2047. $task = $r;
  2048. $task->record = new stdClass();
  2049. foreach ($recordFieldList as $fldName) {
  2050. $aliasFldName = "t__{$fldName}";
  2051. $task->record->{$fldName} = $task->{$aliasFldName};
  2052. unset($task->{$aliasFldName});
  2053. }
  2054. }
  2055. return $task;
  2056. }
  2057. private function _getRecordFieldList($tblName) {
  2058. if (empty($this->_tbls[$tblName])) return;
  2059. $conf = $this->_tbls[$tblName];
  2060. $fldNames = array();
  2061. $fldName = V::get("LOOKAT_FOLDER_VARNAME", '', $conf);
  2062. $fldName = trim($fldName);
  2063. if (!empty($fldName)) $fldNames[$fldName] = true;
  2064. for ($i = 1; $i < 5; $i++) {
  2065. $fldName = V::get("LOOKAT_FOLDER_VARNAME{$i}", '', $conf);
  2066. $fldName = trim($fldName);
  2067. if (!empty($fldName)) $fldNames[$fldName] = true;
  2068. $fldName = V::get("DEST_FOLDER_VARNAME{$i}", '', $conf);
  2069. $fldName = trim($fldName);
  2070. if (!empty($fldName)) $fldNames[$fldName] = true;
  2071. }
  2072. if (!in_array('ID', $fldNames)) {
  2073. $fldNames['ID'] = true;
  2074. }
  2075. return array_keys($fldNames);
  2076. }
  2077. private function _executeTask($task) {
  2078. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
  2079. $DBG_TIME = false;
  2080. $dbgTime = new stdClass();
  2081. $dbgTime->startTime = microtime(true);
  2082. $dbgTime->lastTime = $dbgTime->startTime;
  2083. $confTblName = "{$task->TBL_NAME}_COLUMN";
  2084. $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  2085. $record = $task->record;
  2086. $folderConf = FoldersConfig::getAll($confTblName);
  2087. $uploader = new FileUploader($confTblName, $record);
  2088. $errMsg = '';
  2089. if (!$uploader->setConfig($folderConf, $errMsg)) {
  2090. trigger_error("Error: folders config!", E_USER_NOTICE);
  2091. die("Error: folders config!");
  2092. }
  2093. if ($DBG_TIME) {
  2094. $dbgTime->curTime = microtime(true);
  2095. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-FileUploader->setConfig" . "\n";
  2096. $dbgTime->lastTime = $dbgTime->curTime;
  2097. }
  2098. $uploader->findFolder();
  2099. $mainFolder = $uploader->getDestFolder();
  2100. if ($DBG_TIME) {
  2101. $dbgTime->curTime = microtime(true);
  2102. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]:time after-FileUploader->getDestFolder" . "\n";
  2103. $dbgTime->lastTime = $dbgTime->curTime;
  2104. }
  2105. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
  2106. if (!$mainFolder) {
  2107. $mainFolder = $uploader->generateFolderName();
  2108. $mainFolderPath = rtrim($TBL_mount_point, '/') . '/' . $mainFolder;
  2109. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
  2110. @mkdir($mainFolderPath, 0770, true);
  2111. @chmod($mainFolderPath, 0770);
  2112. if (!file_exists($mainFolderPath)) {
  2113. trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
  2114. return false;
  2115. }
  2116. $requirePermsExt = $this->_getRequiredPermsExtByRecord($record);
  2117. $file = new stdClass();
  2118. $file->name = '.';
  2119. $file->path = '.';
  2120. //$file->owner = '';
  2121. //$file->group = '';
  2122. //$file->perms = '';
  2123. $file->isDir = true;
  2124. $file->permsExt = array();
  2125. $cmdList = $this->_fixFilePerms($file, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $record);
  2126. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$record->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  2127. }
  2128. else {
  2129. $cmdList = $this->_fixRecord($record, $uploader, $mainFolder, $TBL_mount_point, $task);
  2130. }
  2131. if ($DBG_TIME) {
  2132. $dbgTime->curTime = microtime(true);
  2133. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-generate cmdList - mainFolder(" . (($mainFolder)? 1 : 0) . ")" . "\n";
  2134. $dbgTime->lastTime = $dbgTime->curTime;
  2135. }
  2136. if (!empty($cmdList)) {
  2137. foreach ($cmdList as $vCmd) {
  2138. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  2139. exec($vCmd, $out, $outValue);
  2140. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  2141. if ($outValue != 0) {
  2142. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  2143. }
  2144. }
  2145. }
  2146. if ($DBG_TIME) {
  2147. $dbgTime->curTime = microtime(true);
  2148. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-executed cmdList " . "\n";
  2149. $dbgTime->lastTime = $dbgTime->curTime;
  2150. }
  2151. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
  2152. }
  2153. public function _fixRecord($r, $uploader, $mainFolder, $TBL_mount_point, &$task) {
  2154. $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
  2155. $DBG_TIME = false;
  2156. $dbgTime = new stdClass();
  2157. $dbgTime->startTime = microtime(true);
  2158. $dbgTime->lastTime = $dbgTime->startTime;
  2159. $filesWithPerms = array();
  2160. if ($uploader->hasRecordOwnFolder()) {
  2161. $cmd = " ls -Rlea . ";
  2162. $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
  2163. exec($cmd, $filesWithPerms);
  2164. }
  2165. else {
  2166. $lookGlob = $uploader->getFileSearchRegex();
  2167. $cmd = " ls -Rlea {$lookGlob} ";
  2168. $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
  2169. exec($cmd, $filesWithPerms);
  2170. }
  2171. //echo "\n-----------------------\n";
  2172. //echo "filesWithPerms: ";print_r($filesWithPerms);echo "\n";
  2173. if ($DBG_TIME) {
  2174. $dbgTime->curTime = microtime(true);
  2175. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} " . "\n";
  2176. $dbgTime->lastTime = $dbgTime->curTime;
  2177. }
  2178. $filesWithPermsTree = array();
  2179. $lastName = '';
  2180. $folderParent = '';
  2181. foreach ($filesWithPerms as $line) {
  2182. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  2183. $fileParts = array();
  2184. $filePartsArr = explode(' ', $line);
  2185. $lastInd = 0;
  2186. foreach ($filePartsArr as $vPart) {
  2187. if ($lastInd > 7) {// file name
  2188. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  2189. $lastInd++;
  2190. }
  2191. else if (!empty($vPart) || $vPart === '0') {
  2192. $fileParts[] = $vPart;
  2193. $lastInd++;
  2194. }
  2195. }
  2196. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  2197. $lastName = '..';
  2198. continue;
  2199. }
  2200. $file = new stdClass();
  2201. if (!isset($fileParts[8])) {
  2202. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  2203. //continue;
  2204. }
  2205. $file->name = end($fileParts);
  2206. $file->path = array();
  2207. if ($folderParent) $file->path[] = $folderParent;
  2208. $file->path[] = end($fileParts);
  2209. $file->path = implode('/', $file->path);
  2210. //$file->owner = $fileParts[2];
  2211. //$file->group = $fileParts[3];
  2212. //$file->perms = $fileParts[0];
  2213. $file->isDir = (substr($line, 0, 1) == 'd');
  2214. $file->permsExt = array();
  2215. $filesWithPermsTree[$file->name] = $file;
  2216. $lastName = $file;
  2217. }
  2218. else if (substr($line, 0, 1) == ' ') {// extended perm line
  2219. if ($lastName == '..') {
  2220. continue;
  2221. }
  2222. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  2223. }
  2224. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  2225. $folderParent = substr($line, 2, -1);
  2226. }
  2227. else if (substr($line, 0, 5) == 'total') {
  2228. continue;
  2229. }
  2230. else if (empty($line)) {
  2231. $folderParent = '';
  2232. continue;
  2233. }
  2234. }
  2235. //echo "filesWithPermsTree: ";print_r($filesWithPermsTree);echo "\n";
  2236. if ($DBG_TIME) {
  2237. $dbgTime->curTime = microtime(true);
  2238. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: parse cmd output" . "\n";
  2239. $dbgTime->lastTime = $dbgTime->curTime;
  2240. }
  2241. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
  2242. // check perms
  2243. /*
  2244. files:
  2245. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  2246. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  2247. R read, execute, readattr, readextattr, readsecurity
  2248. dir:
  2249. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  2250. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  2251. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  2252. */
  2253. $cmdList = array();
  2254. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  2255. if (false) {
  2256. // TODO: $kFileName == '_PISMA' - readonly
  2257. // TODO: $vFile->path => _PISMA/...
  2258. }
  2259. else {
  2260. $cmdFile = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $r);
  2261. if (!empty($cmdFile)) {
  2262. foreach ($cmdFile as $vCmd) {
  2263. $cmdList[] = $vCmd;
  2264. }
  2265. }
  2266. }
  2267. }
  2268. //echo "cmdList: ";print_r($cmdList);echo "\n";
  2269. //echo "\n-----------------------\n";
  2270. if ($DBG_TIME) {
  2271. $dbgTime->curTime = microtime(true);
  2272. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: end" . "\n";
  2273. $dbgTime->lastTime = $dbgTime->curTime;
  2274. }
  2275. return $cmdList;
  2276. }
  2277. }
  2278. ?>