bash_sync_perms.php 95 KB

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