bash_sync_perms.php 94 KB

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