bash_sync_perms.php 96 KB

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