bash_sync_perms.php 95 KB

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